Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท Projects and Practice

Project: Design a Bookstore API Contract

Build a complete design-first OpenAPI contract for a bookstore: requirements, paths, schemas, errors and examples, then check it with a runnable structural validator.

In this project you act as the API designer for a small online bookstore. You will write the contract first, before any server code exists, using the habits from the previous chapters: a clear operationId for every operation, reusable components, one error shape, examples everywhere and a checker that proves the document is consistent.

The OpenAPI tools themselves cannot run on this site, so the YAML below is read-only and the same document, expressed as JSON, is loaded by a Python stand-in checker that runs here. The checker performs the kind of structural checks that tools such as Spectral and the OpenAPI validators do.

Requirements

The bookstore API must let clients:

  1. List books with paging, and search by title text.
  2. Read one book by ID.
  3. Create a book (staff only).
  4. Place an order for one or more books.

Rules we decide up front:

  • JSON only; errors use application/problem+json.
  • Collections are plural nouns; IDs are opaque strings.
  • Staff operations need a bearer token; reading is public.
  • Money is an object with an integer amount in minor units and an ISO 4217 currency code, never a floating-point number.

Step 1: the skeleton

YAML
openapi: 3.1.0
info:
  title: Bookstore API
  version: 1.0.0
  description: Browse the catalog and place orders.
servers:
  - url: https://api.example.com/v1
tags:
  - name: Books
  - name: Orders

Step 2: components first

Design the shared pieces before the paths that use them:

YAML
components:
  securitySchemes:
    staffToken:
      type: http
      scheme: bearer
  schemas:
    Money:
      type: object
      required: [amount, currency]
      properties:
        amount: {type: integer, description: Minor units (cents), examples: [1299]}
        currency: {type: string, pattern: "^[A-Z]{3}$", examples: [USD]}
    Book:
      type: object
      required: [id, title, price]
      properties:
        id: {type: string, examples: [b-1024]}
        title: {type: string, examples: [Dune]}
        price: {$ref: "#/components/schemas/Money"}
    NewBook:
      type: object
      required: [title, price]
      properties:
        title: {type: string}
        price: {$ref: "#/components/schemas/Money"}
    Problem:
      type: object
      required: [title, status]
      properties:
        title: {type: string}
        status: {type: integer}
        detail: {type: string}
  responses:
    NotFound:
      description: The resource does not exist.
      content:
        application/problem+json:
          schema: {$ref: "#/components/schemas/Problem"}

Step 3: the paths

YAML
paths:
  /books:
    get:
      operationId: listBooks
      summary: List books
      tags: [Books]
      parameters:
        - {name: q, in: query, schema: {type: string}, description: Title search text}
        - {name: limit, in: query, schema: {type: integer, minimum: 1, maximum: 100, default: 20}}
      responses:
        "200":
          description: A page of books.
          content:
            application/json:
              schema: {type: array, items: {$ref: "#/components/schemas/Book"}}
    post:
      operationId: createBook
      summary: Create a book
      tags: [Books]
      security: [{staffToken: []}]
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: "#/components/schemas/NewBook"}
      responses:
        "201":
          description: Created.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Book"}
  /books/{bookId}:
    get:
      operationId: getBook
      summary: Get a book
      tags: [Books]
      parameters:
        - {name: bookId, in: path, required: true, schema: {type: string}}
      responses:
        "200":
          description: The book.
          content:
            application/json:
              schema: {$ref: "#/components/schemas/Book"}
        "404": {$ref: "#/components/responses/NotFound"}

The orders path follows the same pattern. Write POST /orders yourself as an exercise: its body is {items: [{bookId, quantity}]} and it answers 201 with an Order that has id, items and a total of type Money.

Step 4: check the contract

Here is the same document in compact JSON form, loaded by a checker that verifies four things tools check first: every operationId is present and unique, every path variable is declared as a path parameter, every $ref points at something that exists, and every operation has at least one success response.

Python Stand-in: structural checker for the bookstore contract

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The sample deliberately contains mistakes in /orders/{orderId}: a duplicate operationId, an undeclared path variable, a broken $ref and no success response. Fix your own copy until the report is empty.

Step 5: add examples and a mock

Add an examples entry to the Book response, then serve the file with the Prism mock so that a front-end developer can call GET /books/b-1024 at once. Finally, lint with the style rules from the governance lesson.

Stretch goals

  • Add cursor pagination with nextCursor in the list response.
  • Add a 409 Conflict response to createBook for duplicate ISBNs.
  • Add Location header documentation on 201 responses.
  • Split the document into files and bundle it (see splitting and bundling).

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Why model money as an integer amount plus a currency code?

    Minor units avoid binary rounding problems, and the code states which currency the amount uses.
  2. 2. In the checker, which mistake means a path variable was never declared?

    Every {variable} in a path template needs a parameter with in: path and required: true.
  3. 3. Why design the components before the paths?

    Reusable components keep the contract consistent; order in the file does not matter to tools, but the design thinking does.

Summary

  • You designed a contract: requirements, skeleton, components, paths, checks.
  • Decisions such as money format and error shape were made once and reused.
  • A structural checker finds duplicate IDs, undeclared path variables and broken references.
  • Mocks, linting and bundling continue the workflow from the contract.
  • The Python checker is a stand-in for real validators.

Next: Project: a spec quality gate for CI