LibraryLearning
Back to course

APIs and Integration • Lesson 4

How APIs Work

20 minute lesson

Learning objectives

  • Understand APIs as contracts
  • See integration risk more clearly
  • Know what makes APIs brittle

What Is It?

An API (Application Programming Interface) is a defined way for one piece of software to talk to another. Not a vague concept — a concrete interface with specific endpoints, expected inputs, and defined outputs. When your app sends a payment via Stripe, it's calling Stripe's API. When it generates text with OpenAI, it's calling OpenAI's API. When it fetches user data from a database via Supabase, it's calling Supabase's API.

The restaurant analogy is overused but it works when done properly: you're the customer (your app), the kitchen is the backend service (Stripe, OpenAI, your own server), and the waiter is the API. You don't walk into the kitchen and grab food yourself — you interact through the waiter using a defined menu (the API's endpoints). The kitchen can be completely rebuilt, the food can be prepared differently, as long as the menu and the waiter interface stay the same.

What makes APIs powerful is the interface contract. Stripe doesn't expose how it processes cards internally. You just call POST /v1/charges with the right parameters, and Stripe handles the rest. This separation — your code knows what to ask for but not how it's done — is what lets the entire ecosystem of connected services work.

How It Actually Works

Most web APIs today are HTTP-based. You make HTTP requests to specific URLs (called endpoints) with specific methods, headers, and bodies. The server processes the request and returns a response with a status code and a body.

Here's an actual API call to OpenAI:

POST https://api.openai.com/v1/chat/completions
Authorization: Bearer sk-...yourkey...
Content-Type: application/json

{
  "model": "gpt-4o",
  "messages": [
    {"role": "user", "content": "What is the capital of France?"}
  ]
}

And the response:

{
  "id": "chatcmpl-abc123",
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "The capital of France is Paris."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 14,
    "completion_tokens": 9,
    "total_tokens": 23
  }
}

Let's trace what happens:

