Accessing the BLS Public Data API with Java

Spring Framework:

You can acccess the API using SpringSource's RestTemplate exchange method. The exchange method has four parameters:

  • The URL of the target API Service
  • HttpMethod type (e.g. GET, POST, etc)
  • HttpEntity object, which contains Headers and Body, to be used by the REST client to communicate with the API
  • ResponseType - the return value type

For example:

    public <T> ResponseEntity<T> exchange(URI url,
                                          HttpMethod method,
                                          HttpEntity<?> requestEntity,
                                          Class<T> responseType)
                           throws RestClientException

 

The following example assumes the requestType class is APIRequest and the responseType class is APIResponse.class:

ResponseEntity<APIResponse[]> responseEntity = restTemplate.exchange(apiURL, HttpMethod.POST,
                                                    HttpEntity<APIRequest> httpEntity,
                                                    APIResponse[].class);
APIResponse[] = responseEntity.getBody()

The getBody() method returns the response mapped to the responseType class (i.e. the APIResponse.class). Once the response from API service has been mapped to a response type object, regular Java operation can be performed on the POJO response object.

The requestEntity and the responseType can use the Jackson library to bind request and response objects to the JSON request and response. Calling the RestTemplate's exchange method returns a specific ResponseEntity object.

 

Apache HTTP Commons Client:

The HttpPost\HttpGet class can be used to connect to the BLS Public Data API via Apache HTTP Commons Client, as shown in the following example. Remember to include JSON as the ContentType.

HttpPost httpPost = new HttpPost("http://api.bls.gov/publicAPI/v1/timeseries/data/");
StringEntity input = new StringEntity("{\"seriesid\":[\"LAUCN040010000000005\", \"LAUCN040010000000006\"]}");
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
variableFoo = response.getEntity().getContent()

 

Last Modified Date: February 24, 2014