We will allow third-party clients to retrieve the search results via a REST API. These results will be available either in JSON or XML.
We want to handle requests of the /api/search/mixed;keywords=springFramework
form. This is really similar to the search form we already made, except that the request path begins with api
. Every URI found in this namespace should return binary results.
Let's create a new SearchApiController
class in the search.api
package:
package masterSpringMvc.search.api; import masterSpringMvc.search.SearchService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.social.twitter.api.Tweet; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/search") public class SearchApiController { private SearchService searchService; @Autowired public SearchApiController(SearchService searchService) { this.searchService = searchService; } @RequestMapping(value = "/{searchType}", method = RequestMethod.GET) public List<Tweet> search(@PathVariable String searchType, @MatrixVariable List<String> keywords) { return searchService.search(searchType, keywords); } }
This is quite similar to our previous controller, with three subtle differences:
@RequestMapping
annotation. This will be our base address and will prefix every other mapping declared in this controller.@RestController
instead of @Controller
.The RestController
is a shortcut to declare controllers that will return each response as if it were annotated with the @ResponseBody
annotation. It tells Spring to serialize the return type to the appropriate format, which is JSON by default.
When working with a REST API, a good practice is to always specify the method you will respond to. It's rather unlikely that a request can be handled the same way for a GET
or a POST
method.
If you go to http://localhost:8080/api/search/mixed;keywords=springFramework
, you should get a really large result, as follows:
Indeed, Spring handled the serialization of the whole Tweet
class' attributes automatically, using Jackson.