Azure APIM JSON Conversion
February 11, 2023 Leave a comment
This week I was working on an Azure Function Web Hook to receive data from a third party service.
The service I was receiving the data from was a little limited in that all I could provide was an endpoint where the data would be posted, and an example of how the data would be formatted.
{
“cc”: [],
“completed_at”: null,
“cost”: null,
“direction”: “inbound”,
“encoding”: “GSM-7”,
“errors”: [],
“from”: {
“carrier”: “”,
“line_type”: “”,
“phone_number”: “+44123456789”
},
“id”: “22737cb8-39d3-42a9-aded-12c0c0c93f80”,
“media”: [],
“messaging_profile_id”: “xxxx-xxxx-xxxxx-xxxxx”,
“organization_id”: “xxxx-xxxxx-xxxxx-xxxx”,
“parts”: 1,
“received_at”: “2023-02-07T12:57:44.753+00:00”,
“record_type”: “message”,
“sent_at”: null,
“subject”: “”,
“tags”: [],
“text”: “Test 2”,
“to”: [
{
“carrier”: “phone service”,
“line_type”: “Wireless”,
“phone_number”: “+441234567890”,
“status”: “webhook_delivered”
}
],
“type”: “SMS”,
“valid_until”: null,
“webhook_failover_url”: null,
“webhook_url”: “my webhook url”
}
In testing my function in PowerShell on my laptop, everything worked as expected, the simulated JSON data I provided was parsed and the result was as expected.
Once I published the function and linked it to the Azure APIM service, I did another test from PowerShell and as everything worked, I confirmed the URL with the third party api and sent a test message.
Unfortunately, it didn’t work. The request was received, the function executed but nothing happened.
A very long story short, I added some output to the function to see the content of the data the third part was sending, and also, crucially, the headers they were sending.
As it turned out, the content type header was not specified as “application/json“, but rather “application/www-urlencoded“. What this means, is that when Azure receives the data it is not automatically parsed, and you need to rely on your own parser to get the JSON data formatted correctly.
The solution was so simple I couldn’t believe it took me so long to find it.
In Azure APIM there is a section under either your post or get requests, where you can supply a policy. One of the aspects of the policy is overriding headers.
So, by added my own Content Type header, for application/json and setting it to override, the data arriving at my function was parsed for me, and I could then access the data for further processing.
Hopefully will save someone some time!