Contribute in GitHub: Open doc issue

Making an outbound API request that uses the REST client

After you configure and create the Jersey REST client, use it to send an outbound request and to map the response, if any, to a Java object.

Constructing an outbound request

First, construct the request by adding the details of the URL that you want to call to a WebTarget instance. You can add the following details:

The following code shows how to construct a WebTarget instance and how to add path parameter and query parameters:

WebTarget webTarget = client.target("https://example.com")
                            .path("/api")
                            .path("/resource")
                            .queryParam("include_inactive", "true");

Add the remaining details of the request to an InvocationBuilder instance. You can add the following details:

The following code shows how to construct an InvocationBuilder instance, how to add an Accept-Language header, and how to specify that the response body of the API is application/json:

Invocation.Builder invocationBuilder = webTarget
                                        .header("Accept-Language", "en-US")
                                        .request(MediaType.APPLICATION_JSON);

Sending an outbound request

Call the API by specifying the HTTP method for the request on the InvocationBuilder instance. The following example shows how to make the GET request and the response that is returned:

Response responseFromAPI = invocationBuilder.get();

For a POST or PUT request that contains a request body, you also pass in the Java object that is mapped to the JSON request body. The following example shows a POST request that passes in a myObject instantiated POJO, and specifies that the request body media type is application/json:

Response responseFromAPI = invocationBuilder.post(Entity.entity(myObject, MediaType.APPLICATION_JSON));

Handling the response from the request

Check the HTTP response code that determines whether the request was successful or not. For a successful response, if the response contains a response body, it is deserialized to a Java object. For the HTTP code that denotes a successful response, see the documentation for your API. For example, 200 is the standard code for a GET request. A 200 or 201 code might be returned from a POST request. A 204 code might be returned for a POST or DELETE request and means that no response body exists.

If the request is not successful, the response body usually contains an error response. Therefore, make sure you check the response code first for a success code before you attempt to deserialize the body. The deserialization of the response body fails if it tries to deserialize into the wrong POJO type.

In many cases, if the request is not successful, the HTTP error response code provides sufficient information about the problem. However, you can also deserialize the error response body from the API into a Java object if you need further details. You must define a Java object to match the JSON format of the error response. For information about the format, see the documentation for the API that you are calling.

Important: If you call the Response#readEntity() method, the connection is automatically closed. However, you must manually close the connection if you don't call the Response#readEntity() method. For example, you might not call the Response#readEntity() method if the response has no response body or if the API returns an error response body that you do not read.

The following code shows how to check the HTTP response code before you deserialize the response body. It assumes that the API returns a code of 200 if successful, and that the response body must be deserialized into a Java object of type MyResponseObject.

if (HttpStatus.OK.value() == responseStatus) {

    //response body
    MyResponseObject responseObj = responseFromAPI.readEntity(MyResponseObject.class);

    //response headers (if required)
    MultivaluedMap<String, Object> headers = responseFromAPI.getHeaders();

} else {
    // handle the error
    // if not reading the error response entity, you MUST close the connection:
    responseFromAPI.close();
}

In an error scenario, you might want to log or handle different errors in different ways. For example, a 401 response code means unauthorized, so you might need to log in again or refresh your authentication token. A 301 response code means a redirect, which you might want to follow if the API service is trusted. See your API documentation for the different error response codes that the API returns.

Note: If you do not know which attributes a response body contains and you cannot create a Java POJO to match, you can use a generic Java object. Jackson maps the JSON object to a Java Map of name-value pairs.

Object genericObject = responseFromAPI.readEntity(Object.class);

Full example of how to make an outbound API request

The following example shows the previous code examples that are combined to make a GET request and to handle the response:

public ResponseObject invokeOutboundAPI() {

    javax.ws.rs.client.WebTarget webTarget = client.target("https://example.com")
                            .path("/api")
                            .path("/resource")
                            .queryParam("include_inactive", "true");

    javax.ws.rs.client.Invocation.Builder invocationBuilder = webTarget
                                        .header("Authentication", "Bearer " + accessTokenValue)
                                        .request(MediaType.APPLICATION_JSON);

    javax.ws.rs.core.Response responseFromAPI = invocationBuilder.get();

    if (200 == responseStatus) {

        //response body
        MyResponseObject responseObj = responseFromAPI.readEntity(MyResponseObject.class);

    } else if (401 = responseStatus) {

        responseFromAPI.close();
        //perform logic to reauthenticate or to use refresh token to get new access token

    } else {

        // if not reading the error response entity, you MUST close the connection:
        responseFromAPI.close();

        throw new RuntimeException("outbound api request failed");
    }
}