Creating an API with Spring Boot and MySQL: Part 3

Adam Zink
4 min readJul 17, 2018

--

In Part 2, we modeled a USER table with Java objects and created the first endpoint to add a new User.

Next, we are going to complete the endpoints for Users, including operations to get existing Users, update a User’s name, and delete a User.

Audience

Anyone who wants to learn how to create and run an API using Spring Boot with MySQL and Flyway.

Experience with Java programming and relational databases is helpful but not required.

Requirements

GET all Users

Let’s jump in and add some new methods to the classes that were created in Part 2.

Add getAll method to UserResource:

@GET
@Produces(MediaType.APPLICATION_JSON)
public Collection<User> getAll() {
return userService.getAll();
}

Add getAll method to UserService:

public Collection<User> getAll() {
return userConverter.modelToResponse(userRepository.findAll());
}

But hang on! We only have modelToResponse for a single User.

Let’s implement a default method in ModelConverter that takes a Collection of models and converts them into a Collection of responses:

default Collection<S> modelToResponse(final Iterable<M> models) {
assert models != null;

final Collection<S> responses = new ArrayList<S>();
models.forEach(model -> responses.add(modelToResponse(model)));

return responses;
}

The advantage of having a default method in the interface is any converters which implement ModelConverter can use it.

To test the service using a REST client like Postman, choose GET and enter URL as http://localhost:8080/api/users

Note this is the exact same URL used in Part 2 to create a User. The difference is the HTTP action verb (GET vs POST). Also, since GET requests are not supposed to change any data, the request body is not included.

Click Send to retrieve the Users:

Update a User with PUT

In many cases, data needs to be modified after it was originally created with POST. Our REST API will offer a PUT service to change the name of a User.

To update a User, we need several more service methods.

Add update method to UserResource:

@PUT
@Path("{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public User update(@PathParam("id") final Long id, final UserRequest userRequest) {
return userService.update(id, userRequest);
}
  • Recall the UserResource class is also annotated with @Path to address ALL endpoints in the class. Here, the update method is also annotated with @Path to append another level onto the endpoint with the User’s ID
  • The @PathParam annotation captures the value of the User’s ID from the endpoint and assigns the value to the id variable. The two strings must match, like "{id}" and "id", for the value to be captured correctly
  • Both the id and the userRequest object are passed to the update service method, allowing the service to know which User to modify and how to modify it

Add update method to UserService:

public User update(final Long id, final UserRequest userRequest) {
UserModel fromRequest = userConverter.requestToModel(userRequest);

UserModel toSave = userRepository.getOne(id);
toSave.setFirstName(fromRequest.getFirstName());
toSave.setLastName(fromRequest.getLastName());

return userConverter.modelToResponse(userRepository.save(toSave));
}

Note that the first name and last name from the request are used to overwrite the values that were in the database. However, the add date is preserved as the original value when the User was created.

To test the update service using a REST client like Postman, choose PUT and enter URL as http://localhost:8080/api/users/1

Think of this endpoint as an address to an individual user, whereusers is analogous to the street and 1 is analogous to the house number.

The request body needs to be included with the modified name:

{
"firstName": "Adam",
"lastName": "Z"
}

Click Send to update the User:

As expected, addDate is still the original date that the User was first created by POST.

DELETE a User

In order to remove data, another set of methods is needed.

Add delete method to UserResource:

@DELETE
@Path("{id}")
public void delete(@PathParam("id") final Long id) {
userService.delete(id);
}
  • The @PathParam annotation is used again to capture which User ID should be deleted
  • Note how void, i.e. nothing, is returned from the delete method. If the delete is successful, the HTTP response code is 204 indicating No Content (but also indicating no errors)

Add delete method to UserService:

public void delete(final Long id) {
userRepository.deleteById(id);
}

To test the update service using a REST client like Postman, choose DELETE and enter URL as http://localhost:8080/api/users/1

Click Send to remove the User:

To confirm the remove worked, try another GET with URL http://localhost:8080/api/users

As expected, the result list is empty and the User has been removed.

The full set of API endpoints are now available!

The Code

https://github.com/AdamZink/spring-boot-mysql-demo/tree/part-3

Next

The API needs documentation so other developers can integrate it into their applications. Swagger is the perfect tool to describe the API’s operations and also test them against the real MySQL database.

About the Author

--

--