Creating an HTTP Web Service
Learn how to create an HTTP web API to store, fetch, and update data.
The simplest API is the one that we query, and it hands us back data. It used to be common to serve up either XML or some binary data based on the technology stack.
In today’s world of e-commerce and mashups, the popular choice is JSON (JavaScript Object Notation). Creating a Spring WebFlux endpoint that gives us JSON instead of HTML couldn’t be easier.
So far, we’ve developed a shopping Cart containing one or more Item objects. We then persisted these objects into MongoDB and displayed them to the user by using templates.
Let’s build our interfaces for external systems, otherwise known as APIs.
In this chapter, we’ll:
In this chapter, we’ll:
- Learn how to build JSON web services.
- Write self-documenting tests using Spring REST Docs.
- Register these various API interactions in an API portal served automatically by Spring Boot.
- Craft hypermedia representations using Spring HATEOAS.
- Expand the API portal to include hypermedia links.
Defining an API controller
Let’s imagine that now, instead of fetching data from our repository, building up a model, and binding it to a template, we return the data itself:
@RestController //1public class ApiItemController {private final ItemRepository repository; //2public ApiItemController(ItemRepository repository) {this.repository = repository; //3}}
Here’s a breakdown of the code above:
- In line 1,
@RestController
indicates that this is a Spring Web controller, but instead of returning HTML, the return value is written directly into the response body. - In line 3, this controller has a copy of the same
ItemRepository
built previously.- In line 6, we inject this
ItemRepository
by constructor injection.
- In line 6, we inject this
It’s important to remember that a class flagged with @RestController
is just like a class marked with @Controller
because Spring ...