Calling multiple external APIs in Spring Boot - java

I am working on a project but it requires me to call multiple external APIs. I basically have to call an API to get a player id by giving a name. Then use that player id to get a list of match ids. Then make calls for each match id to get details on each match. its alot and doesnt seem optimal but its the only way to do it. I was going to use rest template to make a call to the following
https://americas.api.riotgames.com/lol/match/v5/matches/by-puuid/HDzjdaStxhHcceGGd8qJcc4Vw45FOlOQ1PNXKQ0h9_iqfwHP3oI0spl1bLUOw_7_J49vzaIKylv5Vg/ids?start=0&count=20
I have to pass in headers as well such as
riot token : token
"Origin": "https://developer.riotgames.com"
I was wondering how I can do this in Java Spring boot. I saw RestTemplate would be used but I couldnt figure out how to include the headers. Any guidance would be appreciated.

You can call RestTemplate.exchange() using either the method signature with RequestEntity or with HttpEntity.
// Using RequestEntity
RequestEntity<?> request= RequestEntity.get(url).header(headerName, headerValue).build();
ResponseEntity<String> response = restTemplate.exchange(request, String.class);
// Using HttpEntity
HttpHeaders headers = new HttpHeaders();
headers.set(headerName, headerValue);
HttpEntity httpEntity = new HttpEntity(/* this is nullable */ requestBody, headers);
ResponseEntity,String> response = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
Would also recommend reading through the following:
https://howtodoinjava.com/spring-boot2/resttemplate/spring-restful-client-resttemplate-example/
https://www.baeldung.com/rest-template
How to set an "Accept:" header on Spring RestTemplate request?

Related

Spring Boot - How to send a POST request via a url with query parameters and store the response inside a method?

I have a url generated by a GET method which is somewhat of this format:
https://service-name/api?param1=<value1>&param2=<value2>&param3=<value3>.....
I need to hit this url and store the response (which will be of type application/x-www-form-urlencoded) into a variable, which will be used further.
The issue is that it needs to be done inside the method (get the url and pass it to get a response).
How to go about it?
For a spring boot application to consume an external API, you can use RestTemplate.
An example of usage is below. The response you receive is of type String.
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("Header", "header1");
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://foo/api/v3/projects/1/labels")
.queryParam("param1", param1)
.queryParam("param2", param2);
HttpEntity<?> entity = new HttpEntity<>(headers);
HttpEntity<String> response = restTemplate.exchange(
builder.toUriString(),
HttpMethod.GET,
entity,
String.class);

rest api - how to send body parameters of postman in rest api call

Hi I am able to call a rest api through postman . I have added the following in body part of postman. client_id - xxxx , client_secret - *** etc.
Now i want to make rest api call through java. How do i add these body parameters to request being created from java
If you are using Spring, you can use the RestTemplate Spring REST client to make a call to an external API from Java.
Example:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(someDto, headers)
restTemplate.postForEntity(postUrl, request, String.class);

Passing Request Body to Spring Rest Template without using LinkedMultiValueMap

I'm using the Spring Rest Template to make an Http PUT request and up until now I have been passing the request body using the following:
MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
body.add("account", testAccount);
HttpEntity<?> requestEntity = new HttpEntity<Object>(body, headers);
ResponseEntity<String> responseEntity;
try {
responseEntity = rest.exchange(uri, HttpMethod.PUT, requestEntity, String.class);
}
catch (HttpStatusCodeException e) {
log.error("Http PUT failed with response: " + e.getStatusText());
return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsString());
}
return responseEntity;
The request body that gets sent to my target API appears as:
{"account":[{"account_id":"495"}]}
This works, but my target API is not expecting the account object to have an array as a value and is currently giving me a 500 Internal Server Error, so, my question is, how can I get the value of the 'account' property to be an object rather than an array? For example I would like the request body to appear as:
{"account":{"account_id":"495"}}
Is there another type of Map which can be used which does not accept multiple values?
I would still like to use the exchange method if possible.
Any on help on this would be grand! Many thanks
The answer was actually simply using a regular HashMap instead of the MultiValueMap. As seen here the MultiValueMapcase is used when you want to add an array to a single key in the request body.
Thanks for all the help.

How can I send a post request to check-runs on github API with customized headers?

Reading the API of Github, it demands a custom headers : "vnd.github.antiope-preview+json"; Using spring boot.
I always get 415 Unsupported Media Type eventhough that's what's mentioned in the github API page.
HttpHeaders headers = new headers.setAccept(Collections.singletonList(new MediaType("application","vnd.github.antiope-preview+json")));
headers.setContentType();
HttpEntity<String> entity = new HttpEntity<>(str,headers);
restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
For information , I did it on postman with the same headers.

How to get the HTTP status of an API in spring boot when we hit it internally using Rest template

I want to get the object as well as the HTTP response of one api into another in Spring code. For that I am using a rest template and I am getting the desired Object from it successfully.
But I want to fetch HTTP response also for the respective api.
What should I do to get this?
RestTemplate restTemplate = new RestTemplate();
Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
System.out.println("quote "+quote);
System.out.println(quote.getType());
log.info(quote.toString());
getForObject method of RestTemplate only gets the result. If you're interest in the status code you should invode exchange which returns a ResponseEntity which has a getStatusCode method.
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Quote> response= restTemplate.exchange ("http://gturnquist-quoters.cfapps.io/api/random", HttpMethod.GET, null, Quote.class);
Quote quote = response..getBody();
System.out.println("status "+response..getStatusCode());
System.out.println("quote "+quote);
System.out.println(quote.getType());

Categories

Resources