Kihagyás

OpenAPI and Swagger

The OpenAPI Specification (OAS) is a language-independent standard for describing HTTP APIs. An OpenAPI document can define paths, operations, parameters, request bodies, responses, schemas, authentication methods, and reusable components in JSON or YAML.

Swagger is a family of tools associated with OpenAPI. Examples include:

  • Swagger UI: interactive HTML documentation;
  • Swagger Editor: editing and validation of OpenAPI documents;
  • Swagger Codegen: generation of client libraries and server stubs.

The terms are related but not interchangeable: OpenAPI is the specification, while Swagger refers primarily to tooling.

Swagger UI

API links

How Does OpenAPI Support Testing?

Interactive Examination

Swagger UI can send HTTP requests from the browser and display response bodies, headers, and status codes. This is useful for exploration and demonstrations, but manually pressing Execute is not a repeatable automated test.

Contract-Based Testing

An OpenAPI document can serve as a machine-readable API contract. Testing tools can use it to check whether:

  • requests use declared paths, parameters, and schemas;
  • responses use documented status codes and content types;
  • response bodies conform to declared schemas;
  • required fields and validation constraints are respected.

The contract must itself be reviewed. A response can conform perfectly to an incorrect or incomplete OpenAPI document.

Test Generation

Tools can derive candidate inputs and tests from the contract, including:

  • valid requests;
  • omitted required fields;
  • invalid types or formats;
  • boundary values;
  • undocumented status codes;
  • schema-violating responses.

Code generators primarily create clients and server stubs. They do not by themselves prove that the API behaves correctly; meaningful assertions still require requirements and test oracles.

Change Detection and CI/CD

An OpenAPI diff tool can compare two contract versions and report changes such as removed fields, new required parameters, or modified response schemas. CI pipelines may combine:

  1. syntax and schema validation;
  2. compatibility analysis;
  3. generated-client compilation;
  4. contract and integration tests;
  5. publication of API documentation.

Compatibility is contextual

Not every textual difference is breaking, and some behavioural breaking changes are invisible in the schema. Compatibility decisions must consider actual clients, versioning rules, and documented semantics.

FastAPI Exercise

FastAPI derives an OpenAPI description from Python type annotations, route declarations, validation rules, and metadata. It normally exposes Swagger UI and ReDoc automatically.

OpenAPI and FastAPI

Create and activate a virtual environment:

1
2
3
4
5
mkdir fastapi-openapi-demo
cd fastapi-openapi-demo

python3 -m venv venv
source venv/bin/activate

On Windows PowerShell, activate it with:

1
.\venv\Scripts\Activate.ps1

Install FastAPI and Uvicorn:

1
python -m pip install fastapi "uvicorn[standard]"

Create main.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from fastapi import FastAPI, HTTPException, Path
from pydantic import BaseModel


app = FastAPI(
    title="Demo API",
    description="A small API used to demonstrate OpenAPI documentation.",
    version="1.0.0",
)


class User(BaseModel):
    id: int
    name: str
    email: str


USERS = {
    1: User(id=1, name="Elek Teszt", email="elek@example.com"),
    2: User(id=2, name="Anna Kiss", email="anna@example.com"),
}


@app.get("/hello", tags=["Hello"])
def hello():
    return {"message": "Hello, FastAPI!"}


@app.get(
    "/users/{user_id}",
    response_model=User,
    responses={404: {"description": "User not found"}},
    tags=["Users"],
)
def get_user(user_id: int = Path(ge=1)):
    user = USERS.get(user_id)
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return user

Run the application:

1
uvicorn main:app --reload

Here, main is the module name and app is the FastAPI object.

Open:

Use Swagger UI to call both an existing and a missing user:

  • GET /users/1 should return HTTP 200;
  • GET /users/999 should return HTTP 404;
  • GET /users/0 should fail path-parameter validation.

What is Uvicorn?

Uvicorn is an ASGI server implementation used to run asynchronous Python web applications. FastAPI is the web framework; Uvicorn is the server that hosts the application.

What is FastAPI?

FastAPI is a Python web framework for building APIs using standard type annotations. It can generate an OpenAPI description and interactive documentation from application declarations.

Spring Boot Exercise

The springdoc-openapi library can derive an OpenAPI description from Spring configuration, controller structure, validation constraints, and annotations, and can provide Swagger UI.

OpenAPI and Spring Boot

Create a Maven project with a current compatible Spring Boot release and Java 17 or later. Add:

  • spring-boot-starter-web;
  • spring-boot-starter-validation;
  • spring-boot-starter-test;
  • a springdoc-openapi-starter-webmvc-ui version compatible with the selected Spring Boot version.

At the time of this material's revision, Spring Boot 4 projects use the springdoc-openapi 3.x line. Always check the springdoc compatibility information when changing either dependency.

The springdoc dependency for a current Spring Boot 4 project is:

1
2
3
4
5
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>3.1.0</version>
</dependency>

Application entry point:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package hu.demo.openapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class OpenApiDemoApplication {

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

Create UserController.java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package hu.demo.openapi;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import org.springframework.http.HttpStatus;
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.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


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

    @GetMapping
    @Operation(summary = "List users")
    public List<User> listUsers() {
        return List.of(
            new User(1L, "Elek Teszt", "elek@example.com"),
            new User(2L, "Anna Kiss", "anna@example.com")
        );
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    @Operation(summary = "Create a user")
    public User createUser(@Valid @RequestBody CreateUserRequest request) {
        return new User(100L, request.name(), request.email());
    }
}


record User(Long id, String name, String email) {}


record CreateUserRequest(
    @NotBlank String name,
    @NotBlank @Email String email
) {}

Run the application and open:

Verify at least:

  • GET /api/users returns HTTP 200 and an array;
  • a valid POST /api/users returns HTTP 201;
  • a missing name or invalid email is rejected with HTTP 400.

Generated documentation is not automatically complete

Frameworks can infer paths and schemas, but they cannot infer every business rule, security requirement, example, or semantic guarantee. Generated OpenAPI documents must therefore be reviewed and tested like other development artefacts.


Utolsó frissítés: 2026-09-04 08:34:02