0Pricing
Spring Boot 4 Microservices & REST APIs · Урок

Документирование конечных точек и моделей

Описывайте операции с помощью аннотаций

«Документирование конечных точек и моделей» — бесплатный урок Spring Boot 4 Microservices & REST APIs на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Boot 4 Microservices & REST APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Going beyond auto-detection

Auto-generated docs are functional but terse. Annotations from io.swagger.v3.oas.annotations let you add human-friendly descriptions, examples and response details.

@Operation

@Operation documents a single endpoint: a short summary and a longer description shown in the UI.

@Operation(summary = "Get a user by id",
           description = "Returns a single user or 404 if not found")
@GetMapping("/users/{id}")
public User get(@PathVariable Long id) {
    return service.find(id);
}

@Parameter

@Parameter describes a path, query or header parameter - its meaning, whether it is required, and an example value.

@GetMapping("/users")
public List<User> search(
    @Parameter(description = "Filter by city", example = "Berlin")
    @RequestParam(required = false) String city) {
    return service.search(city);
}

@ApiResponses

Use @ApiResponses to document each possible HTTP status and what it means, including error cases.

@ApiResponses({
  @ApiResponse(responseCode = "200", description = "User found"),
  @ApiResponse(responseCode = "404", description = "User not found")
})
@GetMapping("/users/{id}")
public User get(@PathVariable Long id) { ... }

@Schema on models

@Schema documents a DTO and its fields - descriptions, examples, and constraints that appear in the model section of the UI.

public class User {
    @Schema(description = "Unique id", example = "42")
    private Long id;

    @Schema(description = "Email address", example = "a@b.com")
    private String email;
}

Marking required fields

Set requiredMode to mark a field as mandatory in the schema, so consumers know it must be present in requests.

@Schema(description = "Username",
        requiredMode = Schema.RequiredMode.REQUIRED,
        example = "neo")
private String username;

Documenting request bodies

@RequestBody (the Swagger one) describes the payload. Often the DTO's own @Schema annotations are enough, but you can add a description and example here too.

@PostMapping("/users")
public User create(
    @io.swagger.v3.oas.annotations.parameters.RequestBody(
        description = "New user data", required = true)
    @org.springframework.web.bind.annotation.RequestBody User user) {
    return service.save(user);
}

Hiding things from docs

Use @Hidden on a controller, method, or field to exclude it from the generated documentation - handy for internal endpoints.

@Hidden
@GetMapping("/internal/metrics")
public Metrics internalOnly() { ... }

Grouping with @Tag

@Tag groups related endpoints under a named, described section in the UI - e.g. all user endpoints under "Users".

@Tag(name = "Users", description = "User management operations")
@RestController
@RequestMapping("/users")
public class UserController { ... }

Examples improve usability

Concrete example values on parameters and schema fields make the docs far more useful: consumers can copy realistic payloads instead of guessing formats.

Validation annotations show up too

SpringDoc reflects Jakarta Bean Validation annotations (@NotNull, @Size, @Min) into the schema as constraints, so your validation rules become part of the documented contract.

Quick Check

Check your annotation knowledge.

Recap

You enriched the spec with annotations:

  • @Operation + @ApiResponses describe endpoints and statuses
  • @Parameter documents inputs
  • @Schema documents DTO fields and required-ness
  • @Tag groups, @Hidden excludes

Часто задаваемые вопросы

Урок «Документирование конечных точек и моделей» бесплатный?

Да — полный текст урока «Документирование конечных точек и моделей» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Boot 4 Microservices & REST APIs, подпишись на CoddyKit PRO. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.

Чему я научусь в уроке «Документирование конечных точек и моделей»?

Описывайте операции с помощью аннотаций Ты практикуешь Spring Boot 4 Microservices & REST APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Spring Boot 4 Microservices & REST APIs?

Предыдущий опыт не требуется. Spring Boot 4 Microservices & REST APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Документирование конечных точек и моделей»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Spring Boot 4 Microservices & REST APIs?

Да. Каждый урок Spring Boot 4 Microservices & REST APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Добавление SpringDoc в проект
  2. Документирование конечных точек и моделей
  3. Настройка спецификации OpenAPI
  4. Swagger UI
← Назад к Spring Boot 4 Microservices & REST APIs