SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • What is an API?
  • API Styles
  • Idempotency
  • Data Formats
  • REST, GraphQL, gRPC
  • Pagination, Filtering and Sorting
  • API Versioning
  • Error Handling and Status Codes
  • OpenAPI / Swagger
  • Bulk APIs and File Upload
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/API Design

What is an API?

A menu and a waiter: a clear way for one program to ask another for something.

⏱ 11 min readBeginnerMust KnowHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

An API (Application Programming Interface) is a clear way for one program to ask another program for something, and get an answer.

  • It is like a menu and a waiter. You order from the menu. You never go into the kitchen.
  • The API lists what you can ask for, how to ask, and what you will get back.
  • The other side can change how it works inside. If the API stays the same, nothing breaks for you.

02Concept: What is it?

An API is a contract between two pieces of software. It says: “If you send me a request like this, I will send you a reply like that.”

📨Request
What you ask for. For example: weather for Pune.
📬Response
What you get back. For example: 29°C, Sunny.
📜Contract
The rules both sides agree on: names, formats, errors.
🧠Hiding is the point
An API shows what you can do, and hides how it is done. This is why teams can work on their own parts without breaking each other.

The words “client” and “server”

  • Client: the one who asks (a mobile app, a browser, another service).
  • Server: the one who answers (it owns the data or the logic).
  • One program can be both. A shop server is a client of the payment server.

Not only web APIs

You use APIs inside one program too (a function you call in a library). In system design we mostly mean network APIs: one program calls another over the internet or inside a data centre, usually with HTTP.

03Real-Life Example

🍵The restaurant
You go to a restaurant. You read the menu. You tell the waiter what you want. The waiter goes to the kitchen. The food comes back to you. You never see the kitchen. You also cannot order something that is not on the menu.
Restaurant = API
🧑Customerclient
↔order / food
🧑‍🍳WaiterAPI
↔ticket / dish
🍳Kitchenserver
The waiter is the API. The menu is the documentation. The kitchen is the server.
Restaurant
API
Menu
API documentation (what you can ask)
Waiter
The API itself (takes requests, brings answers)
Order: “one masala dosa”
Request: GET /weather?city=Pune
The dish
Response (usually JSON)
“Sorry, sold out”
Error response (404, 500...)
Kitchen can change its recipe
Server can change its code; the API stays the same
Ordering something not on the menu
Bad request (400) or not found (404)

04Why Do We Need It?

Modern software is made of many parts. They all need a clean way to talk.

🧩Reuse
Build “send an SMS” once. Many apps use it through its API.
🔒Safety
Outsiders reach your data only through the doors you opened.
👥Teams work apart
Front-end and back-end teams agree on the API, then work in parallel.
🔁Change inside
You can rewrite the server. If the API is the same, users do not notice.
🤝Partners
Other companies can build on top of your service.
📱Many clients
One API serves the web app, Android, iOS and other servers.
An API turns a big messy system into a small set of simple, safe actions.

05Where Do We Use It?

🌦️Weather apps
Ask a weather service for today’s forecast.
💳Payments
A shop calls a payment API to charge a card or UPI.
🗺️Maps
Ride apps ask a map API for routes and time.
🔑“Login with Google”
An app asks Google’s API who you are.
💬Chat bots
A bot calls the messaging API to send replies.
🏗️Inside a company
Order service calls inventory service and payment service.

Three kinds by who can use them

KindWho uses itExample
Public (open) APIAny developer, often with a keyA weather or maps API
Partner APIChosen business partnersA bank API for approved apps
Private (internal) APIOnly your own teams and servicesOrder service calling stock service

06Types / Parts / How It Works

Every network API call has the same few parts. Learn these once and you can read any API.

One API call, drawn
📱Client
→↓request
🔌API
→↓uses
🗄️Server + data
Request
MethodGET, POST, PUT, DELETE
URL/weather?city=Pune
Headersauth key, format
Bodydata to send (for POST)
Response
Status code200, 404, 500
Headerscontent type, cache
Bodythe data, often JSON
The client sends a request. The server sends back a response with a status code.

Status codes in short

RangeMeaningExamples
2xxSuccess200 OK, 201 Created, 204 No Content
3xxGo somewhere else301 Moved, 304 Not Modified
4xxYour mistake (the client)400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests
5xxOur mistake (the server)500 Internal Error, 503 Service Unavailable

Where an API can live

Web (network) API
  • Called over HTTP or another protocol
  • Server and client can be on different machines
  • REST, GraphQL, gRPC, WebSockets...
Library API
  • A function you call inside your own program
  • Same machine, no network
  • Example: Math.max(3, 9)
VisualizerFollow one API callStep through the restaurant story, then switch to a real weather request.
Pick a story
🧑Customerreads the menu
↔
🧑‍🍳Waiterthe API
↔
🍳Kitchenthe server
Step 1 of 4
The customer is hungry
You sit at a table and read the menu. The menu lists what you can order. You do not walk into the kitchen.

07How to Use It / Steps / Implementation

