Tutorials
Before you start
All base URLs in these tutorials use the sandbox environment.
All code snippets in these tutorials are in Java. They use:
- The Apache HttpClient (opens in a new tab) library for accessing HTTP resources
- The Apache Oltu (opens in a new tab) library for our OAuth 2.0 client
Most of our APIs use HTTP verbs and a RESTful interface. You can find out more information on these online.
These tutorials use a simple Hello World API that exposes 3 endpoints:
Method | Path | Authorisation | Message |
---|---|---|---|
GET | /hello/world | None | Hello World! |
GET | /hello/application | Application (OAuth 2.0 access_token) | Hello Application! |
GET | /hello/user | User (OAuth 2.0 access_token) | Hello User! |
Accessing an open endpoint
In this example, you'll access the Hello World API ‘Hello World’ endpoint.
This endpoint is unrestricted so you can access it without an OAuth2.0 access_token.
Issue a GET request
Issue a GET request to https://gateway.trade.defra.gov.uk/hello/world
// construct the GET request for our Hello World endpoint HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet("https://gateway.trade.defra.gov.uk/uat/api/hello/world"); request.addHeader("Accept", "application/json"); // execute the request HttpResponse response = client.execute(request); // extract the HTTP status code and response body int statusCode = response.getStatusLine().getStatusCode(); String responseBody = EntityUtils.toString(response.getEntity());
Accessing an application-restricted endpoint
In this example, you will request an OAuth 2.0 access_token and then use it to access the Hello World API ‘Hello Application’ endpoint.
Register with the Defra API Developer Portal and create a sandbox application. You will need your application's client_id and client_assertion.
You will need to test your application in the sandbox environment before you request production credentials.
See the authorisation section for information about requesting an OAuth 2.0 access_token.
1. Request an OAuth 2.0 access token with the required scope
// extract the authorization code from the request querystring OAuthAuthzResponse response = OAuthAuthzResponse.oauthCodeAuthzResponse(httpServletRequest); String authorizationCode = response.getCode(); // create OAuth 2.0 Client using Apache HTTP Client OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); // construct OAuth 2.0 Token request for the authorization code OAuthClientRequest request = OAuthClientRequest .tokenLocation("https://gateway.trade.defra.gov.uk/uat/api/oauth/token") .setGrantType(GrantType.CLIENT_CREDENTIALS) .setClientId(clientId) .setClientAssertion(clientAssertion) .setClientAssertionType(clientAssertionType) .setScope(scope) .buildBodyMessage(); // request the token via the OAuth 2.0 client OAuthJSONAccessTokenResponse response = oAuthClient.accessToken(request); // extract the data from the response String accessToken = response.getAccessToken(); Long expiresIn = response.getExpiresIn();
2. Issue a GET request
Issue a GET request to https://gateway.trade.defra.gov.uk/hello/application, passing your newly issued access_token as an Authorization header with the type Bearer
// construct the GET request for our Hello User endpoint HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet("https://gateway.trade.defra.gov.uk/uat/api/hello/application"); request.addHeader("Accept", "application/json"); request.addHeader("Authorization", "Bearer "+accessToken); // execute the request HttpResponse response = client.execute(request); // extract the HTTP status code and response body int statusCode = response.getStatusLine().getStatusCode(); String responseBody = EntityUtils.toString(response.getEntity());
This should give you a "Hello Application" response.
Accessing a user-restricted endpoint
In this example, you will request an OAuth 2.0 access_token and then use it to access the Hello World API ‘Hello User’ endpoint.
You must register with Defra as a developer and create an application. You will need your application's production or testing client_id and client_secret.
For more information about requesting, refreshing or revoking an OAuth 2.0 access_token, see the authorisation section.
1. Request an OAuth 2.0 authorisation code with the required scope
// replace with your application's client_id and client_secret String clientId = "YOUR-CLIENT-ID"; String clientSecret = "YOUR-CLIENT-SECRET"; String scope = "hello"; String redirectUri = "https://www.example.com/redirect"; // construct the OAuth 2.0 Authorize request OAuthClientRequest request = OAuthClientRequest .authorizationLocation("https://gateway.trade.defra.gov.uk/uat/api/oauth/authorize") .setResponseType("query") .setClientId(clientId) .setScope(scope) .setRedirectURI(redirectUri)
.setResponseType(responseType)
.setState(state)
.setCodeChallange(codeChallange)
.setCodeChallangeMethod(codeChallangeMethod) .buildQueryMessage(); // redirect to the given location httpServletResponse.sendRedirect(request.getLocationUri());
The user will be redirected to the Defra login screen. When they've submitted their credentials, they'll be asked to authorise your application to access the requested scope.
Once the user has granted the requested authority, we will redirect back to your application via the redirect URI. We'll provide it with an authorisation code as a querystring parameter.
This authorisation code can then be exchanged for an OAuth 2.0 and a refresh_token.
2. Exchange the OAuth 2.0 authorisation code for an access token
// extract the authorization code from the request querystring OAuthAuthzResponse response = OAuthAuthzResponse.oauthCodeAuthzResponse(httpServletRequest); String authorizationCode = response.getCode(); // create OAuth 2.0 Client using Apache HTTP Client OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); // construct OAuth 2.0 Token request for the authorization code OAuthClientRequest request = OAuthClientRequest .tokenLocation("https://gateway.trade.defra.gov.uk/uat/api/oauth/token") .setGrantType(GrantType.AUTHORIZATION_CODE) .setClientId(clientId) .setClientSecret(clientSecret) .setRedirectURI(redirectUri) .setCode(authorizationCode)
.setCodeVerifier(codeVerifier) .buildBodyMessage(); // request the token via the OAuth 2.0 client OAuthJSONAccessTokenResponse response = oAuthClient.accessToken(request); // extract the data from the response String accessToken = response.getAccessToken(); String refreshToken = response.getRefreshToken(); String grantedScope = response.getScope(); Long expiresIn = response.getExpiresIn();
3. Issue a GET request
Issue a GET request to https://gateway.trade.defra.gov.uk/hello/user, passing your newly issued access_token as an Authorization header with the type Bearer
// construct the GET request for our Hello User endpoint HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet("https://gateway.trade.defra.gov.uk/uat/api/hello/user"); request.addHeader("Accept", "application/json"); request.addHeader("Authorization", "Bearer "+accessToken); // execute the request HttpResponse response = client.execute(request); // extract the HTTP status code and response body int statusCode = response.getStatusLine().getStatusCode(); String responseBody = EntityUtils.toString(response.getEntity());
This should give you a "Hello User!" response. This may vary depending on whether you used your testing or production client_id and client_secret when you started OAuth 2.0 flow.
4. Refresh an expired OAuth 2.0 access_token
This exchanges a refresh_token for a new access_token (and a new refresh_token).
// replace with your application's client_id and client_secret String clientId = "YOUR-CLIENT-ID"; String clientSecret = "YOUR-CLIENT-SECRET"; // create OAuth 2.0 Client using Apache HTTP Client OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); // construct OAuth 2.0 Token request for the authorization code OAuthClientRequest request = OAuthClientRequest .tokenLocation("https://gateway.trade.defra.gov.uk/uat/api/oauth/token") .setGrantType(GrantType.REFRESH_TOKEN) .setClientId(clientId) .setClientSecret(clientSecret) .setRefreshToken(refreshToken) .buildBodyMessage(); // request the token via the OAuth 2.0 client OAuthJSONAccessTokenResponse response = oAuthClient.accessToken(request); // extract the data from the response String accessToken = response.getAccessToken(); String refreshToken = response.getRefreshToken(); Long expiresIn = response.getExpiresIn();
You should now be ready to start integrating with our APIs.