API (Application Programming Interface)

The contract that lets your code talk to someone else's code.

4 min read

What is an API?

An API is a way for two pieces of software to talk to each other. When you use a weather app, it's calling a weather API to get the forecast. When you log in with Google, that's an API. When Stripe charges your credit card, API.

Think of it as a waiter at a restaurant. You (the client) don't walk into the kitchen and cook your own food. You tell the waiter (the API) what you want, and they bring it back from the kitchen (the server).

javascript
// Your app asks the API for weather data
const response = await fetch("https://api.weather.com/v1/forecast?city=london");
const weather = await response.json();
console.log(weather.temperature); // 12°C

Types of APIs

TypeDescriptionExample
REST APIUses HTTP methods, stateless, most commonTwitter, GitHub, Stripe
GraphQLQuery language, client specifies data shapeGitHub v4, Shopify
SOAPXML-based, enterprise-heavy, strict contractsLegacy banking systems
WebSocketReal-time, bidirectional communicationChat apps, live updates
gRPCBinary protocol, high performanceInternal microservices

REST APIs dominate the web. If someone says "API" without qualifying, they probably mean REST.

Anatomy of an API Request

Every API request has these parts:

javascript
// A complete API request breakdown
const response = await fetch("https://api.example.com/users/123", {
  method: "GET",                          // HTTP method
  headers: {
    "Authorization": "Bearer eyJhbG...",  // Authentication
    "Content-Type": "application/json",   // Data format
    "Accept": "application/json"          // Expected response format
  }
});
ComponentPurposeExample
EndpointURL path to the resource/api/users/123
MethodAction to performGET, POST, PUT, DELETE
HeadersMetadata about the requestAuthorization, Content-Type
BodyData sent with requestJSON payload for POST/PUT
Query paramsFilters and options?page=2&limit=10

Where You'll See This

  • Third-party services - Payment processing, email sending, analytics
  • Backend communication - Your frontend calling your backend
  • Microservices - Services talking to each other
  • Mobile apps - iOS/Android apps fetching data
  • Integrations - Connecting different systems (Slack, GitHub, etc.)
  • Public data - Government data, weather, stocks

API Authentication Methods

MethodHow It WorksUse Case
API KeySecret string in header or query paramSimple integrations
Bearer TokenJWT or OAuth token in Authorization headerUser-specific access
Basic AuthBase64-encoded username:passwordInternal tools
OAuth 2.0Token exchange flow with scopes"Login with Google"
HMACSigned requests with shared secretWebhooks, AWS

Example: Calling an API

javascript
// GET request - fetch data
async function getUser(userId) {
  const response = await fetch(`https://api.example.com/users/${userId}`, {
    headers: {
      "Authorization": `Bearer ${API_TOKEN}`
    }
  });

  if (!response.ok) {
    throw new Error(`API error: ${response.status}`);
  }

  return response.json();
}

// POST request - create data
async function createUser(userData) {
  const response = await fetch("https://api.example.com/users", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${API_TOKEN}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify(userData)
  });

  return response.json();
}

Common Gotchas

⚠️Rate Limiting

Most APIs limit how many requests you can make. Exceed the limit and you'll get a 429 error. Always check the API docs for rate limits and implement backoff strategies.

ℹ️CORS Issues

Browsers block API requests to different domains by default. If you're getting CORS errors in the browser, the API server needs to allow your origin, or you need a backend proxy.

  • Always check response status - A 200 doesn't mean success if the body contains an error object.
  • Handle network failures - APIs go down. Wrap calls in try/catch and have a fallback.
  • Don't expose API keys - Never put secrets in frontend code. Use environment variables and a backend proxy.
  • Version your dependencies - APIs change. Use versioned endpoints (/v1/, /v2/) when available.
  • Read the docs - Every API has quirks. The 10 minutes reading docs saves hours debugging.

Try It

Format API Responses

"An API is just a fancy way of saying 'here's how you can ask me for stuff without learning my entire codebase.'"