Skip to main content
User-restricted REST API tutorial

Hands-on tutorial to help you learn how to connect to our user-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 a user-restricted RESTful API. In particular, it shows you how to do this using NHS Care Identity Service 2 (NHS CIS2) combined authentication and authorisation.

To call a user-restricted RESTful API, you need to tell the API who the end user is. You do this by including an OAuth 2.0 access token when you call the API. You get the access token from our OAuth 2.0 authorisation server.

In this tutorial we'll show 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 an API key and secret.


Creating an application

To create an application:

  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 then prompts 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 such as API Key ('client_id') and Secret (‘client_secret') will be displayed.

Using the 'Try this API' feature

You can call a user-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 user!" response from a user-restricted endpoint. This is an example of a user-restricted endpoint.
  4. In the main panel, read the API specification. Note that there are no request parameters and that a successful response is a JSON object containing a single field message.
  5. Click the 'Try this API' button. This pops-up a 'Try this API' window. Notice that the expandable path header /hello/user... shows an unlocked padlock icon, as this is a user-restricted endpoint and you do need to authorise.
  6. Click the expandable path header /hello/user.... This expands the section and displays the parameters and a ‘Try it out’ button.

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

  8. Click the ‘Execute’ button. This calls the endpoint and displays a ‘Clear’ button next to the ‘Execute’ button. It then displays the request as a CURL command and because you have not authorised the user, 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 oAuth2AuthCode (OAuth2, authorizationCode), where it says 'client_id:', paste the Key (API Key) from the application that you created in your developer account. Do the same with ‘client_secret:', paste Secret (API Key) from your application. If you do not see this option, make sure you are still signed in.

  11. Click 'Authorize'. This displays a simulated login page to sign in.

  12. Click 'Sign In'. This then displays the authentication completed page. Close the browser tab and navigate back to 'Try this API' pop-up window.

  13. Click the 'Close' button on the pop-up box with authorisation options.

  14. Click on the expandable path header /hello/user... and then on the ‘Try it out’ button.

  15. 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.
  16. 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. Install JDK 8 (Java Development Kit) or later and Gradle on your computer.
  3. Launch your favourite code editor.
  4. Create a new Gradle project by running gradle init in command prompt.
  5. Replace the code in the build.gradle file with the code below.

build.gradle

apply plugin: 'java'

apply plugin: 'application'



mainClassName = 'com.example.hellodemo.Application'



group = 'com.example'

version = '0.0.1-SNAPSHOT'

sourceCompatibility = '1.8'



repositories {

	mavenCentral()

}



dependencies {

	compile 'org.apache.httpcomponents:httpclient:4.5.13'

}



jar {

	manifest {

		attributes('Main-Class': mainClassName)

	}

	from {

		configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }

	}

}
  1. Delete the main class and any other test classes that are provided as part of the template. 
  2. Create a new Java class called Application.java and use the code below.  

Application.java

package com.example.hellodemo;





import org.apache.http.HttpEntity;

import org.apache.http.NameValuePair;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.message.BasicNameValuePair;



import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.nio.charset.StandardCharsets;

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

import java.util.stream.Collectors;



public class Application {

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

        OAuth oAuth = new OAuth();

        oAuth.getCode();

        oAuth.getAccessToken();

    }

}



class OAuth {

    final private String authorizationUri = "https://sandbox.api.service.nhs.uk/oauth2/authorize";  // Authorization code endpoint

    final private String redirectUri = "http://localhost:5000/callback";  // Callback endpoint

    final private String tokenUri = "https://sandbox.api.service.nhs.uk/oauth2/token";  // Get tokens endpoint

    final private String clientId= "your-client-id";  // change to your Client_ID

    final private String clientSecret = "your-client-secret";  // change to your client_secret

    final private String state = "random";



    public void getCode() {

        System.out.println("Open the link below in your browser");

        System.out.println(authorizationUri +

                "?client_id=" + clientId +

                "&redirect_uri=" + redirectUri +

                "&response_type=code" +

                "&state=" + state);

    }



