Creating CRUD Endpoints

Introduction

Welcome back! So far, we’ve focused on retrieving data from our RESTful API using GET endpoints. Now, let’s take the next step: creating endpoints for creating, updating, and deleting data. Mastering these operations is critical for building fully functional APIs.

Understanding CRUD

In one of the previous lessons, we covered the concept of resources in REST. In RESTful APIs, a resource can be anything you manage, like a recipe. Each resource is identified by a URI, such as /recipes/123 or /users/john-doe. So far in this course, we have only focused on reading resources. What other operations can we perform on a resource? We can create, read, update, or delete a resource. These four operations form the abbreviation CRUD.

To perform these operations on a resource, different HTTP methods are used. Each method corresponds to one of the CRUD operations. Spring Boot allows for easy creation of endpoints for each method using special annotations. Here’s a quick overview of the HTTP methods, corresponding Spring annotations, and the expected operations:

HTTP MethodSpring AnnotationExpected Operation
GET@GetMappingRead/Retrieve
POST@PostMappingCreate
PUT@PutMappingUpdate/Replace
DELETE@DeleteMappingDelete
PATCH@PatchMappingPartial Update

Although PATCH is included here for completeness, we won’t be practicing it in this course since it’s less frequently used compared to the others.

Retrieving Data

Let's begin with a quick recap on how to retrieve data. You've already created numerous GET endpoints in the previous exercises:

@RestController
@RequestMapping("/recipes")
public class RecipeController {

    @Autowired
    private RecipeRepository recipeRepository;

    @GetMapping
    public List<RecipeItem> getAllRecipes() {
        return recipeRepository.findAll();
    }

    @GetMapping("/{id}")
    public RecipeItem getRecipeById(@PathVariable UUID id) {
        return recipeRepository.findById(id);
    }
}

The first method getAllRecipes returns a list of all recipes when a GET request is made to /recipes. The second method getRecipeById returns a single recipe based on the provided ID when a GET request is made to /recipes/{id}. The @GetMapping annotation maps the HTTP GET requests to these methods.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal