Skip to content

By the Octri team · Updated

API design best practices, with OpenAPI examples

Share

API design best practices are the habits that make an API predictable to call, from resource names and status codes to errors, pagination and versioning. This guide writes each one in OpenAPI and shows the SDK code it produced.

What are the best practices for API design?

Good API design is a handful of decisions you make once and then repeat on every endpoint. Resources get plural nouns, and the HTTP method says what happens to them. Each response carries the status code that matches what happened. Every error arrives in one shape. Lists page with a cursor, the version sits where clients can see it, and a retried write runs once. Each operation also gets an operationId, a tag and a description, because tools read those as closely as people do.

None of it is clever, and that's the point. Think about house numbers on a street. They run in order, with odd numbers on one side and even on the other, so a stranger can find number 48 without asking anyone. An API works the same way. A developer who has called one of your endpoints should be able to guess how the next one works, and so should the code generator reading your spec.

That second reader is easy to forget. Your OpenAPI file turns into docs, SDKs and AI tool definitions, and each of them copies your design decisions, good or bad, into code other people depend on.

One API, designed twice

I wanted to see what these habits change in practice, so while writing this guide I described one small billing API twice. The first spec has five common mistakes. Its paths are verbs (/getInvoices, /createInvoice), no operation has an operationId or a tag, no error responses are declared, the list takes a page number and returns a bare array, and there's no security scheme. The second spec fixes each one. Everything else, from the invoice fields to the server URL, is the same.

Then I scored both with Octri's spec audit and generated a TypeScript and a Python SDK from each with Octri's generator. The first spec scored 4 out of 10, with 16 findings. The second scored 9.5, and 10 once I'd described the fields of the request body as well. Here's what the generated TypeScript SDK looked like in each case.

First spec Second spec
Namespaces getInvoices, createInvoice, invoice invoices
Create createInvoice.create() invoices.create()
Get one invoice.get({ id }) invoices.get({ invoiceId })
List getInvoices.list({ page }) returns one page invoices.list() yields every page
Error body typed as never typed as Problem
Create after a 503 never retried retried, up to 3 attempts
Diagram comparing two versions of the same billing API spec and the TypeScript SDK generated from each: an operationId and tag change the methods from client.createInvoice.create to client.invoices.create, a cursor and next_cursor turn a one-page list into one that yields every invoice, an error schema types error.data as Problem, and a declared Idempotency-Key header lets the SDK retry a create after a 503.
What four design changes in one billing API spec did to the TypeScript SDK generated from it.

The sections below go through each practice with the OpenAPI that expresses it and what it did to the generated code.

Name resources with plural nouns

A path names a thing, and the method says what to do with it. GET /invoices lists invoices, POST /invoices creates one, and GET /invoices/{invoice_id} fetches one. When the path holds the verb, every new action needs a new path, and nothing tells a reader which paths belong together.

yaml
paths:
  /invoices:
    get: ...      # list invoices
    post: ...     # create an invoice
  /invoices/{invoice_id}:
    get: ...      # get one invoice
  /customers/{customer_id}/invoices:
    get: ...      # one customer's invoices

Name path parameters after the thing they identify. My first spec used /invoice/{id}, and the Python SDK's method took an argument called id, which shadows a Python built-in. The second spec's invoice_id became invoice_id in Python and invoiceId in TypeScript.

Some actions don't fit create, read, update and delete. Voiding an invoice is one. A sub-path such as POST /invoices/{invoice_id}/void keeps the resource in front and the action readable.

Rule of thumb: nest one level at most. /customers/{customer_id}/invoices reads well, and anything deeper usually means the inner resource deserves its own top-level path.

Use methods and status codes for what they mean

HTTP already defines what each method promises. RFC 9110 makes GET, HEAD, OPTIONS and TRACE safe, and PUT and DELETE idempotent along with them, so sending one twice has the same effect as sending it once. POST makes no such promise.

Method Use it to Success status
GET Read a resource or a list 200 OK
POST Create a resource, or run an action 201 Created, or 200 OK for an action
PUT Replace a resource 200 OK or 204 No Content
PATCH Change some fields 200 OK
DELETE Remove a resource 204 No Content

Errors work the same way. A 400 means the request was malformed, 401 means missing or invalid credentials, 403 means the caller isn't allowed, 404 means the resource doesn't exist, 409 means a conflict with the current state, 422 means the input failed validation, and 429 means slow down. A 5xx means the problem is on your side.