    public void getAccessToken() throws IOException {

        Scanner in = new Scanner(System.in);

        System.out.println("Enter code:");

        String code = in.nextLine();



        HttpPost httpPost = new HttpPost(tokenUri);

        List<NameValuePair> params = new ArrayList<>();

        params.add(new BasicNameValuePair("grant_type", "authorization_code"));

        params.add(new BasicNameValuePair("client_id", clientId));

        params.add(new BasicNameValuePair("client_secret", clientSecret));

        params.add(new BasicNameValuePair("redirect_uri", redirectUri));

        params.add(new BasicNameValuePair("code", code));



        httpPost.setEntity(new UrlEncodedFormEntity(params));



        CloseableHttpClient client = HttpClients.createDefault();

        CloseableHttpResponse response = client.execute(httpPost);

        HttpEntity entity = response.getEntity();



        if (entity != null) {

            InputStream instream = entity.getContent();

            String text = new BufferedReader(

                    new InputStreamReader(instream, StandardCharsets.UTF_8)).lines()

                    .collect(Collectors.joining("\n"));

            System.out.println(text);

            instream.close();

        }



        client.close();

    }

}
  1. Replace clientId and clientSecret with the credentials given to you from your new app created in the guide above. Please note that clientId is the API Key. 
  2. In your terminal, ensure you are in the project directory. Build the application using the command ./gradlew build.
  3. Run the application using the command java -jar build/libs/demo-0.0.1-SNAPSHOT.jar.
  4. Once running, open your browser and copy and paste the URL prompted in the command line. You should be redirected to our sign-in page.
  5. Sign in using the simulated login page.        
  6. You should be redirected to a broken page. Copy and paste the code in the URL link of the broken page, back to your command line prompt.         
  7. You should be presented with a JSON object in the console containing your access token. Run the following command and replace the text <paste your access_token here> with your access token. 
    If you are using Mac or Linux, enter: $ curl -X GET -H "Authorization: Bearer <paste your access_token here>" https://sandbox.api.service.nhs.uk/hello-world/hello/user.
    If you are using Windows, enter: Invoke-WebRequest -Uri "https://sandbox.api.service.nhs.uk/hello-world/hello/user" -Headers @{Authorization = "Bearer <paste your access_token here>"}.

  8. If successful, you should be greeted with {{{ "message": "Hello User!" }}}.


Using .Net (C#)

To call the API from a .NET application:

  1. Create an application using the guide above.

  2. Launch your favorite code editor.

  3. Create a new .net console project.

  4. Add the following code to your program.cs

program.cs

using System;

using System.Collections.Generic;

using System.Linq;

using Newtonsoft.Json;

using Microsoft.AspNetCore.WebUtilities;

using System.Web;

using System.Net.Http;

using System.Threading.Tasks;



namespace HelloWorldUserRestrictedAPI

{

    class OAuth

    {

        Random random = new Random();

        private string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";



        private string AuthorizationUri = "https://sandbox.api.service.nhs.uk/oauth2/authorize";  // Authorization code endpoint

        private string RedirectUri = "http://localhost:5000/callback";  // Callback endpoint

        private string TokenUri = "https://sandbox.api.service.nhs.uk/oauth2/token";  // Get tokens endpoint      

        private string client_id = "Your_Client_Id";  // change to your Client_ID

        private string client_secret = "Your_Client_Secret";  // change to your client_secret

        private string state;

        public void GetCode()

        {

            var _state = new string(Enumerable.Repeat(chars, 16).Select(s => s[random.Next(s.Length)]).ToArray());

            this.state = _state;

            var dictionary = new Dictionary<string, string>()

           {

               {"client_id", client_id},

               {"redirect_uri", RedirectUri },

               {"response_type", "code"},

               {"state", _state}

           };

            string url = QueryHelpers.AddQueryString(AuthorizationUri, dictionary);

            Console.WriteLine("Open link in your browser " + url);

        }



        public async Task GetAccessToken()

        {

            Console.WriteLine("Enter callback url:");

            string CallbackUrl = Console.ReadLine();

            Uri siteUri = new Uri(CallbackUrl);

            string _code = HttpUtility.ParseQueryString(siteUri.Query).Get("code");

            string _state = HttpUtility.ParseQueryString(siteUri.Query).Get("state");



            if (this.state == _state)

            {

                HttpClient client = new HttpClient();

                client.DefaultRequestHeaders.Add("cache-control", "no-cache");

                var dict = new Dictionary<string, string>()

               {

                   {"grant_type", "authorization_code"},

                   {"client_id", client_id},

                   {"client_secret", client_secret},

                   {"redirect_uri", RedirectUri},

                   {"code", _code}

               };

                FormUrlEncodedContent postData = new FormUrlEncodedContent(dict);

                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, TokenUri);

                request.Content = postData;

                var response = await client.SendAsync(request);

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

                var json = JsonConvert.DeserializeObject(responseString);

                Console.WriteLine(json);

            }

            else

            {

                Console.WriteLine("callback is malformed");

            }

        }

    }



    class Program

    {

        static async Task Main(string[] args)

        {

            OAuth OAuth = new OAuth();

            OAuth.GetCode();

            await OAuth.GetAccessToken();

        }

    }

}
  1. Replace clientId and clientSecret with the credentials given to you from your new app created in the guide above. Please note that clientId is the API Key. 
  2. Run the command: dotnet run.
  3. Once running, open your browser and copy and paste the URL prompted in the command line. You should be redirected to our sign-in page.
  4. Sign in using the simulated login page.
  5. You should be redirected to a broken page. Copy and paste the URL link of the broken page in your command line prompt.
  6. You should be presented with a JSON object in the console containing your access token. Run the following command and replace the text <paste your access_token here> with your access token.
    If you are using Mac or Linux, enter: $ curl -X GET -H "Authorization: Bearer <paste your access_token here>" https://sandbox.api.service.nhs.uk/hello-world/hello/user.
    If you are using Windows, enter: Invoke-WebRequest -Uri "https://sandbox.api.service.nhs.uk/hello-world/hello/user" -Headers @{Authorization = "Bearer <paste your access_token here>"}.
  7. If all is successful, you should be greeted with 
    {{{ "message": "Hello User!" }}}.

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 repository and navigate to the new repository by using change directory cd command.
  4. Install the following library by running the command npm i client-oauth2 express.
  5. Create a new JavaScript file called HelloApplication.js.
  6. Copy the JavaScript code below into your newly created file HelloUser.js file.

