Skip to content

Tutorial 02 15 Adding Create Endpoints

Steve Ives edited this page May 19, 2020 · 12 revisions

Harmony Core Logo

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.

VIDEO: Creating a Basic Solution

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-Type that identifies the type of data being sent in the request body as being of type application/json.

  • Include an HTTP request header named Content-Length that 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.

Enabling Create Endpoints


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:

  1. Edit regen.bat and remove the rem comment from the beginning of the line, like this:

    set ENABLE_POST=-define ENABLE_POST
    

Generating the Code

  1. Save your changes to regen.bat.

  2. 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 ..
    
  3. 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.

  1. Look for the word DONE to indicate that all code generation tasks completed successfully.

What Changed

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.

Building the Code

  1. Select Build > Rebuild Solution from the Visual Studio menu.

  2. Check the Output window, 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 ==========
    

Testing the New Functionality

  1. 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.

  1. Start Postman and close any request tabs that may be open.

  2. Select File > Import from the Postman menu.

  3. In the IMPORT dialog, click the Upload Files button.

  4. Browse to your main solution folder, select the PostManTests.postman_collection.json file, then click the Open button.

  5. Back in the IMPORT dialog, click the Import button.

  6. In the COLLECTION EXISTS dialog, click the Replace button.

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.

  1. Open the Customer Tests folder and select the POST 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 Headers tab and you will see that the Content-Type header is set to application/json
  • Click on the Body tab 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.

  1. Click the big blue Send button.

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:

Post Response Body

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.

  1. In the response tab-set, click on the Headers tab, you should see something like this:

Post Response Headers

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.

  1. Click the big blue Send button again.

You just created another new customer, and you should notice that the customer number was incremented again.

  1. Click on the GET Read Customer request and change the parameter value in the URL to a value of 39 before clicking the big blue Send button.

You should see that the GET endpoint was able to retrieve the entity that you just created.

Stop the Service

  1. When you are done with your testing, stop the self-hosting application.

Suppressing Create Endpoints

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


Clone this wiki locally