This blog post describes a general procedure for writing code that calls an HTTP/HTTPS GET REST API and parses the JSON or XML response.

Step 1: Form the CURL Command

A GET request in the form of a CURL command will look like this:

curl -X GET https://test-api.service.hmrc.gov.uk/organisations/vat/123456789/obligations \
-H "Accept: application/vnd.hmrc.1.0+json"  \
-H "Authorization: Bearer hmrc_app_server_token"

Some notes:

  • Header fields are added using the “-H” option.  Add the header fields and values as required by your particular REST API.
  • If OAuth2 authentication is required, the OAuth2 access token is provided in an “Authorization: Bearer …” header field.
  • If HTTP Basic authentication is required, which means providing a username/password, then use the –user option like this:
    --user username:password
    
  • Query params are added in the URL and should appear just as they would in a browser address bar.

Step 2. If the REST API GET returns JSON or XML, get a representative sample of the JSON or XML response.  For example:

{
  "obligations": [
    {
      "start": "2017-01-01",
      "end": "2017-03-31",
      "due": "2017-05-07",
      "status": "F",
      "periodKey": "18A1",
      "received": "2017-05-06"
    },
    {
      "start": "2017-04-01",
      "end": "2017-06-30",
      "due": "2017-08-07",
      "status": "O",
      "periodKey": "18A2"
    }
  ]
}

Step 3.  Generate Code

Go to the online tool at http://tools.chilkat.io/curl.cshtml and generate code in any of 29 different programming languages.  Paste the CURL command and respresentative JSON/XML response into the text boxes, and select the type of response (JSON, XML, Text, or Binary).  If the GET returns just a status code, such as 201, and no response body, then select “Text” as the type of response.

Then click “Generate Code” and your sample code is generated.  It generates code to send the request and to parse the JSON or XML response.