Skip to lesson

Practice: OpenAPI documentation

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

A frontend developer trusts the 200 in the spec and never handles the 201 the server really sends. These mistakes show how docs drift from the API, each with real generated output.

Mistake 1: trusting the generated status codes

The generated spec documents what the method signature shows, not what the method does. Here is a coupon controller with no docs annotations.

Example 1 · CouponController.java with no docs annotations

Runs in: the docs-lab practice project (Spring Boot 4.1 + springdoc-openapi)

Java
// src/main/java/com/shoplite/lab/CouponController.java (docs-lab, before documenting)package com.shoplite.lab;
import java.net.URI;import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;
import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.DeleteMapping;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.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.server.ResponseStatusException;
import jakarta.validation.Valid;
@RestController@RequestMapping("/lab/coupons")class CouponController {
    private final Map<String, Coupon> coupons = new ConcurrentHashMap<>(Map.of(            "FEST10", new Coupon("FEST10", 10, true),            "HOSTEL5", new Coupon("HOSTEL5", 5, false)));
    @GetMapping    List<Coupon> list() {        return coupons.values().stream().sorted(Comparator.comparing(Coupon::code)).toList();    }
    @GetMapping("/{code}")    Coupon get(@PathVariable String code) {        Coupon coupon = coupons.get(code);        if (coupon == null) {            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Coupon " + code + " was not found.");        }        return coupon;    }
    @PostMapping    ResponseEntity<Coupon> create(@Valid @RequestBody CouponRequest request) {        Coupon coupon = new Coupon(request.code(), request.percentOff(), true);        coupons.put(coupon.code(), coupon);        return ResponseEntity.created(URI.create("/lab/coupons/" + coupon.code())).body(coupon);    }
    @DeleteMapping("/{code}")    ResponseEntity<Void> delete(@PathVariable String code) {        if (coupons.remove(code) == null) {            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Coupon " + code + " was not found.");        }        return ResponseEntity.noContent().build();    }}
Sample output
$ curl http://localhost:8080/v3/api-docs.yaml        (paths only)
paths:
  /lab/coupons:
    get:
      tags:
      - coupon-controller
      operationId: list
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/Coupon"
    post:
      tags:
      - coupon-controller
      operationId: create
      requestBody:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CouponRequest"
        required: true
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Coupon"
  /lab/coupons/{code}:
    ...
    delete:
      tags:
      - coupon-controller
      operationId: delete
      parameters:
      - name: code
        in: path
        required: true
        schema:
          type: string
      responses:
        "200":
          description: OK

$ curl -i -X DELETE http://localhost:8080/lab/coupons/HOSTEL5
HTTP/1.1 204 
Date: Fri, 16 Oct 2026 06:43:51 GMT

What this code does

  • POST is documented as "200": OK although it returns 201 with Location; DELETE as "200" although it returns 204 with no body.
  • There is no 400 or 404 anywhere, though the server sends both as application/problem+json.
  • The tag coupon-controller and operationIds list, create, delete are class and method names, not names a reader would choose.

Every operation gets "200": OK unless you say otherwise. A create that returns ResponseEntity.created(...) is documented as 200, a delete that returns noContent() as 200 with no word about its 204, and none of the errors appear.

The fix is a habit: for each endpoint, open the contract table and write one @ApiResponse per status it lists. Then press Try it out once for each code and compare the live result with the docs.

Mistake 2: docs that promise rules the code does not check

springdoc copies Bean Validation annotations into the schema whether or not they run. Here @Valid was dropped during a refactor.

Example 2 · Docs say maximum 50, the server accepts 90

Runs in: the docs-lab practice project (Spring Boot 4.1 + springdoc-openapi)

Java
// CouponController.java: @Valid was dropped from create() during a refactor@Operation(operationId = "createCoupon", summary = "Create a coupon")@ApiResponse(responseCode = "201", description = "Created",        headers = @Header(name = "Location", description = "URL of the new coupon"))@ApiResponse(responseCode = "400", description = "Invalid fields",        content = @Content(mediaType = "application/problem+json",                schema = @Schema(implementation = ProblemDetail.class)))@PostMappingResponseEntity<Coupon> create(@RequestBody CouponRequest request) {    Coupon coupon = new Coupon(request.code(), request.percentOff(), true);    coupons.put(coupon.code(), coupon);    return ResponseEntity.created(URI.create("/lab/coupons/" + coupon.code())).body(coupon);}
Sample output
$ curl http://localhost:8080/v3/api-docs.yaml        (trimmed)
...
    CouponRequest:
      type: object
      properties:
        code:
          type: string
          description: Capital letters and digits
          example: DIWALI15
          maxLength: 12
          minLength: 4
        percentOff:
          type: integer
          format: int32
          description: Discount in percent
          example: 15
          maximum: 50
          minimum: 1
      required:
      - code

$ curl -i -X POST -H "Content-Type: application/json" -d '{"code":"MEGA90","percentOff":90}' http://localhost:8080/lab/coupons
HTTP/1.1 201 
Location: /lab/coupons/MEGA90
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:44:47 GMT

{"code":"MEGA90","percentOff":90,"active":true}

(with @Valid back in place)
$ curl -i -X POST -H "Content-Type: application/json" -d '{"code":"MEGA90","percentOff":90}' http://localhost:8080/lab/coupons
HTTP/1.1 400 
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:43:50 GMT
Connection: close

{"detail":"Invalid request content.","instance":"/lab/coupons","status":400,"title":"Bad Request"}

What this code does

  • The schema still shows maximum: 50 and minLength: 4, copied from CouponRequest's annotations, and the operation still promises a 400.
  • Without @Valid nothing checks them, so a 90% coupon is created with 201. With @Valid the same request gets 400.
  • The docs were right and the code was wrong: put @Valid back and add a controller test that sends an invalid body. The error body comes out A to Z (detail first) because this small lab keeps Jackson 3's default order; ShopLite sets spring.jackson.mapper.sort-properties-alphabetically=false (Exception Handling module) so its bodies follow the contract's order.

The docs still say maximum: 50, but the server accepts 90. A client trusts the docs and skips its own check, and bad data gets in.

The same happens with a documented 400 for a method that can never answer 400, or a 404 on a list endpoint. When docs and behaviour disagree, decide which one is right from the contract, then fix the other. A docs test catches missing status codes; a controller test with an invalid body catches a missing @Valid.

Reading a spec and writing the matching curl requests

A spec is enough to call an API without seeing its code. Here is one curl request for each documented response of a ShopLite endpoint.

Example 3 · From a spec to curl requests, one per response code

Runs in: the shoplite-api Spring Boot project

Terminal
# 1. listCategories: GET, no parameterscurl http://localhost:8080/api/v1/categories# 2. createCategory, success: a JSON body (CategoryRequest), -i to see 201 and Locationcurl -i -X POST http://localhost:8080/api/v1/categories \  -H "Content-Type: application/json" \  -d '{"name": "Smart Watches", "parentId": 1}'# 3. the same again: 409, the name is already used# 4. a name shorter than minLength 2: 400curl -i -X POST http://localhost:8080/api/v1/categories \  -H "Content-Type: application/json" -d '{"name": "S"}'# 5. a parent that does not exist: 422curl -i -X POST http://localhost:8080/api/v1/categories \  -H "Content-Type: application/json" -d '{"name": "Gaming", "parentId": 42}'
Sample output
$ curl http://localhost:8080/api/v1/categories
[{"id":1,"name":"Electronics","parentId":null},{"id":2,"name":"Mobiles","parentId":1},{"id":3,"name":"Laptops","parentId":1},{"id":4,"name":"Accessories","parentId":1},{"id":5,"name":"Books","parentId":null},{"id":6,"name":"Fashion","parentId":null},{"id":7,"name":"Home & Kitchen","parentId":null}]

$ curl -i -X POST http://localhost:8080/api/v1/categories -H "Content-Type: application/json" -d '{"name": "Smart Watches", "parentId": 1}'
HTTP/1.1 201 
Location: http://localhost:8080/api/v1/categories/8
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:50:07 GMT

{"id":8,"name":"Smart Watches","parentId":1}

$ (the same command again)
HTTP/1.1 409 
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:50:07 GMT

{"type":"https://shoplite.example/problems/already-exists","title":"Resource already exists","status":409,"detail":"A category named Smart Watches already exists.","instance":"/api/v1/categories"}

$ curl -i -X POST http://localhost:8080/api/v1/categories -H "Content-Type: application/json" -d '{"name": "S"}'
HTTP/1.1 400 
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:50:07 GMT
Connection: close

{"type":"https://shoplite.example/problems/validation-failed","title":"Validation failed","status":400,"detail":"The request has 1 invalid field.","instance":"/api/v1/categories","errors":[{"field":"name","message":"must be 2-50 characters"}]}

$ curl -i -X POST http://localhost:8080/api/v1/categories -H "Content-Type: application/json" -d '{"name": "Gaming", "parentId": 42}'
HTTP/1.1 422 
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:50:07 GMT

{"type":"https://shoplite.example/problems/rule-broken","title":"Business rule broken","status":422,"detail":"Parent category 42 does not exist.","instance":"/api/v1/categories"}

What this code does

  • Every documented code of createCategory was reached: 201 with Location, 409 for the repeated name, 400 for a one-letter name and 422 for parent 42.
  • Each request was built from the spec alone: the path, the body schema's fields and limits, and the response descriptions.
  • The spec is in the first practice exercise; these calls ran against ShopLite with its seed data.

For each operation, take the method and path; put path parameters into the URL, query parameters after ?, and a request body as JSON with Content-Type: application/json. Then try one request per documented response code, not only the happy path.

Use the schema to build the bad requests: minLength: 2 suggests a one-letter name for the 400, the 409 description tells you to repeat a create, and a $ref to another resource suggests an id that does not exist for the 422.

Interview drill: OpenAPI vs Swagger, code-first vs contract-first

OpenAPI is the specification; Swagger is a family of tools. Here is one operation written code-first, then contract-first.

Java
// Code-first: springdoc builds the spec from this method and its annotations@Operation(operationId = "getCategory", summary = "Get one category")@ApiResponse(responseCode = "200", description = "The category")@ApiResponse(responseCode = "404", ref = "NotFound")@GetMapping("/{id}")CategoryResponse get(@PathVariable Long id) {    return service.get(id);}
// Contract-first: the same operation is written by hand in YAML first (as in the first practice exercise),// and the code is written or generated to match it
  • Single team, API already running: code-first, plus a docs test.
  • Several teams or a public API, agreement before code: contract-first.
  • Either way: the spec is versioned in Git and reviewed like code.

OpenAPI 3.x is the file format. Swagger UI, Swagger Editor and Swagger Codegen are tools from SmartBear that read or write it, and springdoc-openapi is a Spring library that generates it. Saying "Swagger 3.0" for the spec is outdated; "OpenAPI 3.1" is correct.

Code-first generates the spec from the code (ShopLite with springdoc): fast, never describes missing endpoints, but needs annotations and a test to be accurate. Contract-first writes the spec first and builds to it: best when several teams must agree early, but code can drift unless code is generated from the spec or tested against it.

Finish up

Mark complete & continue

Next: Mini project: ShopLite API docs