-
Notifications
You must be signed in to change notification settings - Fork 14
Tutorial 02 15 Adding Create Endpoints

Create operations are invoked when a client sends an HTTP POST request to the main collection endpoint of an entity, and cause a new entity to be created. The primary key value for the new entity will be automatically assigned by custom code that you must provide.
When performing an HTTP POST there are several requirements that the client must comply with in order for a new entity to be created. The client must:
-
Include in the body of the HTTP request the data representing the new entity, in JSON format, excluding primary key information, but including at least valid data any other required fields.
-
Include an HTTP request header named
Content-Typethat identifies the type of data being sent in the request body as being of typeapplication/json. -
Include an HTTP request header named
Content-Lengththat specifies the length of the data (in bytes) being sent in the request body. Note that some client tools, including Postman, will add this header automatically based on the data you pass.
If you need to create a new entity but have the primary key value for the new entity provided by the client, use an Upsert operation instead.
IMPORTANT: Before enabling create endpoints you MUST have completed both the Postman Tests and Adding a Primary Key Factory topics.
To generate endpoints that allow clients to create new entities via POST operations you must enable the ENABLE_POST option:
-
Edit
regen.batand remove the rem comment from the beginning of the line, like this:set ENABLE_POST=-define ENABLE_POST
-
Save your changes to
regen.bat. -
If you don't already have a command prompt open in the solution folder, use the
Tools > Command Prompt (x64)menu option to open a Windows command prompt, and type the following command:cd .. -
Type the following command to regenerate your code:
regen
As the batch file executes you will see various messages confirming which source files are being generated.
- Look for the word
DONEto indicate that all code generation tasks completed successfully.
Enabling the ENABLE_POST option causes an additional endpoint method to be added to each of the generated OData Controller classes. The new method, with most of the code removed from the procedure division, looks something like this:
{ODataRoute}
{Produces("application/json")}
{ProducesResponseType(^typeof(Customer),StatusCodes.Status200OK)}
{ProducesResponseType(StatusCodes.Status400BadRequest)}
{HttpPost}
;;; <summary>
;;; Create a new customer (automatically assigned primary key).
;;; </summary>
;;; <returns>Returns an IActionResult indicating the status of the operation and containing any data that was returned.</returns>
public method PostCustomer, @IActionResult
{FromBody}
required in aCustomer, @Customer
proc
;;Remove the primary key fields from ModelState
ModelState.Remove("CustomerNumber")
endmethod
The sample code above was taken from CustomersController.dbl, and as you can see the code accepts a single customer object containing that contains the data for the customer to be created. Notice that the aCustomer parameter is decorated with an attribute {FromBody}, indicating that the data must be provided via the body of the HTTP request.
The one line of code that we left in the procedure division is, in this example ModelState.Remove("CustomerNumber"). This code ensures that any primary key value provided by the client is removed. Remember that with POST operations the primary key will be provided by the custom primary key factory class.
You will find similar new code in all of your other controllers.
If you are generating Postman Tests then a new POST request is added to the folder for each entity type, but you will need to re-import the newly generated tests into Postman. The instructions will walk you through doing this later.
-
Select
Build > Rebuild Solutionfrom the Visual Studio menu. -
Check the
Outputwindow, you should see something like this:1>------ Rebuild All started: Project: Repository, Configuration: Debug Any CPU ------ 2>------ Rebuild All started: Project: Services.Models, Configuration: Debug Any CPU ------ 3>------ Rebuild All started: Project: Services.Controllers, Configuration: Debug Any CPU ------ 4>------ Rebuild All started: Project: Services.Isolated, Configuration: Debug Any CPU ------ 5>------ Rebuild All started: Project: Services, Configuration: Debug Any CPU ------ 6>------ Rebuild All started: Project: Services.Host, Configuration: Debug Any CPU ------ ========== Rebuild All: 6 succeeded, 0 failed, 0 skipped ==========
- In Visual Studio, press
F5(start debugging) to start the self-hosting application. Once again you should see the console window appear, with the messages confirming that your service is running.
It is not possible to test the functionality of the new endpoints using a web browser, because the functionality to be tested involves issuing an HTTP POST request. Browsers can issue POST requests, but only via the use of an HTML form or some client-side JavaScript code. So you will need to use some other tool, and our tool of choice is Postman.
-
Start
Postmanand close any request tabs that may be open. -
Select
File > Importfrom the Postman menu. -
In the
IMPORTdialog, click theUpload Filesbutton. -
Browse to your main solution folder, select the
PostManTests.postman_collection.jsonfile, then click theOpenbutton. -
Back in the
IMPORTdialog, click theImportbutton. -
In the
COLLECTION EXISTSdialog, click theReplacebutton.
Postman will now re-load the tests in the Harmony Core Sample API collection, and you will notice that the total number of tests increases.
- Open the
Customer Testsfolder and select thePOST Create Customer (auto assign key)request.
You will notice that:
- The HTTP method is set to
POST. - The URL is set to
{{ServerBaseUri}}/Customers - Click on the
Headerstab and you will see that theContent-Typeheader is set toapplication/json - Click on the
Bodytab and you will see that the request contains JSON data for a sample customer.
The JSON data does include a CustomerNumber property, but as mentioned earlier, this value will be discarded and replaced with a server-generated value. Remove the property from the data if you wish.
- Click the big blue
Sendbutton.
Postman will again execute the request, wait for a response, parse the response, and display the details of the response in the UI. You should see that the response body looks something like this:

