Create a Web API
Last Updated: December 2023
This tutorial teaches how to create an ASP.NET Core Web API in SnapDevelop.
In this tutorial, you learn how to:
- Create a Web API Project
- Inject DataContext and Service
- Run and Test the Web APIs
- Call the Web APIs from PowerBuilder
The following diagram shows the high-level design of a Web API.
When the client app sends a user request (an URL) to the Web API, the API controller class handles the request and calls the method in the service class to perform the business logics and data operations.
- Controller is responsible for initial processing of the request and returning the processing result. A controller does not include data access or business logic; it invokes services to perform data operations and business logic.
- Service is responsible for retrieving and creating data models from data sources, executing application logic and operations, etc. Services are where the core business logic resides. A service typically separates its interface from the implementation of that interface.
These concepts will be covered later in this tutorial.
Prerequisites
Installing the sample database
To install the sample database used in this tutorial, follow these steps:
Install SQL Server Express or SQL Server 2012 or later.
Download the database backup file (AdventureWorks_for_sqlserver.zip) from https://github.com/Appeon/.NET-Project-Example-Database.
Restore the database using the downloaded database backup file.
For how to restore the database, you can refer to the readme file: https://github.com/Appeon/.NET-Project-Example-Database/blob/master/README.md.
Configuring the network environment
The projects used in this tutorial need to download the required dependency packages from NuGet site, so make sure the current machine can connect to the Internet.
If you are connecting to the Internet through a proxy, first make sure that the proxy is working properly and that the NuGet site is not excluded from the exception list. If the network connection is normal, but SnapDevelop still prompts a network connection error, please restart the SnapDevelop IDE and then try again.
Create a Web API Project
Start SnapDevelop and select Create New Project from the Welcome page. Or, from the File menu, select New and then New Project...
Step 1: In the New Project dialog, select ASP.NET Core Web API from the project templates options, and then click Next.
Step 2: Specify the project name as WebAPI1 and click Next.
Step 3: Select Basic from the Type drop-down list and click Create.
If you have changed the settings on this screen, they will be used as default settings for the next project.
- Type -- The following types can be selected:
- Basic -- Creates a standard ASP.NET Core application. The application includes a sample controller for building a RESTful HTTP service.
- DataStore -- Creates a standard ASP.NET Core application. The application includes samples of using the .NET DataStore model, controller, and service for building RESTful HTTP services.
- SqlModelMapper -- Creates a standard ASP.NET Core application. The application includes samples of using the SqlModelMapper model, controller, and service for building RESTful HTTP services.
- Target Framework -- The .NET version the project is targeting. Although only the latest frameworks are listed here (because it is recommended to use the latest framework when creating a project), SnapDevelop is compatible with projects of different frameworks. Multiple projects in the same solution can target different .NET versions. After the project is created, the target framework can be modified in the project properties page.
- Authentication Type -- The authentication method to use in the application.
- Configure for HTTPS -- When this option is enabled, an HTTPS URL and port will be automatically assigned to the Web API service. You can change the HTTPS URL and port in your project's launchSettings.json file.
- Enable Docker -- When this option is enabled, the files and configurations required for Docker support will be automatically added to the project.
- Docker OS -- The operating system of the Docker runtime environment: Windows or Linux.
- Use Controller -- (Basic only) When this option is enabled, the controller will be generated automatically, otherwise the controller will not be generated.
- Enable OpenAPI Support -- When this option is enabled, the Swagger UI generator will be automatically added to the Program.cs file in the project, and the middleware will be downloaded and enabled so that you can access the Swagger UI page to try out the API directly during the development phase.
A template API is created from the project template. The Web API project contains the following folders and files by default:
Step 4: Select menu View > DB Server Explorer.
Step 5: In DB Server Explorer, click Connect to database to create a new connection.
Step 6: Enter the connection information for the database. Click Test Connection. Make sure the test connection is successful. Click OK.
You will see the connection listed in DB Server Explorer.
Step 7: Expand the connection, right click a table and then select SqlModelMapper.
Step 8: Set Model Directory to use the root directory. Use the default values for the other settings. Click OK.
SnapDevelop will convert the selected table into the entity class model and the database context according to the database type.
- AdventureWorks2012DataContext.cs: This is the database context that manages database connections and transactions. The connection string is saved in
appsettings.json
. - Department.cs: This is the entity class model converted from a database table. It maps to the table
HumanResources.Department
in the AdventureWorks2012 database.
Now you can use the scaffolding feature to generate the controller and service (including implementation and interface) files from the model.
Step 9: Right click the model and then select Scaffolding > Scaffold Service and Controller from Model.
Step 10: Modify Model to SqlModelMapper. Use the default values for the other settings. Click Generate.
Step 11: When you are prompted to install the NuGet package, click Yes to confirm the install.
After the package is installed, the controller and service (including implementation and interface) files are generated in the project, and simple CRUD methods are automatically implemented in the controller file.
Services folder: This folder contains the service which performs the data operations on the data model.
\IDepartmentService.cs: This service defines the
IDepartmentService
interface which contains the declaration of the following methods. All of these methods are declared with parameter(s) and return type only, but with an empty body, as shown below:public interface IDepartmentService : IServiceBase<Department> { Task<Department> RetrieveOneAsync(short departmentid, CancellationToken cancellationToken); Task<IList<Department>> RetrieveAsync(CancellationToken cancellationToken); Task<int> UpdateAsync(Department Department, CancellationToken cancellationToken); Task<int> DeleteAsync(short departmentid, CancellationToken cancellationToken); }
\Impl\DepartmentService.cs: This service provides the implementation of the IDepartmentService interface. It contains the actual definition of the methods declared in the interface.
Take the
RetrieveOneAsync
method in DepartmentService.cs for example. It retrieves one data row from the database according to the specified departmentid, and returns the retrieved data in an instance of theDepartment
data model.public async Task<Department> RetrieveOneAsync(short departmentid, CancellationToken cancellationToken) { var result = await _dataContext.SqlModelMapper.LoadByKeyAsync<Department>(new object[] { departmentid }, cancellationToken); return result.FirstOrDefault(); }
Controllers\DepartmentController.cs: This controller is based on the DepartmentService service. It defines the routing format, the HTTP method, and the action methods corresponding to the service.
[Route("api/[controller]/[action]")]
[controller]
will be automatically replaced with the name of the controller, which by convention is the controller class name minus the "Controller" suffix. For this sample, the controller class name is DepartmentController, so the controller name is "Department".[action]
will be automatically replaced with the name of the action method in the controller. For example, appendingapi/department/retrieveone/{departmentid}
to the base URL would cause theRetrieveOneAsync
action method in theDepartmentController
class to run.//GET api/Department/RetrieveOne/{departmentid} [HttpGet("{departmentid}")] [ProducesResponseType(typeof(Department), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task<ActionResult<Department>> RetrieveOneAsync(short departmentid) { try { var result = await _idepartmentservice.RetrieveOneAsync(departmentid, default); return Ok(result); } catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } }
The [HttpGet] attribute denotes a method that responds to an HTTP GET request.
"{departmentid}"
is a placeholder variable for the unique identifier of the department. Whenretrieveoneasync
is invoked, the value of"{departmentid}"
in the URL is provided to the method in itsdepartmentid
parameter.
Inject DataContext and Service
Inject the DataContext and the Service to the project.
Step 1: Open the Program.cs file.
Step 2: Right-click where you want to insert the code and then select Inject DataContext. In the Inject DataContext(s) dialog box, make sure WebAPI1 and AdventureWorks2012DataContext are selected and click OK.
Step 3: Right-click where you want to insert the code and then select Inject Service. In the Inject Service(s) dialog box, make sure WebAPI1 and DepartmentService are selected and click OK.
After that, the following using
statements and scripts are automatically inserted:
Run and Test the Web APIs
Run the Web APIs
Let's run the Web API and see what interfaces it provides.
Press Ctrl + F5 in the SnapDevelop IDE (or click the Start Without Debugging icon in the toolbar). SnapDevelop will compile the Web API project, start the Web API service, and display the Web API's Swagger UI in the browser. You can use the Enable OpenAPI Support option to decide whether to generate Swagger UI pages during the process of creating a Web API project. Swagger is commonly used to generate documentation and help pages for Web APIs. For more information on Swagger, please refer to https://swagger.io/.
The Swagger page of the Web API shows all the interfaces provided in the Web API. You can expand and try out each interface (click Try it Out ).
For example, expand the GET/api/Address/{id}
interface, click the Try it Out button, enter the number 1 in the departmentid parameter box, and click the Execute button.
The page will return:
- The Curl commands for testing this interface.
- The request URL for testing the interface.
- HTTP response status code, body and headers.
If you replace the Swagger path with the API path in the URL, for example, https://localhost:7128/api/Department/RetrieveOne/1
, the page will return a JSON string like the following.
Test the Web APIs
Select Web API Tester from the Test menu.
In the Web API Tester, expand the list of tests and double-click the RetrieveOneAsync(Int16 departmentid)
method under DepartmentController. Then enter 1 as the value for departmentid on the right and click Send. The returned data is displayed in the JSON string format in the Body panel.
For more information on Web API Tester, visit the tutorial Testing with Web API Tester.
Call the Web APIs from PowerBuilder
In this section, we create a PowerBuilder app as the client app to access the Web APIs.
Step 1: Add a DataWindow
In this example, a traditional PowerBuilder DataWindow will be created.
Start PowerBuilder and create a template application with no database connection. Then add a Grid DataWindow that maps to the table
HumanResources.Department
in the AdventureWorks2012 database. Save the DataWindow object with the name d_department.Add a DataWindow control to a window. Set its Name to dw_department and DataObject to d_department. And add a Retrieve button for the retrieval operation.
Step 2: Retrieve Data to the DataWindow
The PowerBuilder RESTClient
object provides the ability to access the RESTful Web APIs. It can load the JSON-formatted string returned from the RESTful Web Service APIs into the DataWindow object.
- In the Declare Instance Variables of your window, add an instance variable of the RESTClient object:
RESTClient inv_RestClient
- In the open event of your window, create the object variable:
// Create the RESTClient object variable
inv_RestClient = CREATE RESTClient
- In the clicked event of the Retrieve button, add the
RESTClient.RetrieveOne()
method to call the Web API and load the data directly into the DataWindow. If you retrieve more than one row, useRESTClient.Retrieve()
instead.
// Retrieve the DW using the RESTClient
inv_RestClient.RetrieveOne(dw_department, "https://localhost:7128/api/Department/RetrieveOne/1")
- Now you can run the PowerBuilder application, and click Retrieve to retrieve data via the Web API. (Note: Your Web API needs to be running.)