Calling an API (as a client)

  1. 1
    Read the documentation
    Find the base URL, the endpoints, and how to log in.
  2. 2
    Get a key or token
    Most APIs need to know who you are.
  3. 3
    Send a request
    Pick the method, the URL, headers and a body if needed.
  4. 4
    Check the status code
    2xx means success. 4xx means fix your request. 5xx means try later.
  5. 5
    Read the body
    Parse the JSON and use it in your app.
  6. 6
    Handle failure
    Set a timeout. Retry carefully. Show a friendly message.
Example: ask for the weather
GET /weather?city=Pune HTTP/1.1
Host: api.example.com
Authorization: Bearer <your-token>
Accept: application/json

--- response ---
HTTP/1.1 200 OK
Content-Type: application/json

{ "city": "Pune", "tempC": 29, "sky": "Sunny" }

Designing an API (as a server)

  1. List the things (resources) your users care about: users, orders, products.
  2. Choose clear names. Use nouns in URLs: /orders/42, not /getOrder?id=42.
  3. Use the right method for the action and the right status code for the result.
  4. Write the contract first (for example with OpenAPI), then build it.
  5. Add safety: authentication, input checks and rate limits.
  6. Plan for change: add a version (/v1/) before you need it.

08Key Terms to Know

TermMeaning in easy words
EndpointOne URL plus a method that does one job, like GET /users/7
Request / ResponseThe message the client sends / the message the server sends back
HTTP methodThe action: GET (read), POST (create), PUT (replace), PATCH (change a part), DELETE (remove)
Status codeA number that says how it went (200 OK, 404 Not Found, 500 Server Error)
HeaderExtra information about the message, like the format or a login token
Payload / BodyThe actual data sent in a request or response
API keyA secret string that tells the server which app is calling
Rate limitA cap on how many calls you can make in a period of time
VersioningKeeping old and new forms of an API side by side (/v1, /v2) so old clients keep working
SDKA ready-made code library that wraps an API so you do not write raw requests
OpenAPIA standard file format to describe a REST API, so tools can make docs and code from it
ContractThe agreed rules of the API. Breaking it breaks the clients

09Pros, Cons and Trade-offs

✅ Pros
  • Clear and safe way to share data and features
  • Teams and companies can build on each other
  • Server can change inside without breaking clients
  • One API can serve web, mobile and partners
⚠️ Cons
  • Every API is a promise you must keep (hard to change later)
  • Network calls are slower and can fail
  • Needs security, limits and monitoring
  • Bad design makes every client’s life hard

Trade-offs to remember

ChoiceWe gainWe lose
Small, simple APIEasy to learn and useClients may need many calls
Big, flexible APIFewer calls, more powerHarder to learn, secure and keep stable
Public APIGrowth, partners, ecosystemSupport work, abuse, and you cannot easily break it
Strict contractSafe for clientsSlower to change

10Common Problems and Mistakes

Common mistakes

  1. Changing the API without a version. Old apps stop working.
  2. Vague errors. “Something went wrong” helps nobody. Return a clear status code and message.
  3. Wrong status codes. Sending 200 with an error inside confuses clients and tools.
  4. No limits on a public API. One user can overload the system.
  5. Leaking inner details. Do not show database field names or stack traces.
  6. No timeout on calls. A slow server then freezes your app.
  7. Returning too much data. Secrets, huge lists, fields nobody asked for.

Problems you will meet

🐢Slow responses
One slow API makes your whole page slow.
💥API goes down
Your app must cope when a partner API is not available.
🔀Breaking changes
A removed field breaks apps you never met.
🔁Duplicate calls
Retries can run the same action twice. See Idempotency.

11Real-World Examples

💳Payment gateways
Shops call a payment API to start a payment and check its status.
🗺️Map and ride apps
Ride apps call map services for routes and distance (general idea).
🔑Login with Google / GitHub
Apps ask the provider’s API who the user is, using OAuth.
📧Email and SMS services
Your server calls one API call to send a message.
☁️Cloud services
Every cloud feature (storage, compute) is controlled through APIs.
🛒Marketplaces
Sellers update products and orders through the marketplace API.
Mini case: an online shop
📱Mobile app
→↓Shop API
🛒Shop server
→↓calls
💳Payment API
📦Shipping API
📧Email API
Client Your server Other APIs you use
The shop’s own API is used by its apps. The shop also calls other APIs.

12Related Topics to Read Next

API Styles→

The main ways an API can talk: request-response, streaming, events.

REST, GraphQL, gRPC→

Three popular API designs and how to choose.

Idempotency→

What happens when the same request is sent twice.

Data Formats→

JSON, XML, Protobuf: how the data is written.

HTTP / HTTPS→

The protocol most web APIs ride on.

Rate Limiting→

How to stop one caller from overloading your API.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔API: a contract for how one program asks another for something.
  • ✔Think: menu + waiter + kitchen. You see the menu, not the kitchen.
  • ✔Call parts: method, URL, headers, body, then status code and response body.
  • ✔Status codes: 2xx ok, 4xx client error, 5xx server error.
  • ✔Good API: clear nouns, right methods, clear errors, versioned, secured, rate limited.
  • ✔Never: break old clients without a new version.
  • ✔One line: “An API hides how things work and shows only what you can ask for.”
← Previous
Nginx and HAProxy
Next →
API Styles