Search code examples
jsonvbscriptasp-classicwinhttprequest

Problem adding JSON content to WinHttpRequest POST request in classic ASP


I am trying to retrieve data using an NHS API and the instructions are as follows...

Endpoint        https://api.nhs.uk/service-search/search?api-version=1
Method      POST
Headers     Content-Type: application/json
subscription-key: MYKEYHERE
Body        {
    "filter": "OrganisationTypeID eq 'PHA'",
    "orderby": "OrganisationName",
    "top": 25,
    "skip": 0,
    "count": true
}

Following the answer here How can I post data using cURL in asp classic? I tried this...

<%
Dim http: Set http = Server.CreateObject("WinHttp.WinHttpRequest.5.1")
StrFilter = "OrganisationTypeID eq 'PHA'"
StrFilter = Server.UrlEncode(StrFilter)
Dim url: url = "https://api.nhs.uk/service-search/search?api-version=1"
Dim data: data = "filter=" & StrFilter & "&orderby=OrganisationName&top=25&skip=0&count=true"
With http
  Call .Open("POST", url, False)
  Call .SetRequestHeader("subscription-key", "MYKEYHERE")
  Call .SetRequestHeader("Content-Type", "application/json")
  Call .Send(data)
End With
If Left(http.Status, 1) = 2 Then
  'Request succeeded with a HTTP 2xx response, do something...
  Response.Write http.responseText
Else
  'Output error
  Call Response.Write("Server returned: " & http.Status & " " & http.StatusText)
End If
%>

...but this gives me "Server returned: 400 Bad Request". It's almost certainly a case of me not knowing how to do this properly. Where am I going wrong? Thanks


Solution

  • The issue is the API expects an application/json body, so you need to pass that instead of application/x-www-form-urlencoded data.

    You can build the JSON up as a string but it needs to conform to a JSON structure or you will likely get an HTTP 400 Bad Request again.

    Replace data with;

    Dim data: data = "{ ""filter"": ""OrganisationTypeID eq 'PHA'"", ""orderby"": ""OrganisationName"", ""top"": 25, ""skip"": 0, ""count"": true }"
    

    You could also use some existing libraries to build and parse JSON for you.

    Personally I'd recommend - JSON object class by RCDMK