Skip to content

ADR - Clean OpenAPI 3.0 Documentation using 'Code First Approach'

Status

  • Proposed
  • Trialing
  • Under review
  • Approved
  • Retired

Context & Scope

While adopting OpenAPI 3.0 standards using springdoc, we end up adding lot of documentation to native controller of each API.

  • API contract is not clearly visible
  • reduces the readability of the API
  • business logic & documentation at the same place

Tradeoff Analysis

  • To maintain clean API documentation
  • API, Controller segregation
  • adopt future changes w.r.t to documentation or contract change

Proposed Solution:

  • Introduce API, Controller Layer Segregation
  • API will have contract, definitions & OpenAPI documentation
  • Controller will implement the API contract with clean code

#References:

  1. ‘Code First’ API Documentation

Sample Refactor in Storage Patch API

Sample Example code

Lets consider a TODO API with normal Crud operation

First we write Interface and define necessary annotations.

@RequestMapping("/api/todos")
@Tag(name = "Todo API", description = "euismod in pellentesque ...")
interface TodoApi {

  @GetMapping
  @ResponseStatus(code = HttpStatus.OK)
  List<Todo> findAll();

  @GetMapping("/{id}")
  @ResponseStatus(code = HttpStatus.OK)
  Todo findById(@PathVariable String id);

  @PostMapping
  @ResponseStatus(code = HttpStatus.CREATED)
  Todo save(@RequestBody Todo todo);

  @PutMapping("/{id}")
  @ResponseStatus(code = HttpStatus.OK)
  Todo update(@PathVariable String id, @RequestBody Todo todo);

  @DeleteMapping("/{id}")
  @ResponseStatus(code = HttpStatus.NO_CONTENT)
  void delete(@PathVariable String id);
}

Then we derive existing controllers from interface for controller implementation

@RestController
class TodoController implements TodoApi {
  // method implementations  
}

Consequences

  • Requires changes across services and code refactoring.
  • No Breaking functional changes.
Edited by Srinivasan Narayanan