Skip to content
ADevGuide Logo ADevGuide
Go back

How APIs Work: A Simple Guide for Beginners

By Pratik Bhuite | 12 min read

Hub: Web Fundamentals / Networking and Protocols

Series: Internet and Web Foundations Series

Last verified: Mar 11, 2026

Part 10 of 10 in the Internet and Web Foundations Series

Key Takeaways

On this page
Reading Comfort:

How APIs Work: A Simple Guide for Beginners

APIs are how apps talk to each other. Your frontend calls an API, the API validates the request, runs business logic, reads or writes data, and returns a structured response. Once you understand this lifecycle, backend behavior becomes much easier to design and debug.

Table of Contents

Open Table of Contents

Quick Definition

An API (Application Programming Interface) is a contract that defines how one software system requests data or actions from another system.

In web backends, API contracts usually define:

  1. Endpoint path (for example, /orders/123).
  2. Method (GET, POST, PUT, PATCH, DELETE).
  3. Input format (headers, query params, body schema).
  4. Output format (status code + JSON body).
  5. Error behavior (validation errors, auth errors, rate limits).

Where APIs Fit in Modern Systems

APIs sit between clients and backend services:

  1. Web/mobile clients call public APIs.
  2. Internal services call service-to-service APIs.
  3. Third-party systems call partner APIs (payments, messaging, maps).

Without APIs, each consumer would need direct database access or custom integration logic, which breaks security and maintainability.

How an API Request Flows End to End

flowchart TD
    A[Client App] --> B[DNS + TLS]
    B --> C[API Gateway or Load Balancer]
    C --> D{Auth Valid?}
    D -->|No| E[401 or 403]
    E --> A
    D -->|Yes| F[Application Service]
    F --> G{Input Valid?}
    G -->|No| H[400 Validation Error]
    H --> A
    G -->|Yes| I[(Cache)]
    I --> J{Cache Hit?}
    J -->|Yes| K[Return Response]
    J -->|No| L[(Database)]
    L --> M[Business Logic]
    M --> N[Write Audit/Event]
    N --> O[(Queue or Log)]
    M --> K
    K --> A
    A --> P{Retry Needed?}
    P -->|Yes| C
    P -->|No| Q[Done]

    classDef api fill:#e3f2fd,stroke:#1565c0,stroke-width:2px,color:#000000;
    class A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q api;

Typical timing buckets in observability:

  1. Network setup (DNS/TLS/connection).
  2. Gateway middleware (auth/rate limit/routing).
  3. Application logic execution.
  4. Data layer time (cache/DB/downstream calls).
  5. Serialization and response transfer.

Anatomy of an API Request and Response

Example request:

POST /api/v1/orders HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJ...
Content-Type: application/json
Idempotency-Key: 8d57c8f4-6ad0-4c74-8ae4-f51e58e93401

{
  "userId": "u_1024",
  "items": [
    { "sku": "book-001", "qty": 1 }
  ]
}

Example success response:

HTTP/1.1 201 Created
Content-Type: application/json

{
  "orderId": "ord_7782",
  "status": "confirmed"
}

Example validation error:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
  "error": "invalid_request",
  "message": "items must not be empty"
}

Common API Styles

REST (most common in web backends)

  • Resource-oriented (/users/123/orders).
  • Uses standard HTTP semantics and status codes.
  • Easy to cache and proxy.

RPC-style APIs

  • Action-oriented (/createOrder, /approveInvoice).
  • Can be simpler for command-heavy systems.
  • Needs stronger naming and consistency discipline.

GraphQL

  • Client asks exactly for needed fields.
  • Reduces over-fetching in complex UI use cases.
  • Adds schema, resolver, and performance complexity.

WebSocket APIs

  • Persistent connection for real-time updates.
  • Useful for chat, live dashboards, and collaborative editing.
  • Requires connection lifecycle and backpressure handling.

Status Codes and Error Handling

Good APIs return predictable status codes:

  1. 2xx: successful.
  2. 4xx: client input or auth issue.
  3. 5xx: server-side failure.

Recommended error principles:

  1. Keep error shape consistent (code, message, optional details).
  2. Separate user-safe messages from internal diagnostics.
  3. Include a request ID for tracing.
  4. Use retries only for retryable failures (timeouts, 429, transient 5xx).

Authentication and Authorization Basics

Common API auth patterns:

  1. Session cookies (browser-first apps).
  2. Bearer tokens (JWT or opaque access tokens).
  3. API keys (server-to-server/partner integrations).

Auth answers “Who are you?”
Authorization answers “What are you allowed to do?”

Even if frontend hides a button, authorization must still be enforced on the server for every protected endpoint.

Versioning and Backward Compatibility

Breaking clients in production is expensive. Versioning helps APIs evolve safely.

Common strategies:

  1. URI versioning (/api/v1/...).
  2. Header/media-type versioning.
  3. Consumer-driven compatibility testing.

