Module: Building REST APIs

@GetMapping, @PostMapping

Building REST APIs - @GetMapping, @PostMapping

This tutorial will guide you through creating basic REST APIs using Spring Boot, focusing on the @GetMapping and @PostMapping annotations. We'll build a simple API to manage a list of books.

Prerequisites

  • Java Development Kit (JDK) 8 or later
  • Maven or Gradle
  • An IDE (IntelliJ IDEA, Eclipse, VS Code)
  • Basic understanding of REST principles

Project Setup

If you haven't already, create a new Spring Boot project using Spring Initializr (https://start.spring.io/).

  • Project: Maven Project
  • Language: Java
  • Spring Boot: (Latest Stable Version)
  • Dependencies: Spring Web

Creating a Simple Book Model

Let's define a Book class to represent our data:

package com.example.restapi;

public class Book {
    private Long id;
    private String title;
    private String author;

    public Book(Long id, String title, String author) {
        this.id = id;
        this.title = title;
        this.author = author;
    }

    // Getters and Setters (omitted for brevity, but essential)
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
    public String getAuthor() { return author; }
    public void setAuthor(String author) { this.author = author; }
}

Explanation:

  • @RestController: This annotation marks the class as a REST controller. It combines @Controller and @ResponseBody. @ResponseBody ensures that the return value is directly written to the response body (e.g., as JSON).
  • @GetMapping("/books"): This annotation maps HTTP GET requests to the /books path to the getAllBooks() method. When a client sends a GET request to /books, this method will be executed.
  • @PostMapping("/books"): This annotation maps HTTP POST requests to the /books path to the createBook() method. When a client sends a POST request to /books, this method will be executed.
  • @RequestBody Book book: This annotation indicates that the request body should be deserialized into a Book object. This is how we receive data from the client in a POST request.
  • List<Book> books = new ArrayList<>();: This is a simple in-memory list to store our books. In a real application, you'd typically use a database.
  • nextId++: This is a simple way to generate unique IDs for our books.

Running the Application

Run your Spring Boot application. It will typically start on port 8080.

Testing the APIs

You can test the APIs using tools like:

  • curl: A command-line tool for making HTTP requests.
  • Postman: A popular GUI tool for testing APIs.
  • Web browser: For GET requests.

1. Get All Books (GET /books)

Open your web browser or use curl:

curl http://localhost:8080/books

Initially, this will return an empty list: []

2. Create a Book (POST /books)

Use curl or Postman to send a POST request to /books with a JSON payload:

curl -X POST -H "Content-Type: application/json" -d '{"title": "The Lord of the Rings", "author": "J.R.R. Tolkien"}' http://localhost:8080/books

Or using Postman, set the request type to POST, the URL to http://localhost:8080/books, set the Content-Type header to application/json, and enter the following JSON in the request body:

{
  "title": "The Lord of the Rings",
  "author": "J.R.R. Tolkien"
}

The response will be a JSON representation of the created book, including its assigned ID:

{"id":1,"title":"The Lord of the Rings","author":"J.R.R. Tolkien"}

3. Get All Books Again (GET /books)

Now, if you make a GET request to /books again, you'll see the newly created book in the list:

[{"id":1,"title":"The Lord of the Rings","author":"J.R.R. Tolkien"}]

Key Takeaways

  • @GetMapping is used to handle GET requests.
  • @PostMapping is used to handle POST requests.
  • @RequestBody is used to bind the request body to a method parameter.
  • Spring Boot simplifies the creation of REST APIs with these annotations.

Next Steps

  • Explore other HTTP methods like @PutMapping (for updating) and @DeleteMapping (for deleting).
  • Learn about request parameters and path variables.
  • Integrate a database to persist your data.
  • Implement error handling and validation.