Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

API
APIs: REST & GraphQL
0/11 completed
Beginner
What is an API?HTTP methods, status codes and headersJSON
Intermediate
REST design principlesErrors and validationPagination, filtering and sortingGraphQL basics
Advanced
Versioning and cachingRate limiting and idempotencyOpenAPI documentation
Pro
Webhooks, real-time APIs and API security
Tracks / APIs: REST & GraphQL / Advanced

OpenAPI documentation

An API is only as good as its documentation. OpenAPI (formerly Swagger) is the standard, machine-readable way to describe a REST API: every endpoint, parameter, request body, response and error. From one OpenAPI file, tools generate interactive docs, client libraries in many languages, mock servers and tests.

An OpenAPI document

OpenAPI documents are written in YAML (or JSON). Here's a small but complete one:

yaml
openapi: 3.1.1
info:
  title: Shop API
  version: 1.4.0
  description: Products and orders for the Learn to Code shop.
servers:
  - url: https://api.myshop.example/v1

paths:
  /products:
    get:
      summary: List products
      operationId: listProducts
      tags: [Products]
      parameters:
        - name: category
          in: query
          schema: { type: string, enum: [kitchen, office, garden] }
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 20 }
      responses:
        '200':
          description: A page of products
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Product' }
    post:
      summary: Create a product
      operationId: createProduct
      tags: [Products]
      security: [{ bearerAuth: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/NewProduct' }
      responses:
        '201':
          description: Created
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Product' }
        '422':
          $ref: '#/components/responses/ValidationError'

  /products/{id}:
    get:
      summary: Get one product
      operationId: getProduct
      tags: [Products]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: integer }
      responses:
        '200':
          description: The product
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Product' }
        '404':
          description: Not found

components:
  schemas:
    NewProduct:
      type: object
      required: [name, price]
      properties:
        name: { type: string, minLength: 2, maxLength: 100, example: Mug }
        price: { type: number, exclusiveMinimum: 0, example: 8.99 }
        category: { type: string, enum: [kitchen, office, garden] }
    Product:
      allOf:
        - $ref: '#/components/schemas/NewProduct'
        - type: object
          required: [id]
          properties:
            id: { type: integer, example: 42 }
  responses:
    ValidationError:
      description: The request body failed validation
      content:
        application/problem+json:
          schema:
            type: object
            properties:
              title: { type: string }
              errors: { type: array, items: { type: object } }
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
Section Holds
info Title, version, description, contact, licence
servers Base URLs (production, staging)
paths Each URL, its methods (operations), parameters, bodies and responses
components Reusable pieces: schemas, responses, parameters, securitySchemes
security Which authentication an operation needs

Schemas use JSON Schema, the same vocabulary as many validation tools: type, required, enum, minimum, maxLength, format: email, $ref. OpenAPI 3.1 is fully compatible with JSON Schema; 3.2 (released in 2025) adds features such as streaming responses, but 3.1 is the version with the widest tool support today.

What you get from it

Tool Gives you
Swagger UI, Redoc, Scalar Interactive documentation with "Try it out" buttons
openapi-generator, openapi-typescript, Orval Typed client libraries for TypeScript, Python, Java, Go…
Prism, Microcks A mock server from the spec, so the frontend can start before the backend exists
Spectral Linting: consistent naming, every operation documented, error responses defined
Schemathesis, Dredd Tests that call your API and check it matches the spec

Code first or design first?

  • Design first: write the OpenAPI file, review it with the API's users, then implement. Best for public APIs and APIs shared between teams.
  • Code first: generate the spec from your code (FastAPI and Spring's springdoc do this automatically; in Node, tools like zod-openapi, @asteasolutions/zod-to-openapi, Fastify or tsoa). Less duplication, and the docs can't drift from the code.

Here's the code-first idea in miniature: Zod schemas validate requests and produce the JSON Schemas for the document, so there's a single source of truth:

Node.js · editable

You'd then serve Swagger UI or Scalar pointing at /openapi.json.

Writing good API docs

A spec alone isn't enough. Great API documentation also has:

  • A quick start: how to get a key and make a first successful request in five minutes.
  • Authentication explained with a working example.
  • Real examples for every request and response, including errors.
  • Guides for common tasks ("accept a payment", "sync orders").
  • Conventions in one place: pagination, errors, rate limits, versioning, dates and IDs.
  • A changelog, with deprecations announced in advance.

Stripe, Twilio and GitHub are famous for their docs; borrow their ideas.

Practice

  1. Add a GET /orders/{id} operation to the YAML document with a 200 and a 404 response.
  2. Add a DELETE /products/{id} operation that requires bearerAuth and returns 204.
  3. Extend the Zod example with a GET /products operation whose 200 response is an array of Product.
✎ Check your understanding

1.What is an OpenAPI document?

2.Where do reusable schemas go in an OpenAPI document?

3.What's an advantage of the code-first approach?

← Rate limiting and idempotency