Search code examples
restspring-boothttp-postconsumer

Sprint Boot - Post a single string/enum to a REST service


I'm trying to send a single string to a REST API via Spring Boot but I keep getting 400: Bad Request. I checked through postman that this json is accepted by the API:

{
    "currency": "USD"
}

I wrote the following piece of code to post to this service:

public Account createAccount(Currency currency)
{
        Account account = (Account) restTemplate.postForObject(url, currency.toString(), Account.class);
        return account;
}

Currency enum is given below:

public enum Currency 
{
    USD, EUR
}

I tried both by sending it as the enum and string value, none worked.


Solution

  • You should create a class that encapsulates the enum eg:

    public class CreateAccountRequest {
    
      private final Currency currency;
    
      public CreateAccountRequest(Currency currency) {
        this.currency = currency; 
      }
    
      public Currency getCurrency() {
    
      }
    }
    

    Then when you do postForObject:

    restTemplate.postForObject(url, createAccountRequest, Account.class);