Skip to main content
Application-restricted REST API tutorial

Hands-on tutorial to help you learn how to connect to our application-restricted REST APIs.

This developer resource is in beta. We welcome your feedback via the feedback widget or by contacting us.

Overview

This tutorial shows you how to connect to an application-restricted RESTful API. In particular, it shows how to do this using API key authentication.

To call an application-restricted RESTful API, you need to tell the API who the calling application is. You do this by including your application's API key when you call the API.

In this tutorial we'll show you how to do this using our example API, Hello World. It explains: 

  • using the 'Try this API' feature
  • using Java
  • using .NET (C#)
  • using Javascript
  • using Python

Whichever method you use you’ll need to create an application first to generate a client ID and client secret .


Creating an application

The following steps can be used to create an application. This generates an API key which can be used in all the below methods. You must send the API key in the apikey header when you call the API.

  1. In a new browser tab, navigate to My developer account.
  2. Sign in to your developer account by selecting 'Sign in' in the top navigation bar.
  3. View your applications by selecting 'My applications'.
  4. Create a new application by clicking the '+NEW APP' button.
  5. Give your new application a name, such as 'Hello World Example Application', and a description, such as 'Application for learning how to call APIs'.
  6. Activate the Hello World API for your application. To do this, further down the page, find the Hello World API (Sandbox environment) and click 'Enable API'. This will then prompt you to enter a Callback URL, enter 'https://digital.nhs.uk/api-spec-try-it-now/oauth-redirect'.
  7. Select 'Create' to create the application. Your new application details will be displayed.
  8. Make a note of your API key. You can copy it to your clipboard by clicking the ‘copy’ icon.
     

Using the 'Try this API' feature

You can call an application-restricted REST API directly from the API specification page using the 'Try this API' feature:

  1. Create an application using the guide above.

  2. In a new browser tab, navigate to our Hello World API.

  3. In the left-hand navigation, select Get a "Hello application!" response from an application-restricted endpoint. This is an example application-restricted endpoint.
  4. In the main panel, read the API specification. Notice that there are no request parameters and that a successful response is a JSON object containing a single field message
  5. Click on the ‘Try this API’ button. This pops-up a ‘Try this API’ window. Notice that the expandable path header /hello/application... shows an unlocked padlock icon, as this is an application-restricted endpoint and you do need to authorise.
  6. Click on the expandable path header /hello/application.... This expands the section and displays the parameters and a ‘Try it out’ button.

  7. Click on the ‘Try it out’ button. This displays an ‘Execute’ and a ‘Cancel’ button in the expanded section below.

  8. Click on the ‘Execute’ button. This calls the endpoint and displays a ‘Clear’ button next to ‘Execute’ button. It then displays the request as a CURL command and because you have not specified an API key, you should get a 401 Unauthorised response.

  9. Scroll to the top of the window and click the 'Authorize' button. You should see a pop-up box with authorisation options.
  10. Under the heading api_key (apiKey), where it says Value:, paste the API key from the application that you created in your developer account. If you don't see this option, make sure you are still signed in.

  11. Click 'Authorize', followed by 'Close'.
  12. Click on the expandable path header /hello/application... and then on the ‘Try it out’ button.
  13. Click 'Execute' button. This calls the endpoint and displays a ‘Clear’ button next to ‘Execute’ button. It then displays the request as a CURL command. If all is working well, the response should be 200 OK with a suitable JSON object in the response body.
  14. Optionally, click on the ‘Download’ button on the right-hand side of Response, to download the response as a JSON file.

Using Java

To call the API from a Java program:

  1. Create an application using the guide above.

  2. Launch your favourite Java code editor.

  3. Create a new class called HelloApplication.java.

  4. Enter the following code into the class file:

HelloApplication.java

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;





public class HelloApplication {



    // replace with your actual key

    private static String API_KEY = "YOUR-APIKEY";



    private static String BASE_URL = "https://sandbox.api.service.nhs.uk/hello-world/hello/application";



    public static void main(String[] args) throws IOException {

		URL obj = new URL(BASE_URL);



		HttpURLConnection connection = (HttpURLConnection) obj.openConnection();

		connection.setRequestMethod("GET");

        connection.setRequestProperty("Accept", "application/json");

        connection.setRequestProperty("apikey", API_KEY);

        

		int responseCode = connection.getResponseCode();



		if (responseCode == HttpURLConnection.HTTP_OK) {

			BufferedReader in = new BufferedReader(new InputStreamReader(

					connection.getInputStream()));

			String inputLine;

			StringBuffer response = new StringBuffer();



			while ((inputLine = in.readLine()) != null) {

				response.append(inputLine);

			}

			in.close();



			System.out.println(response.toString());

		} else {

			System.out.println(

                "GET request not worked, response code: "+responseCode

            );

		}



	}



}
  1. Replace YOUR-APIKEY with your application’s API Key.
  2. Compile and run your Java program. If all is working well, the response should be a suitable JSON object in the response body.

Using .NET (C#)

To call the API from a .NET application:

  1. Create an application using the guide above.

  2. Launch your favourite code editor.

  3. Add the following code to your class file:

HelloApplication.cs

using System;

using System.Net.Http;



namespace dotnetapi

{

    class Program

    {

        static async System.Threading.Tasks.Task Main(string[] args)

        {

            // replace with your actual key

            string apikey = "YOUR-APIKEY";

            string url = "https://sandbox.api.service.nhs.uk/hello-world/hello/application";



            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Add("apikey", apikey);

            client.DefaultRequestHeaders.Add("accept", "application/json");



            HttpResponseMessage response = await client.GetAsync(url);



            response.EnsureSuccessStatusCode();

            string responseString = await response.Content.ReadAsStringAsync().Result;            

            Console.WriteLine(responseString);

        }

    }

}
  1. Replace YOUR-APIKEY; with the obtained key.
  2. Compile and run your C# program, the response should be a suitable JSON object in the response body.

Using Javascript

To call the API from a JavaScript application:

  1. Create an application using the guide above.

  2. Launch your favourite code editor.

  3. Create a new script called HelloApplication.js.

  4. Add the following code to your script:

HelloApplication.js

// replace with your actual key

const apikey = "YOUR-APIKEY"



const url = "https://sandbox.api.service.nhs.uk/hello-world/hello/application"



fetch(

    url,

    {

        method: 'GET',

        headers: {

            'Accept': 'application/json',

            'apikey': apikey,

        }

    }

)

.then(resp => resp.json())

.then((data) => {

    console.log(data);

})

.catch((error) => {

    console.error(error);

});
  1. Replace YOUR-APIKEY with the obtained key.

  2. Run the code in your browser, the response should be a suitable object logged into the browser console.


Using Python

To call the API from a Python script:

  1. Create an application using the guide above.

  2. Launch your favourite code editor.

  3. Create a new script called HelloApplication.py.

  4. Add dependency, using e.g. `pip install requests`.

  5. Add the following code to your script:

HelloApplication.py

import requests



APIKEY = 'YOUR-APIKEY'  # replace with your actual key



response = requests.get(

    "https://sandbox.api.service.nhs.uk/hello-world/hello/application",

    headers={'apikey': APIKEY}

)

print(response.json())
  1. Replace YOUR-APIKEY with the obtained key.

  2. Run the script, the response should be a suitable JSON object in the response body.

Last edited: 12 March 2021 12:56 pm