Vikash
Vikash

Reputation: 2163

Why passing param name is mandatory for RestTemplate in Spring

I implemented api

https://theysaidso.com/api/#qod 

using spring rest template. My question is if I make url like below it works. But if I remove the param name from the bracket, it doesnt and returns error. Any idea? Thanks!

This works :

QuoteResponse quoteResponse=    
this.restTemplate.getForObject("http://quotes.rest/qod.json?category=
{param}", QuoteResponse.class, category);

this doesn't

QuoteResponse quoteResponse=    
this.restTemplate.getForObject("http://quotes.rest/qod.json?category={}", 
QuoteResponse.class, category);

I imagine that both translates to below (taking value passes as inspire for category string

"http://quotes.rest/qod.json?category=inspire"

Update(added more code): Controller

@Autowired
QuoteService quoteService;

@RequestMapping(value="/ws/quote/daily", produces=MediaType.APPLICATION_JSON_VALUE,method=RequestMethod.GET)
public ResponseEntity<Quote> getDailyQuote(@RequestParam(required=false) String category){
    Quote quote = quoteService.getDaily(category);
    if(quote==null)
        return new ResponseEntity<Quote>(HttpStatus.INTERNAL_SERVER_ERROR);
    return new ResponseEntity<Quote>(quote,HttpStatus.OK);

}

QuoteService.getDaily

@Override
public Quote getDaily(String category){
    if(category==null || category.isEmpty())
        category=QuoteService.CATEGORY_INSPIRATIONAL;
    QuoteResponse quoteResponse=
            this.restTemplate.getForObject("http://quotes.rest/qod.json?category={cat}", 
                    QuoteResponse.class, category);


    return quoteResponse.getContents().getQuotes()[0];      
}

Upvotes: 0

Views: 721

Answers (1)

Mehraj Malik
Mehraj Malik

Reputation: 15864

this.restTemplate.getForObject("http://quotes.rest/qod.json?category=
{param}", QuoteResponse.class, category); 

When you make request like this, it means you are passing PathVariable into Controller which handeled by @PathVariable annotation in the controller's argument.

PathVariable are required in order to get your work done if controller has @PathVariable on it.

restTemplate.getForObject("http://quotes.rest/qod.json?category={}", 
QuoteResponse.class, category); 

When you make request like this, you are not sending any PathVariable with your request which is required here, so does not work and throws MissingPathVariableException

Upvotes: 2

Related Questions