I can successfully call the AirTable API from both PostMan and Intellij's built-in Rest Client using my API key. When I try to use Spring's RestTemplate with the same URL and headers I get a 401
org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
My RestTemplate Code is:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + apiKey);
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
return restTemplate.getForObject(URL, String.class, entity);
Providing the exact same URL and header (the Bearer API key) via Rest clients such as PostMan or Intellij's built in client I get a 200 response and the expected data back from AirTable.
What I am doing wrong with RestTemplate in the code above?
The overload of getForObject
you’re using takes a vararg of object as last argument which are values to use for substituting in the variables of the first argument, which should be URI template.
This means the header you’re setting isn’t used how you want it to be used.
You should instead use the correct exchange
overload taking an HttpEntity
, which will behave as expected.
Another option, to save you from always explicitly putting the auth in the request, is using an interceptor (there’s one for Basic auth which you can use as reference).