Both of my generated SDKs turned these codes into error classes, such as SdkNotFoundError for a 404 and SdkRateLimitError for a 429, so callers can catch the one they handle. That only helps if a missing invoice returns 404. An API that returns 200 with "success": false in the body hides the failure from every tool that reads status codes.

Rule of thumb: when you create something, return 201 and the new resource, with a Location header pointing at it. RFC 9110 describes exactly that for POST.

Give every operation an operationId and a tag

The operationId is the operation's name, and generators use it for the SDK method. The tag groups operations, and generators use it for the namespace.

yaml
/invoices:
  post:
    operationId: createInvoice
    tags: [invoices]
    summary: Create an invoice

Without them, the generator falls back on the path. My first spec got a separate namespace for every path, so the three invoice operations were spread across client.getInvoices, client.createInvoice and client.invoice. The audit explains the risk in its finding: with no operationId, the generated method name "is derived from the path and will move with it". Rename a path and you've renamed a method in every SDK, which is a breaking change for everyone who installed one.

With an operationId and a tag on each, all three landed on client.invoices as list, create and get. The blog post Ten habits for writing great OpenAPI specs covers how to write the names and descriptions themselves.

Send every error in one shape

Pick one error format and use it on every endpoint. RFC 9457, published in July 2023 to replace RFC 7807, defines one called problem details. It uses the application/problem+json media type and five standard members: type, title, status, detail and instance. You can add your own members next to them.

json
{
  "type": "https://api.acme.example/problems/invoice-not-found",
  "title": "Invoice not found",
  "status": 404,
  "detail": "No invoice has the id inv_999.",
  "instance": "/invoices/inv_999"
}

In OpenAPI, define the response once under components and reference it from each operation:

yaml
components:
  responses:
    Problem:
      description: The request failed. The body says why.
      content:
        application/problem+json:
          schema:
            $ref: "#/components/schemas/Problem"
paths:
  /invoices/{invoice_id}:
    get:
      responses:
        "404":
          $ref: "#/components/responses/Problem"

In my first SDK, the decoded error body was typed never, because the spec never said what an error looks like. In the second, error.data was typed as Problem, and each operation exported its own error type, such as CreateInvoiceError. A caller can read error.data.detail with autocomplete. SDK error handling covers the client side of this.

Unofficial Resend API showcase built with Octri, on its Errors page, listing the SDK's error classes from SdkValidationError to SdkTimeoutError and a table mapping status codes 400, 401, 403, 404, 409, 422, 429 and 5xx to their error classes.
An unofficial Resend API showcase built with Octri. Its Errors page lists the error classes the generated SDK raises and the status code behind each.

Page through lists with a cursor

A list endpoint should return one page at a time and tell the caller how to get the next one. There are two common ways. Offset pagination (?offset=40&limit=20) is easy to build, but rows added or deleted between requests shift every page after them, so a client can skip an item or see one twice. Cursor pagination hands back an opaque marker for where the page ended, and the next request starts from there.

yaml
/invoices:
  get:
    operationId: listInvoices
    parameters:
      - name: cursor
        in: query
        schema: { type: string }
      - name: limit
        in: query
        schema: { type: integer, minimum: 1, maximum: 100 }
components:
  schemas:
    InvoiceList:
      type: object
      required: [data]
      properties:
        data:
          type: array
          items: { $ref: "#/components/schemas/Invoice" }
        next_cursor:
          type: [string, "null"]

That shape was enough for the generator to recognize cursor pagination from the names cursor and next_cursor, with no extension in the spec. The TypeScript SDK's client.invoices.list() became a lazy generator that walks every page:

typescript
for await (const invoice of client.invoices.list({ status: "open" })) {
  console.log(invoice.id);
}

The Python SDK got client.invoices.list_paginated(), which does the same. My first spec, with its page number and bare array, produced a list({ page }) that returns one page and leaves the loop, and the question of when to stop, to the caller.

Rule of thumb: wrap every list in an object such as { "data": [...] }, even before you paginate. A bare array has nowhere to put a cursor later without breaking every client.

Unofficial Intercom API showcase built with Octri, on the reference page for GET /conversations, with per_page and starting_after query parameters for cursor pagination, an Intercom-Version header with its allowed versions, and a TypeScript SDK example calling client.conversations.list().
An unofficial Intercom API showcase built with Octri. The list endpoint takes a page size and a cursor, and the Intercom-Version header picks the API version.

Version where clients can see it

