AlgoViz

API design introduction

easy 24 min

An API is a contract: it says what a program may ask for and what it gets back, and it hides how the work is done.

See it run

One request from tap to screen, what can refuse it, and how nouns become endpoints.

Operations

Search products

A shopper searches for headphones. Nine messages, there and back.

Step 1 of 9

Tap

Our systemShopperMobile appAPI gatewayAPI serverDatabase

The shopper types headphones and taps search.

Step 1: Tap

GET /products?q=headphones HTTP/1.1Authorization: Bearer fake-token-for-docsdef search(request):    user = authenticate(request)       # 401 if unknown    allow(user, "products:read")       # 403 if not allowed    q = validate(request.query)        # 422 if wrong    rows = db.find_products(q)    return 200, to_json(rows, page=1)
Round trips
1, when connected
Ends with
200
New connection
3 with TLS 1.3

Say the steps in order: receive, authenticate, authorize, validate, process, respond.

In the real world

The same api design introduction doing real jobs. Pick one and step through it.

The team replaces the database. The apps do not notice.

Step 1 of 2

Today

Our systemGET /productsPhone appAPI serverPostgreSQL

The app calls the API, the API reads PostgreSQL.

Step 1: Today

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • A verb in every URL

    minor

    The method already says what to do. Verbs grow into hundreds of unrelated addresses.

    Wrong
    POST /createNewProductPOST /deleteProductFromCatalog
    Right
    POST   /productsDELETE /products/{id}
  • GET that changes something

    critical

    Crawlers, link previews and retries call GET freely. Each call would change data.

    Wrong
    GET /orders/789/cancel
    Right
    POST /orders/789/cancellation
  • 200 with an error inside

    major

    Caches, gateways, dashboards and retries read the status code and believe it worked.

    Wrong
    return 200, {"error": "not found"}
    Right
    return 404, {"error": "product_not_found"}
  • Trusting the address

    critical

    Anyone can change the id in a URL. The server must check who owns the order.

    Wrong
    return db.order(order_id)
    Right
    order = db.order(order_id)if order.user_id != user.id:    return 404, {"error": "order_not_found"}

Interview tips

  • How to explain it

    • An API is a contract between programs.
    • URL is the noun, method is the verb, status is the outcome.
    • What is behind it can change.
  • Memory trick: WAITER

    • Web-based, Application interface, Intermediary.
    • Transport by HTTP methods, Endpoints define resources.
    • Request and response.
  • In five minutes

    • Three to five endpoints.
    • One error per endpoint.
    • Say paging and idempotency out loud.
  • Avoid

    • Endpoints copied from tables.
    • Lists without a limit.
    • Sessions inside one server.