Hanh Nguyen
Hanh Nguyen

Reputation: 135

400 Bad Request when using RestTemplate.postForObject to call API

I am trying to post data to my api using RestTemplate, but it returns 400 bad request exception when posting. How could i fix it?

public void postDataToApi(List<String> accountIds, String myApiUrl) {
  ObjectMapper mapper = new ObjectMapper();
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_JSON);
  String accountIdsJsonList = mapper.writeValueAsString(accountIds);
  HttpEntity<String> entity = new HttpEntity<String>(accountIdsJsonList, headers);
  RestTemplate restTemplate = new RestTemplate();
  String result = restTemplate.postForObject(myApiUrl, entity, String.class);
}

Api that i want to post data is YahooApi

https://ads-developers.yahoo.co.jp/reference/ads-search-api/v4/BudgetOrderService/get/en/

Thanks for your reading.

Upvotes: 0

Views: 1054

Answers (2)

Abhale Amol
Abhale Amol

Reputation: 119

The API (yahoo) you have mentioned is accepting only authorized requests. So yahoo API is expecting only the secure requests with either token (generate token first & send it in each reqest) or client_id & client_secret (both in combination to authorize request).

Upvotes: 1

Mahesh Bhuva
Mahesh Bhuva

Reputation: 764

I guess you need to set accountIds in map. Right now you are directly posting list as json request without key. As we can see from API doc enter image description here

Try this

public void postDataToApi(List<String> accountIds, String myApiUrl) {
  ObjectMapper mapper = new ObjectMapper();
  HttpHeaders headers = new HttpHeaders();
  Map<String, Object> reqBody = new HashMap<>();
  reqBody.put("accountIds", accountIds);
  headers.setContentType(MediaType.APPLICATION_JSON);
  String accountIdsJsonList = mapper.writeValueAsString(reqBody);
  HttpEntity<String> entity = new HttpEntity<String>(accountIdsJsonList, headers);
  RestTemplate restTemplate = new RestTemplate();
  String result = restTemplate.postForObject(myApiUrl, entity, String.class);
}

Upvotes: 1

Related Questions