Vijayanath Viswanathan
Vijayanath Viswanathan

Reputation: 8561

HTTP Patch in azure function

I am looking a way to implement proper HTTP Path in Azure function. I have found examples which are checking for null of each of the property and adding it to the entity to PATCH. I found this is not ideal but just a workaround. The only signature I found for HTTP triggered function(v2) is,

public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "HTTP VERB", Route = "")] HttpRequest req,
     ILogger log)
    {
    }

Instead of this I need to pass "JsonPatchDocument" and the client would be able to pass PATCH document as below,

public async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "PATCH", Route = "")] **JsonPatchDocument<Customer> patch**,
 ILogger log)
{
}

PATCH /api/customer
[
    {
      "op": "replace",
      "path": "/firstname",
      "value": "Vijay"
    },
    {
      "op": "replace",
      "path": "/email",
      "value": "[email protected]"
    },
]

so that I can use "patch.ApplyTo()" to path the properties. Is it possible to do in azure function?

Upvotes: 2

Views: 3585

Answers (1)

Vijayanath Viswanathan
Vijayanath Viswanathan

Reputation: 8561

I found a solution for this. I couldn't pass "JsonPatchDcument" type to azure function but I could parse the request body to JsonPatchDocument as below,

FunctionName("PatchInstitute")]
    public async Task<IActionResult> PatchInstitute(
        [HttpTrigger(AuthorizationLevel.Anonymous, "patch", Route = ApiConstants.BaseRoute + "/institute/{instituteId}")] HttpRequest req,
        ILogger log, [Inject]IInstituteValidator instituteValidator, int instituteId, [Inject] IInstituteProvider instituteProvider)
    {
        try
        {
           //get existing record with Id here
            var instituteDto = instituteProvider.GetInstitueProfileById(instituteId);



            using (StreamReader streamReader = new StreamReader(req.Body))
            {
                var requestBody = await streamReader.ReadToEndAsync();

                //Deserialize bosy to strongly typed JsonPatchDocument
                JsonPatchDocument<InstituteDto> jsonPatchDocument = JsonConvert.DeserializeObject<JsonPatchDocument<InstituteDto>>(requestBody);

                //Apply patch here
                jsonPatchDocument.ApplyTo(instituteDto);

                //Apply the change
                instituteProvider.UpdateInstitute(instituteDto);

            }

            return new OkResult();

        }
        catch (Exception ex)
        {
            log.LogError(ex.ToString());
           // return Generic Exception here
        }
    }

And JsonPathDocument to pass from client would looks like below,

[
    {
      "op": "replace",
      "path": "/isActive",
      "value": "true"
    }
]

Here you can pass whatever the fields to update (patch)

Upvotes: 7

Related Questions