HelloApplication.js

const ClientOAuth2 = require('client-oauth2')

const https = require('https');

const express = require('express')

const app = express()

//const BASE_URL = "https://sandbox.api.service.nhs.uk"

var access_token



app.listen(5000)

console.log("Server running")

const clientId = "Your_Client_Id" //ENTER CLIENT ID CREDENTIALS

const clientSecret = "Your_Client_Secret" //ENTER CLIENT SECRET CREDENTIALS

const client = new ClientOAuth2({

    clientId,

    clientSecret,

    redirectUri: 'http://localhost:5000/callback',

    authorizationUri: 'https://sandbox.api.service.nhs.uk/oauth2/authorize',

    accessTokenUri: "https://sandbox.api.service.nhs.uk/oauth2/token",

    response_type: 'code',

})





app.get('/', (req, res) => {

    var uri = client.code.getUri()

    res.redirect(uri + 'hello')

})



app.get('/callback', (req, res) => {

    client.code.getToken(req.originalUrl).then(token => {

        client.code.Token = token

        access_token = token.accessToken

        res.redirect("http://localhost:5000/profile")

    })

})



app.get('/profile', (req, res) => {

    var option = {

        host: "sandbox.api.service.nhs.uk",

        path: "/hello-world/hello/user",

        headers: {

            'Authorization': "Bearer " + access_token 

        }

    }



    https.get( option, (resp) => {

        var body = '';

        resp.on('data', function(chunk) {

          body += chunk;

        });

        resp.on('end', function() {

          

            res.send(body);

        });

      })

})
  1. Replace clientId and clientSecret with the credentials given to you from your new app created in the guide above. Please note that client_id is the API Key.
  2. Run the command node HelloUser.js.
  3. Once running, open your browser at http://localhost:5000. You should be redirected to our sign-in page.
  4. Sign in using the simulated login page.
  5. If successful, you should be greeted with {{{ "message": "Hello User!" }}}.

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 'HelloWorld.py'.

  4. Install the required modules by running the command: `pip install requests-oauthlib flask`.

  5. Add the following code to your script:

HelloApplication.py

import os



from flask import Flask, redirect, request, session, url_for

from flask.json import jsonify

from requests_oauthlib import OAuth2Session



app = Flask(__name__)

app.secret_key = os.urandom(24)



BASE_URL = "https://sandbox.api.service.nhs.uk"

authorize_url = "https://sandbox.api.service.nhs.uk/oauth2/authorize"

access_token_url = "https://sandbox.api.service.nhs.uk/oauth2/token"



# replace "redirect_uri" with callback url,

# which you registered during the app registration

redirect_uri = "http://localhost:5000/callback"



# replace with your api key

client_id = "your_client_id"

# replace with your secret

client_secret = "your_client_secret"





@app.route("/")

@app.route("/login")

def login():

    nhsd = OAuth2Session(client_id=client_id, redirect_uri=redirect_uri)

    authorization_url, state = nhsd.authorization_url(authorize_url)

    # State is used to prevent CSRF, keep this for later.

    session["oauth_state"] = state

    return redirect(authorization_url)





@app.route("/callback", methods=["GET"])

def callback():

    nhsd = OAuth2Session(client_id=client_id, redirect_uri=redirect_uri, state=session["oauth_state"])

    token = nhsd.fetch_token(

       token_url=access_token_url,

       client_secret=client_secret,

       authorization_response=request.url,

    )

    session["oauth_token"] = token

    return redirect(url_for(".profile"))





@app.route("/profile", methods=["GET"])

def profile():

    # Fetching a protected resource using an OAuth 2 token.

    nhsd = OAuth2Session(client_id, token=session["oauth_token"])

    user_restricted_endpoint = jsonify(

       nhsd.get(f"{BASE_URL}/hello-world/hello/user").json()

    )

    return user_restricted_endpoint





if __name__ == "__main__":

    os.environ["FLASK_ENV"] = "development"

    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

    app.run(debug=True)
  1. Replace client_id and client_secret with the credentials from step 7 while creating an application.
  2. Run the command: python HelloWorld.py.
  3. Open your browser at http://localhost:5000. You should be redirected to our Simulated login page (please do not click on the URL provided by your app in the console).
  4. Click on the Sign in button.
  5. If successful, you should be greeted with { "message": "Hello User!" }.

Last edited: 17 August 2021 4:40 pm