Sooner or later you'll need to change something that breaks existing callers. Decide how clients pick a version before that day comes. The two common places are the URL (/v2/invoices) and a header. GitHub uses X-GitHub-Api-Version, and the Intercom page above takes an Intercom-Version header with a list of allowed values. Document what a request without a version gets.

Most changes don't need a new version. Adding an endpoint, an optional parameter or a response field is safe. Removing or renaming a field, changing its type, or making an optional parameter required breaks someone. Adding a value to a response enum can break clients that treat enums as closed, which is why OpenAPI data types recommends SDKs that keep unknown values. How to version API documentation covers the docs side.

Make retried writes safe with idempotency keys

Networks fail halfway. A client sends POST /invoices, the connection drops, and it can't tell whether the invoice was created. Because POST isn't idempotent, RFC 9110 says a client "SHOULD NOT automatically retry a request with a non-idempotent method" without some way to know it's safe. An idempotency key is that way: the client sends a unique key, and the server returns the first result for any repeat with the same key.

yaml
/invoices:
  post:
    operationId: createInvoice
    parameters:
      - name: Idempotency-Key
        in: header
        schema: { type: string }

The Idempotency-Key header has an IETF draft behind it, at version 09 as of 21 November 2026 and still a working group document. That one declaration changed my generated SDK more than I expected. Both SDKs attached a generated key to every POST, but only the second treated createInvoice as safe to retry, so it retried after a 503 with up to 3 attempts. The first SDK never retried the create. The second also exposed an idempotencyKey argument for callers who want to pass their own key. What is an idempotency key? explains how to honor the key on the server.

Declare authentication

Put every way to authenticate in components.securitySchemes, and set security at the top level so it applies to every operation unless one overrides it.

yaml
security:
  - bearerAuth: []
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer

My first spec had none, and the audit's finding says what that costs: the generated client "exposes no authentication configuration". The second SDK's quickstart opened with auth: { bearerAuth: process.env.ACMEBILLING_TOKEN! }. How to document API authentication covers scopes, key rotation and the 401 versus 403 question.

Filter, sort and describe with the schema

Filters belong in query parameters, with one naming convention across the API, such as ?status=open and ?created_after=2026-11-01. When a filter takes a fixed set of values, declare them as an enum. My second spec's status filter pointed at an InvoiceStatus enum, and the TypeScript SDK typed the argument as "draft" | "open" | "paid" | "void", still accepting other strings so a new status wouldn't break old SDKs.

Examples matter just as much, because docs and SDK quickstarts are built from them. I put examples on the Invoice schema and forgot them on InvoiceInput, the body for creating one. The generated quickstart then called create with a customer ID of "customer-1" and a currency of "currency". Add realistic examples to request bodies too, and the first code a developer copies will look like your API.

When you retire an operation, a parameter or a field, mark it deprecated: true in the spec first and keep it working for a stated period. Generated docs show the mark, and SDK doc comments carry it into the editor, so callers hear about it before anything breaks.

API design checklist

  • Paths are plural nouns, nested one level at most, with parameters named after what they identify.
  • Each method is used for what HTTP defines it to do, and every response has an honest status code.
  • POST that creates returns 201 with the new resource and a Location header.
  • Every operation has an operationId, a tag, a summary and a description.
  • Every error uses one shape, such as RFC 9457 problem details, defined once in components.
  • Lists return an object with the items and a cursor for the next page.
  • Clients choose a version in the URL or a header, and a request without one gets a documented default.
  • Writes that clients might retry accept an Idempotency-Key header.
  • Authentication is declared in securitySchemes and applied with security.
  • Filters with fixed values are enums, and request bodies have realistic examples.
  • Retired operations and fields are marked deprecated before they're removed.

API design with Octri

The free spec audit scores your OpenAPI file out of 10 with the rules Octri runs before it generates an SDK, and names the operation and the rule behind every lost point. It's how my two billing specs got their 4 and 10, so you can see which design decisions cost points before anyone installs an SDK.

From the same spec, SDK Studio generates SDKs in ten languages that follow your design. Method names come from your operation IDs and namespaces from your tags. Lists with a cursor get pagination helpers, error schemas become typed errors, and operations that take an Idempotency-Key are retried safely. API Studio publishes the reference with every parameter, response and error on each endpoint's page, next to code samples from those SDKs, and the hosted MCP server gives AI agents one tool per operation. When you change the design, import the new spec and all of it follows.

Share

Keep reading