Notice that the primary key of the entity that was created was set on the server side, likely to a value of 39. Remember that the data in the sample environment is reset to a known state each time you start the service, which you just did.
- In the response tab-set, click on the
Headerstab, you should see something like this:

Notice that amongst the various HTTP headers that were returned by the service is a header named Location, the value of which is the URL that can be used to retrieve the newly created entity. This behavior is defined as part of the REST pattern.
- Click the big blue
Sendbutton again.
You just created another new customer, and you should notice that the customer number was incremented again.
- Click on the
GET Read Customerrequest and change the parameter value in the URL to a value of39before clicking the big blueSendbutton.
You should see that the GET endpoint was able to retrieve the entity that you just created.
- When you are done with your testing, stop the self-hosting application.
Enabling create endpoints adds endpoints to all of your code generated OData Controllers, but it is possible to prevent the generation of these endpoints for certain structures. This capability is documented in structure specific endpoint control.
Next topic: Adding Upsert Endpoints
-
Tutorial 2: Building a Service from Scratch
- Creating a Basic Solution
- Enabling OData Support
- Configuring Self Hosting
- Entity Collection Endpoints
- API Documentation
- Single Entity Endpoints
- OData Query Support
- Alternate Key Endpoints
- Expanding Relations
- Postman Tests
- Supporting CRUD Operations
- Adding a Primary Key Factory
- Adding Create Endpoints
- Adding Upsert Endpoints
- Adding Patch Endpoints
- Adding Delete Endpoints
-
Harmony Core CLI Tool
-
OData Aware Tools
-
Advanced Topics
- CLI Tool Customization
- Adapters
- API Versioning
- Authentication
- Authorization
- Collection Counts
- Customization File
- Custom Field Types
- Custom File Specs
- Custom Properties
- Customizing Generated Code
- Deploying to Linux
- Dynamic Call Protocol
- Environment Variables
- Field Security
- File I/O
- Improving AppSettings Processing
- Logging
- Optimistic Concurrency
- Multi-Tenancy
- Publishing in IIS
- Repeatable Unit Tests
- Stored Procedure Routing
- Suppressing OData Metadata
- Traditional Bridge
- Unit Testing
- EF Core Optimization
- Updating a Harmony Core Solution
- Updating to 3.1.90
- Creating a new Release
-
Background Information