Practical rule:

  • Additive changes (new optional fields) are usually safe.
  • Removing/renaming fields is breaking and needs version transition.

Reliability Patterns Used in Production

flowchart TD
    A[Client Request] --> B[Gateway Rate Limit]
    B --> C{Allowed?}
    C -->|No| D[429 Retry-After]
    D --> A
    C -->|Yes| E[Service Handler]
    E --> F{Timeout Reached?}
    F -->|Yes| G[Fail Fast + Fallback]
    G --> H[Standard Error]
    H --> A
    F -->|No| I[Downstream Call]
    I --> J{Transient Error?}
    J -->|Yes| K[Retry with Exponential Backoff + Jitter]
    K --> I
    J -->|No| L[Commit Result]
    L --> M[Emit Metrics and Trace]
    M --> N[Response]
    N --> A

    classDef rel fill:#e8f5e9,stroke:#1b5e20,stroke-width:2px,color:#000000;
    class A,B,C,D,E,F,G,H,I,J,K,L,M,N rel;

Core patterns to implement early:

  1. Timeouts for every downstream call.
  2. Rate limiting at edge.
  3. Idempotency keys for non-read operations.
  4. Retries with jitter, not tight loops.
  5. Observability: logs, metrics, traces, request IDs.

Real-World Example: E-commerce Checkout API

Checkout usually involves multiple APIs:

  1. Cart service validates items and prices.
  2. Inventory service reserves stock.
  3. Payment service authorizes transaction.
  4. Order service persists final order.
  5. Notification service sends confirmation.

Failure handling matters more than the happy path:

  1. Payment succeeds but order write fails -> use idempotency + recovery worker.
  2. Inventory reservation times out -> release or expire reservation.
  3. Duplicate client submit -> dedupe by idempotency key.

This is why API contracts must include retry semantics and explicit error models.

Interview Questions

1. What is the difference between an API endpoint and an API contract?

An endpoint is a network address plus method, such as POST /api/v1/orders. A contract is broader: it defines request schema, response schema, status behavior, auth rules, and error semantics.

In interviews, this distinction shows maturity: stable systems rely on contract design, not just endpoint creation.

2. Why should POST operations often use idempotency keys?

Clients retry on timeouts and network drops. Without idempotency, retries can create duplicate payments or duplicate orders.

An idempotency key lets server return the previous result for repeated equivalent requests, preventing duplicate side effects.

3. When would you choose GraphQL over REST?

GraphQL is strong when UI screens need many related entities with variable field selection, and frontend teams need high query flexibility.

REST remains simpler for many service APIs, especially where caching, clear resource boundaries, and operational simplicity are priorities.

4. What are common causes of high API latency even when CPU is low?

Low CPU does not mean low latency. Major contributors include slow queries, connection pool starvation, lock contention, cache misses, high network RTT, and slow downstream dependencies.

A strong answer explains latency as end-to-end path time, not just compute time.

5. How do authentication and authorization differ in API design?

Authentication verifies caller identity (token/session/API key validity). Authorization verifies access rights for a resource or action.

You can have successful authentication with failed authorization, such as a valid user token trying to access another tenant’s data.

6. How do you evolve an API without breaking existing clients?

Use contract-first governance, additive changes by default, explicit deprecation windows, and versioning for breaking changes.

Also publish changelogs and test compatibility with representative client versions before rollout.

Conclusion

APIs are not just HTTP endpoints. They are durable contracts that define communication between systems. If the contract is clear and reliability patterns are in place, teams can scale faster with fewer production incidents.

When learning backend engineering, understanding how APIs work is one of the highest-leverage skills you can build.

References

  1. MDN: HTTP Overview
    https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview
  2. MDN: Fetch API
    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
  3. RFC 9110 - HTTP Semantics
    https://www.rfc-editor.org/rfc/rfc9110
  4. RFC 9112 - HTTP/1.1
    https://www.rfc-editor.org/rfc/rfc9112
  5. RFC 9457 - Problem Details for HTTP APIs
    https://www.rfc-editor.org/rfc/rfc9457
  6. Roy Fielding Dissertation (REST)
    https://ics.uci.edu/~fielding/pubs/dissertation/top.htm
  7. Stripe Docs: Idempotent Requests
    https://docs.stripe.com/api/idempotent_requests

YouTube Videos

  1. “REST API concepts and examples” - Web Dev Simplified
    https://www.youtube.com/watch?v=-MTSQjw5DrM
  2. “HTTP Crash Course & Exploration” - Hussein Nasser
    https://www.youtube.com/watch?v=iYM2zFP3Zn0

Share this post on:

Next in Series

Continue through the Internet and Web Foundations Series with the next recommended article.

Related Posts

Keep Learning with New Posts

Subscribe through RSS and follow the project to get new series updates.

Was this guide helpful?

Share detailed feedback

Previous Post
What Is REST API? Beginner's Guide with Examples
Next Post
What is MCP (Model Context Protocol)? Understanding the Differences