Skip to content

Tutorial 02 17 Adding Patch Endpoints

mattl91 edited this page Oct 21, 2022 · 12 revisions

Harmony Core Logo

Adding Patch Endpoints

The term Patch is used to describe an operation where an entity is partially updated.

VIDEO: Creating a Basic Solution

In Harmony Core, as in many other RESTful web service implementations, an HTTP PATCH operation is used to perform a patch operation for an entity.

When performing an HTTP PATCH there are several requirements that the client must comply with in order for an entity to be patched. The client must:

  • Include in the body of the HTTP request a valid JSON Patch Document that describes one or more changes that are to be applied to an existing entity

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

Enabling Patch Endpoints

To generate endpoints that allow clients to patch entities via HTTP PATCH operations, you must enable the ENABLE_PATCH option:

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

    set ENABLE_PATCH=-define ENABLE_PATCH
    

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_PATCH 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:

        {HttpPatch("Customers(CustomerNumber={aCustomerNumber})")}
        {Produces("application/json")}
        {ProducesResponseType(StatusCodes.Status204NoContent)}
        {ProducesResponseType(StatusCodes.Status400BadRequest)}
        {ProducesResponseType(StatusCodes.Status404NotFound)}
        ;;; <summary>
        ;;; Patch  (partial update) a customer.
        ;;; </summary>
        ;;; <param name="aCustomerNumber">Customer number</param>
        ;;; <returns>Returns an IActionResult indicating the status of the operation and containing any data that was returned.</returns>
        public method PatchCustomer, @IActionResult
            {FromODataUri}
            required in aCustomerNumber, int
            {FromBody}
            required in aCustomer, @JsonPatchDocument<Customer>
        proc
            ;; Validate inbound data
            if (!ModelState.IsValid)
                mreturn ValidationHelper.ReturnValidationError(ModelState)



    mreturn NoContent()

endmethod

The sample code above was taken from CustomersController.dbl, and as you can see, the code accepts two parameters:

  • A parameter named aCustomerNumber which is the primary key value for the entity to be patched.

    • Notice that the parameter is decorated with an attribute {FromODataUri}, indicating that the data must be provided via a URL parameter of the HTTP request.
  • A parameter named aCustomer which is a JSON Patch Document of type customer, containing the change instructions that are to be applied to the existing customer entity.

    • Notice that the parameter is decorated with an attribute {FromBody}, indicating that the patch document must be provided via the body of the HTTP request.

The little bit of code that we left in the procedure division does two things:

  • It checks the value of ModelState.IsValid, and if it's false, it returns an error.

    • Code that has already executed in the ASP.NET Core pipeline has already inspected the inbound data from the client, and if that data is determined to be invalid for any reason, then ModelState.IsValid is set to false. By returning ValidationHelper.ReturnValidationError(ModelState), we ensure that the client will receive an HTTP 400 (bad request) response, and also that information about the invalid data will be included in the body of the response to the client.
  • On successful completion a NoContent() response is returned. This will result in an HTTP 204 (no content) response to the client.

You will find similar new code in all of your other controllers.

If you are generating Postman Tests, a new PATCH 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 PATCH request. Our tool of choice for issuing PATCH requests 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 Choose Files button.

  4. Browse to your main solution folder, select the PostMan_ODataTests.postman_collection file, and 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 PATCH Patch customer request.

You will notice that:

  • The HTTP method is set to PATCH.

  • The URL is set to {{ServerBaseUri}}/{{ODataPath}}/v{{ApiVersion}}/Customers(CustomerNumber=123).

  • 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 a sample JSON patch document.

    [
      {
        "op": "replace",
        "path": "PropertyName",
        "value": "PropertyValue"
      }
    ]
    
  1. Change the value of the CustomerNumber parameter in the URL to 1.

  2. In the request body, change the JSON patch document so that it looks like this:

   [
     {
       "op": "replace",
       "path": "Street",
       "value": "123 Main St."
     },
     {
       "op": "replace",
       "path": "City",
       "value": "Roseville"
     },
     {
       "op": "replace",
       "path": "ZipCode",
       "value": "95747"
     }
   ]

First, let's examine the current data for customer 1.

  1. Select the GET Read Customer request, change the value of the CustomerNumber parameter in the URL to 1 and click the big blue Send button.

You should see that customer 1 currently looks like this:

{
    "@odata.context": "https://localhost:8086/odata/v1/$metadata#Customers/$entity",
    "@odata.etag": "W/\"YmluYXJ5J0FDQUFBQUFBNHhsU3FRPT0n\"",
    "CustomerNumber": 1,
    "Name": "San Pablo Nursery",
    "Street": "1324 San Pablo Dam Road",
    "City": "San Pablo",
    "State": "CA",
    "ZipCode": 94806,
    "Contact": "Karen Graham",
    "Phone": "(555) 912-2341",
    "Fax": "(555) 912-2342",
    "FavoriteItem": 13,
    "PaymentTermsCode": "01",
    "TaxId": 559244251,
    "CreditLimit": 2000.00,
    "GlobalRFA": "ACAAAAAA4xlSqQ=="
}
  1. Now switch back to the PATCH Patch customer request and click the big blue Send button.

You should see a response of '204 No Content', indicating a successful PATCH.

  1. Once again, select the GET Read Customer request and click the big blue Send button.

You should see that customer 1 now looks like this:

{
    "@odata.context": "https://localhost:8086/odata/v1/$metadata#Customers/$entity",
    "@odata.etag": "W/\"YmluYXJ5J0FDQUFBQUFBdHRqVXh3PT0n\"",
    "CustomerNumber": 1,
    "Name": "San Pablo Nursery",
    "Street": "123 Main St.",
    "City": "Roseville",
    "State": "CA",
    "ZipCode": 95747,
    "Contact": "Karen Graham",
    "Phone": "(555) 912-2341",
    "Fax": "(555) 912-2342",
    "FavoriteItem": 13,
    "PaymentTermsCode": "01",
    "TaxId": 559244251,
    "CreditLimit": 2000.00,
    "GlobalRFA": "ACAAAAAAttjUxw=="
}

Notice that the values of the Street, City, and ZipCode properties have been patched to the values you provided.

Stop the Service

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

Suppressing Patch Endpoints

Enabling patch 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 Delete Endpoints


Clone this wiki locally