1. Your code constructs the request It sets the URL (https://api.openai.com/v1/chat/completions), method (POST), headers (Authorization, Content-Type), and body (the JSON with model and messages).

2. Your code sends it over HTTPS This means DNS lookup → TCP connection → TLS handshake → HTTP request. All of the previous articles in this series happen here.

3. OpenAI's servers receive it Their API gateway authenticates your API key (sk-...), routes the request to the right internal service, processes it, and prepares a response.

4. The response comes back Status code 200 OK, Content-Type: application/json, and the JSON body with the completion.

5. Your code parses the response It reads choices[0].message.content to get "The capital of France is Paris."

API Keys and Authentication

APIs require authentication so they can identify who's calling (for billing, rate limiting, and security). The most common patterns:

  • API Keys: A long secret string in a header (Authorization: Bearer sk-...). Simple. Must be kept secret — never hardcode in frontend code or commit to git.
  • OAuth tokens: For acting on behalf of a user (more on this in the OAuth article). Used when you need access to a user's data in another service.
  • Basic Auth: Base64-encoded username:password in the Authorization header. Old, mostly replaced by API keys.

Rate Limits

Every API has rate limits — maximums on how many requests you can make per second/minute/day. Exceeding them returns a 429 Too Many Requests response. APIs include headers like X-RateLimit-Remaining and Retry-After to help you manage this. Good API integration code handles 429s gracefully with exponential backoff.

Versioning

APIs version their endpoints (/v1/, /v2/) so they can make breaking changes without breaking existing integrations. When you see /v1/ in a URL, that's the API provider promising that v1 behaviour won't change. When they release v2 with different behaviour, old integrations keep working.

The Jargon Decoded

  • Endpoint — A specific URL that the API exposes for a specific operation. https://api.stripe.com/v1/charges is an endpoint. Each endpoint maps to a resource and accepts specific HTTP methods.
  • API Key — A secret string that authenticates your requests to an API. Treat it like a password. Never expose it in frontend JavaScript or public repositories.
  • Base URL — The root URL of an API. https://api.openai.com — all endpoints are paths relative to this.
  • Request Body — The data you send with POST/PUT/PATCH requests. Usually JSON. Defined by the API's schema.
  • Response Body — The data the API sends back. Usually JSON. Defined by the API's schema.
  • Rate Limiting — A cap on how many requests you can make per unit time. Designed to prevent abuse and ensure fair use. Exceeding it gives a 429 error.
  • SDK (Software Development Kit) — A library the API provider ships so you can call the API without manually constructing HTTP requests. openai.chat.completions.create(...) is an SDK call that handles the HTTP underneath.
  • Webhook — The reverse of an API call: the server calls you when something happens. Stripe calls your endpoint when a payment succeeds. (More in the webhooks article.)
  • Pagination — When an API response has many results, it returns them in pages. You get the first 20, then request the next 20, etc. Look for next_cursor, page, or offset parameters.

Why This Matters When You're Building

Every external service integration in your vibe-coded app is an API call. Stripe, SendGrid, Twilio, OpenAI, GitHub, Slack, Supabase — all APIs. The patterns are the same even though the specific endpoints differ.

Understanding APIs means:

You can read API documentation. When AI generates code to call an API, you can verify it's using the right endpoint, method, and parameters by checking the docs — instead of hoping the AI is up to date.

You can debug integration failures. "My Stripe payment failed" is too vague. "I'm getting a 400 from POST /v1/payment_intents with the error amount must be at least $0.50" is debuggable.

You know what to protect. API keys in client-side JavaScript are readable by anyone who opens DevTools. Always call external APIs from your server (or a serverless function), not from the browser. The browser sends the API key to the user's machine. Don't do that.

You can handle failures properly. Networks fail. Rate limits get hit. APIs go down. Code that assumes every API call succeeds will fail in production. Handle errors explicitly.

What To Tell The AI

"I'm integrating the Stripe API to process one-time payments. Write me a Next.js API route that creates a PaymentIntent server-side and returns the client secret to the frontend. Explain why the secret key must stay server-side."

"My OpenAI API calls are hitting rate limits during peak usage. Write code that implements exponential backoff with jitter on 429 responses — retry after 1s, then 2s, 4s, 8s with random jitter. Cap at 5 retries."

"I need to call a third-party API that requires an API key. Show me the correct pattern for storing and accessing this key in a Next.js app using environment variables — development and production — so it never appears in client-side code."

"I'm building a feature that calls the GitHub API to list a user's repositories. Walk me through authenticating with a personal access token, paginating through all results, and handling API errors gracefully."

"The API I'm integrating doesn't have an official SDK. Show me how to build a minimal wrapper class that handles authentication headers, base URL, error parsing, and retries — so I'm not repeating that setup in every API call."

Common Misconceptions

"The SDK is the API." The SDK is a wrapper around the API. OpenAI's Python library is not OpenAI's API — it's a convenience layer that makes HTTP calls. This matters when the SDK is outdated, unavailable in your language, or when you need to do something the SDK doesn't support. Knowing the underlying HTTP API means you're never blocked.

"An API call is instantaneous." API calls are network requests. They take 50-3000ms depending on the service, server location, and what the API is doing internally. Code that calls an API synchronously without handling latency will freeze UIs and time out under load. Always think about: what happens if this takes 2 seconds? What happens if it times out?

"If there's no error, it worked." Status code 200 doesn't always mean success at the business logic level. Always check the response body. Many APIs return 200 OK with {"success": false, "error": "..."} in the body. Read the docs for what success actually looks like in that API.

"I can call external APIs from the browser." You can, if the API supports browser-side calls (and has CORS headers to allow it). But for APIs requiring secret keys (most of them), you absolutely should not — the key will be visible in your JavaScript and anyone can steal it to use your API quota. Always proxy calls through your server.

Sources

  • Stripe API Reference — Arguably the best-designed API documentation in the industry. Study it as a benchmark.
  • OpenAI API Documentation — Practical reference for a modern AI API
  • HTTP APIs vs SDKs — Thoughtworks — Discussion of API design principles
  • APIs for Beginners — freeCodeCamp — Non-technical introduction to the concept
  • REST API Best Practices — Microsoft — Production-grade patterns for building and consuming APIs

Checkpoint questions

  • What is an API really giving you?
  • Where do API integrations usually break?

Exercise

Take one integration you use and list its trust assumptions and failure points.

Memory recall

Quick quiz

Use retrieval, not rereading. Answer from memory, then check the feedback.

1. What is an API really giving you?

2. Where do API integrations usually break?

3. Why should builders think of APIs as risk surfaces?

Progress

Mark this lesson complete when done

Next lesson