0Pricing
Spring Boot 4 Complete Guide · Leçon

Créer des contrôleurs REST

Concevez et mettez en œuvre des points de terminaison RESTful à l’aide de `@RestController` et de différentes annotations de mappage.

Créer des contrôleurs REST est une leçon Spring Boot 4 Complete Guide gratuite sur CoddyKit. Ceci est la leçon 1 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Spring Boot 4 Complete Guide, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Spring Boot 4 Complete Guide comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

Welcome to REST Controllers!

You're about to dive into building powerful web services with Spring Boot! Today, we'll learn how to create RESTful APIs, which are the backbone of modern web applications.

Think of a REST API as a standard way for different computer systems to talk to each other over the internet.

What are RESTful APIs?

REST stands for REpresentational State Transfer. It's an architectural style for networked applications.

  • Resources: Everything is a resource (e.g., a user, a product).
  • Unique Identifiers: Each resource has a unique URL (e.g., /users/123).
  • Standard Methods: We use standard HTTP methods like GET, POST, PUT, DELETE to interact with resources.

Spring Boot makes implementing these a breeze!

Introducing `@RestController`

In Spring Boot, the @RestController annotation is key to building RESTful web services. It's a special type of Spring component.

  • It tells Spring that this class handles incoming web requests.
  • It combines @Controller and @ResponseBody.

@ResponseBody means the return value of your methods should be directly bound to the web response body.

Your First GET Endpoint

Let's create a simple endpoint that responds to a GET request. GET requests are used to retrieve data.

We use the @GetMapping annotation to map HTTP GET requests to specific handler methods.

Runnable GET Example

Try running this simple Spring Boot application. It defines a /hello endpoint that returns a greeting.

package com.coddykit;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class MyApplication {
  public static void main(String[] args) {
    SpringApplication.run(MyApplication.class, args);
  }
}

@RestController
class HelloController {
  @GetMapping("/hello")
  public String sayHello() {
    return "Hello from CoddyKit!";
  }
}

Testing Your GET Endpoint

After running the previous code, your Spring Boot application starts on port 8080 by default.

You can access your new endpoint by opening a web browser and navigating to:

  • http://localhost:8080/hello

You should see the message "Hello from CoddyKit!" displayed.

Introducing `@PostMapping`

While GET is for retrieving data, POST requests are typically used to create new resources on the server.

The @PostMapping annotation maps HTTP POST requests to a specific method. When you send data, it often comes in the 'request body'.

We use @RequestBody to tell Spring to convert the incoming body into a Java object (or a simple String).

Runnable POST Example

Let's add a POST endpoint to our existing controller. This endpoint will accept a name in the request body and return a personalized greeting.

package com.coddykit;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class MyApplication {
  public static void main(String[] args) {
    SpringApplication.run(MyApplication.class, args);
  }
}

@RestController
class HelloController {
  @GetMapping("/hello")
  public String sayHello() {
    return "Hello from CoddyKit!";
  }

  @PostMapping("/greet")
  public String greetUser(@RequestBody String name) {
    return "Hello, " + name + "!";
  }
}

Path Variables with `@PathVariable`

Sometimes, you want to extract a value directly from the URL path itself. This is where path variables come in handy.

The @PathVariable annotation allows you to bind a URL template variable to a method parameter.

  • Example URL: /users/123
  • Here, 123 is a path variable representing a user ID.

Using Path Variables in Code

This example adds an endpoint that uses a path variable to greet a specific person whose name is part of the URL.

package com.coddykit;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class MyApplication {
  public static void main(String[] args) {
    SpringApplication.run(MyApplication.class, args);
  }
}

@RestController
class HelloController {
  @GetMapping("/hello")
  public String sayHello() {
    return "Hello from CoddyKit!";
  }

  @PostMapping("/greet")
  public String greetUser(@RequestBody String name) {
    return "Hello, " + name + "!";
  }

  @GetMapping("/greet/{name}")
  public String greetPathVar(@PathVariable String name) {
    return "Greetings, " + name + " from path!";
  }
}

Quick Check: Controller Basics

You've learned about `@RestController` and basic mapping annotations. Let's test your understanding.

Recap: Creating REST Controllers

Great job! You've taken your first steps into building RESTful APIs with Spring Boot:

  • We understood what RESTful APIs are and their purpose.
  • We learned about the fundamental @RestController annotation.
  • You implemented and tested endpoints for GET requests using @GetMapping.
  • You also created a basic POST endpoint with @PostMapping and used @RequestBody.
  • Finally, you saw how to extract dynamic data from URLs using @PathVariable.

Next, we'll dive deeper into handling various HTTP requests and crafting responses!

Questions Fréquemment Posées

La leçon « Créer des contrôleurs REST » est-elle gratuite ?

Oui — le texte complet de « Créer des contrôleurs REST » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Spring Boot 4 Complete Guide, passe à CoddyKit PRO. Le cours Spring Boot 4 Complete Guide comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Créer des contrôleurs REST » ?

Concevez et mettez en œuvre des points de terminaison RESTful à l’aide de `@RestController` et de différentes annotations de mappage. Tu pratiques Spring Boot 4 Complete Guide avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Spring Boot 4 Complete Guide ?

Aucune expérience préalable n'est requise. Spring Boot 4 Complete Guide sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 1 sur 4.

Combien de temps prend la leçon « Créer des contrôleurs REST » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Spring Boot 4 Complete Guide ?

Oui. Chaque leçon Spring Boot 4 Complete Guide inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Créer des contrôleurs REST
  2. Gérer les requêtes et les réponses HTTP
  3. Validation des entrées et gestion des erreurs
  4. Documenter les interfaces REST avec OpenAPI et Swagger
← Retour à Spring Boot 4 Complete Guide