Computing Foundations › APIs and the Web › Day 22
Day 22: What an API Is and Why Everything Has One
After this lesson you will be able to explain what an API is as a contract between programs, name the parts of a request and response, and call several free public web APIs with curl — the exact skill that lets you reach a hosted model over HTTP.
Hands-on lab for this lesson
Lab files on GitHub: https://github.com/ai-roadmap-365/ai-roadmap-365.github.io/tree/main/labs/sections/computing-foundations/day-022-what-an-api-is-and-why
- Get the hands-on files. Clone the labs repository once (you can reuse this clone for every lesson). This works on macOS, Linux, and Windows (PowerShell or WSL):
git clone https://github.com/ai-roadmap-365/ai-roadmap-365.github.io.git cd ai-roadmap-365.github.io - Open this lesson's lab. Move into the directory for this specific day. Every lab lives at the same predictable path — section / subsection / week / day:
cd labs/sections/computing-foundations/day-022-what-an-api-is-and-why - Read the lab guide. Open `README.md` in that directory. It lists the exact commands, what each does, the expected output, and how to check your work — read it before running anything.
- Run it and check your work. Follow the README's "How to run" section: run the example first to see the finished result, then complete the numbered exercises in `starter/`, then run the tests. The tests pass (exit 0) only when your work is correct.
bash tests/run_tests.sh # or the test command named in the lab README
You can also open the lab as a local page (works offline, shows the file tree and expected output).
Learning objectives
By the end of this lesson you will be able to:
- Define an API as a contract and interface between two programs, and state what it hides (the implementation) versus what it exposes (the requests it accepts and responses it returns)
- Distinguish the kinds of APIs — library, operating-system, and web — and explain why web APIs over HTTP are the kind that connect programs across the network
- Name the five parts of an HTTP API request (method, path/endpoint, parameters, headers, body) and the parts of a response (status code, headers, body), and say what each contributes
- Call the free public JSONPlaceholder, httpbin, and Open Notify ISS APIs with curl and read the JSON responses
- Read API documentation well enough to find an endpoint, its parameters, and an example request/response
- Explain the public/partner/internal framing of an API as a product, and reason about the security, privacy, performance, scalability, and cost implications of calling a remote API
- Connect APIs to AI practice: explain why every hosted model is reached through a web API and why request-shaping, rate limits, and per-call cost matter
Prerequisites
- Days 15-21 (the networking category): URLs, DNS, TCP/ports, and especially HTTP requests, responses, methods, and status codes
- Day 21 comfort with curl (running a request and reading the output)
- A computer running macOS or Linux with curl and python3 (both preinstalled) and internet access
Why this matters
-
Every model you will use is behind an API. GPT, Claude, Gemini, the open ones you host yourself — all of them, the same shape.
-
An API is what lets you use a model you could never train, on hardware you do not own, for the price of a request.
-
Everything you build will expose one too, so that something else can call it.
-
This is Week 4, and it turns you from someone who reads about services into someone who composes them.
-
Reading documentation quickly is half the skill. The other half you already have: HTTP.
The idea in plain language
-
An API is a contract between two programs: send this shape, get that shape back.
-
The client asks; the server answers. One request, one response.
-
The contract is all either side needs. How the server does its work stays private behind the line.
-
A web API is HTTP with structure. Same methods, same status codes, but the body is data rather than a page.
-
JSON is the near-universal language of that body, which is why tomorrow’s lessons dwell on it.
Historical background
-
“API” originally meant a library’s function signatures — the interface one piece of code offered another, inside one program.
-
Networked APIs came next, with heavyweight protocols like CORBA and SOAP that required generated code and matching toolchains on both ends.
-
REST was described in 2000 by Roy Fielding, in a dissertation, as an architectural style rather than a standard — use HTTP as it was designed.
-
The public API era began around 2005. Amazon, Flickr, Twitter and Google opened interfaces, and companies discovered their service could be a platform.
-
JSON displaced XML over the following decade, largely because it was smaller and needed no library to read.
-
The pattern is now universal. Every service ships an API, because a service nothing can call is a service nothing will build on.
What it is — and what it is not
It is:
- A published agreement about requests and responses.
- A boundary that hides implementation deliberately.
- A product in its own right, versioned and supported like one.
It is not:
-
Not a database. You get what the interface offers, in the shape it offers it.
-
Not a website. It returns data for programs, not pages for people.
-
Not stable by nature. It is stable because someone chose to keep it so, and publishing a version number is that promise made explicit.
-
Not free of the network. Everything from Week 3 still applies: latency, TLS, status codes, retries.
Why it was created and what problems it solves
-
Reuse without copying. You call a service rather than rebuilding it.
-
Separation of concerns. The provider can rewrite everything behind the contract and you never notice.
-
Composition. Small services combine into something none of them could do alone.
-
Access to what you cannot own. A model that cost millions to train answers your request for a fraction of a cent.
-
A machine-readable interface. Anything a person can do through a screen, a program can do through an API — which is what makes automation possible at all.
How it works
The endpoint: an address for an operation
-
An endpoint is a URL the API answers at, usually standing for one resource or operation.
-
/todos/1returns to-do item one;/users/1returns user one. The path names what you are asking about, often with an identifier. -
An API is largely a well-organised set of endpoints.
-
Read the diagram as a boundary. Your program is the client; the service is the server; the API is the single defined line between them.
-
The client depends only on that line. The database, the language and the machinery stay private behind it.
The request
| Part | What it carries | Example |
|---|---|---|
| Method | The verb — what kind of operation | GET, POST |
| Path | Which resource | /users/1 |
| Query parameters | Options that refine it | ?_limit=5 |
| Headers | Metadata | Accept: application/json |
| Body | Data sent with the request | {"title":"Learn APIs"} |
-
The method says what you want done, exactly as on Day 18.
-
Parameters refine, the way options on an order narrow it down.
-
Headers carry metadata, including the
Authorizationheader that will prove who you are from Day 25. -
The body describes the thing to create, for a
POST, almost always as JSON.
The response
-
A status code tells your program at a glance whether it worked — Day 18’s
200,404,401,429,500. -
Headers describe the answer,
Content-Type: application/jsonabove all. -
The body is the data, again almost always JSON.
-
JSON is nested keys and values, readable by both humans and programs, and the near-universal language of web APIs.
-
One request, one response. The same conversation your browser has with every page — now made by your program, for structured data rather than a page to display.
Reading the documentation
-
You cannot guess your way through an API. Every one defines its own endpoints, parameters and formats.
-
The documentation lists each endpoint, the parameters it accepts, an example request and an example response.
-
The method that works: find the endpoint that returns what you want, note its method and required parameters, copy the example, run it, and compare your response against the documented one.
-
Good documentation includes a runnable example for exactly this reason.
-
Half of using a new API is reading its documentation quickly, and that is a skill that transfers to every API you will ever meet.
An everyday analogy
Ordering at a restaurant.
| The restaurant | The API |
|---|---|
| The menu | The documentation |
| A dish name | An endpoint |
| ”No onions, extra rice” | Query parameters |
| Your table number | Your credentials |
| The order slip | The request |
| The plate arriving | The response |
| The kitchen | The implementation, hidden |
-
You order from the menu, not by describing a recipe. The menu is the contract.
-
You never enter the kitchen. How the dish is made is deliberately none of your business, and that is what lets them change it.
-
“We are out of that” is a
4xx. “The oven caught fire” is a5xx.
Examples in practice
-
GET /users/1returns one user as JSON — the simplest complete example there is. -
POST /v1/messageswith a JSON body is every hosted model call you will ever make. -
A weather API taking
?lat=&lon=and returning a forecast object. -
A payment API where
POSTtwice creates two charges, which is Day 18’s idempotency problem with money attached. -
A documented endpoint that returns a different shape than documented, which is why you compare against the example rather than trusting the prose.
Implications: security, privacy, performance, scalability, and cost
-
Security: an API is your service’s attack surface, published deliberately. Everything exposed is exposed to everyone who finds it.
-
Never trust input from a client. Validate on the server, always, because the client may not be the one you wrote.
-
Privacy: an API returns exactly what it returns. An endpoint that includes email addresses in a response has published them, whether the interface displays them or not.
-
Performance: every call is a network round trip. A loop making a thousand calls is a thousand round trips, and Day 15’s arithmetic applies.
-
Batch endpoints exist for this reason, and using one is usually a larger win than any code optimisation.
-
Cost: APIs are metered. A retry loop with a bug is a bill, and a runaway loop against a model API is an expensive bug indeed.
Alternatives: free, open source, and commercial
| Approach | Type | Where it fits |
|---|---|---|
| REST over HTTP | The default | Almost everything; Day 23 covers it properly |
| GraphQL | Free, open source | Clients that need to choose their own response shape |
| gRPC | Free, open source | Service-to-service calls where speed matters more than readability |
| WebSockets | Built in | Persistent two-way channels, not request-response |
| Webhooks | The inverse | The server calls you — Day 26 |
| SDK / client library | Usually free | The same API, wrapped, with retries and types included |
-
Use the official client library where one exists. It handles retries, pagination and errors you would otherwise get wrong.
-
Understand the underlying HTTP anyway. When the library misbehaves, you debug it with
curl.
Comparison with related concepts
| Term | What it actually is |
|---|---|
| API | The published contract between two programs |
| Endpoint | One URL the API answers at |
| Client | The program making the request |
| Server | The program answering it |
| Payload | The body of a request or response |
| SDK | A library wrapping an API in your language |
| Contract | What both sides agreed, and what versioning protects |
When to use it — and when not to
-
Use an API when someone else has solved the problem better than you will this week — payments, maps, speech, translation, inference.
-
Use one when the data lives elsewhere and you need it current.
-
Expose one when something else will need to call your work, including your own future project.
-
Do not call an API in a loop when a batch endpoint exists. Read the documentation for one before writing the loop.
-
Do not scrape when an API exists. It is slower, more fragile, and usually against the terms you agreed to.
-
Do not build an API for one caller you control. A function call is cheaper than a network hop, and you can always promote it later.
The AI connection
-
Every hosted model is an API, and the request is a
POSTwith a JSON body — the exact shape in this lesson. -
The contract is what lets you switch providers. Similar shapes mean a change of endpoint and key rather than a rewrite.
-
Your own model becomes useful when it has an API. A notebook helps you; an endpoint helps everyone else.
-
Rate limits and token costs are contract terms, as real as the request format, and Day 27 deals with them properly.
-
Agents and tool use are APIs all the way down. A model calling a tool is a program calling an API, with the model choosing the arguments.
Knowledge check
quiz:
question: "A service rewrites its entire backend — new language, new database, new servers — and existing client programs keep working with no changes. What made that possible?"
options:
- "The API contract stayed the same, and clients depend only on the contract"
- "The clients were using an SDK that absorbed the changes"
- "HTTP is stateless, so clients never noticed the servers changed"
- "The new backend returned the same status codes as the old one"
answer_index: 0
explanation: "The contract is the whole point of the boundary: clients depend on the shape of requests and responses, never on what produces them. That is what lets everything behind the line be replaced without coordination."
Hands-on exercise
Call a real API, read its documentation, and compare what you got against what was promised. Worked through fully in the Day 22 lab directory.
| What you are doing | Command |
|---|---|
| Fetch one resource | curl https://jsonplaceholder.typicode.com/todos/1 |
| See the content type | curl -I https://jsonplaceholder.typicode.com/todos/1 |
| Refine with a parameter | curl 'https://jsonplaceholder.typicode.com/todos?_limit=3' |
| Filter by field | curl 'https://jsonplaceholder.typicode.com/todos?userId=1' |
| Create something | curl -X POST -H 'Content-Type: application/json' -d '{"title":"Learn APIs"}' https://jsonplaceholder.typicode.com/todos |
| Ask for a missing resource | curl -i https://jsonplaceholder.typicode.com/todos/99999 |
Expected output
{"userId":1,"id":1,"title":"delectus aut autem","completed":false}
Content-Type: application/json; charset=utf-8
HTTP/1.1 404 Not Found
{}
-
The body is JSON, and
Content-Typesays so — which is how your program knows to parse it. -
404with an empty object is the API saying “no such resource” in its own vocabulary.
Validate your work
-
You fetched a single resource and a filtered collection
-
You created something with a
POSTand read the status code it returned -
You provoked a
404and can explain why it is a4xxrather than a5xx -
You found the endpoint you used in the API’s documentation and compared the documented response with yours
-
You can name the five parts of a request without looking
-
bash tests/run_tests.shreports 0 failures
Troubleshooting
-
The URL with
?does nothing. The shell interprets?and&. Quote the whole URL. -
Your
POSTbody is ignored. MissingContent-Type: application/json. -
The JSON is one unreadable line. Pipe it through
jq, orpython3 -m json.tool. -
You get HTML back instead of JSON. You probably hit an error page. Check the status with
-i.
Common mistakes
-
Guessing endpoints instead of reading the documentation.
-
Assuming a
200means the body is what you wanted. It means the request was handled. -
Calling in a loop where a parameter would have returned everything at once.
-
Hard-coding the base URL in fifty places instead of one.
Practice assignment
-
Pick three public APIs you have never used and, from their documentation alone, make one successful request to each. Time how long each took to figure out.
-
Write down each one’s contract in your own words: base URL, one endpoint, its parameters, its response shape.
-
Find one API whose documentation is wrong about something, and note how you discovered it.
-
Sketch the API you would expose for something you have already built, listing three endpoints and their shapes.
Extension challenge
-
Read an OpenAPI specification for a real service and find the endpoint you used. A machine-readable contract is what generates SDKs and documentation alike.
-
Call the same API from
curland from Python and confirm you get identical responses. Any difference is your client adding something. -
Build the smallest possible API — one endpoint, returning JSON — and call it from another program. Being on both sides of the line once teaches more than reading about it.
-
Compare a REST endpoint with a GraphQL one for the same data, and count the round trips each needs to answer the same question.
Quiz
Q1. What is the best short description of an API?
- A program you download and install to speed up your computer
- The physical server that stores a website's data
- A contract for how one program asks another to do something
- A visual dashboard that humans click to use a service
Show answer
Answer: C. A contract for how one program asks another to do something
An API is an Application Programming Interface: an agreed contract describing the requests one program accepts and the responses it returns, while hiding how it is implemented. The server, the data, and a human dashboard are all different things.
Q2. Which kind of API is reached over HTTP across the network and is the focus of this week?
- A library API
- An operating-system (system-call) API
- A hardware API
- A web API
Show answer
Answer: D. A web API
A web API is a service on another computer that you call over HTTP, using the same request/response conversation your browser uses. Library and operating-system APIs are local — called within one machine — rather than across the network.
Q3. In a web API request, what is the endpoint?
- The specific URL the API answers at, one per resource
- The status code the server sends back
- The secret key that proves who is calling
- The JSON data returned in the response body
Show answer
Answer: A. The specific URL the API answers at, one per resource
An endpoint is a specific URL a web API answers at, such as /todos/1 or /users/1. The path names what you are asking about; the status code and body are parts of the response, not the endpoint.
Q4. Which list correctly names parts of an HTTP API request?
- Status code, headers, and body
- Method, path, parameters, headers, and body
- Latitude, longitude, and timestamp
- Client, server, and network
Show answer
Answer: B. Method, path, parameters, headers, and body
A request carries a method (the verb), a path/endpoint, query parameters that refine it, headers of metadata, and an optional body (payload). Status code, headers, and body describe the response, not the request.
Q5. You run `curl https://jsonplaceholder.typicode.com/todos/1` and get back `{"userId":1,"id":1,"title":"delectus aut autem","completed":false}`. What did you just do?
- Installed the JSONPlaceholder service on your computer
- Sent a secret API key to authenticate yourself
- Made a GET request to an endpoint and received a JSON response body
- Changed the data stored on the server
Show answer
Answer: C. Made a GET request to an endpoint and received a JSON response body
This is a complete API exchange: a GET request to the /todos/1 endpoint returns a 200 response whose JSON body has named fields. Nothing was installed, no key was sent, and GET only reads — it does not change server data.
Q6. Why does API documentation exist and need to be read for each new API?
- Because all APIs are identical, so one manual covers them all
- Because APIs are illegal to use without reading a legal notice first
- Because documentation is the program that runs the API
- Because every API defines its own endpoints and formats
Show answer
Answer: D. Because every API defines its own endpoints and formats
Each API defines its own set of endpoints, the parameters they accept, and the shape of their responses, so you read the docs to find the right endpoint and copy a working example. Documentation is a guide, not the running service, and APIs are not interchangeable.
Q7. A paid API returns HTTP 429 when your program calls it rapidly in a loop. What does that mean and why did it happen?
- You are rate-limited for calling too fast; slow down
- The server crashed; there is nothing you can do
- Your request body was malformed; fix the JSON
- The endpoint URL was misspelled; correct the path
Show answer
Answer: A. You are rate-limited for calling too fast; slow down
429 Too Many Requests signals a rate limit — a cap on requests per period that shared services enforce so no caller overwhelms them. A tight loop trips it; the fixes are to slow down, batch, or fetch fewer times. A malformed body is 400 and a bad path is usually 404.
Q8. What does it mean to describe an API "as a product" with public, partner, and internal audiences?
- The API is sold in physical stores
- The same interface can be public, partner, or internal
- Only public APIs are real APIs; partner and internal ones are fakes
- A product API cannot be reached over HTTP
Show answer
Answer: B. The same interface can be public, partner, or internal
Organizations treat APIs as products with different audiences: public APIs are open to any developer, partner APIs are shared with specific companies under agreement, and internal APIs connect a company's own systems. All are the same technical idea aimed at different callers.
Glossary
- API
- An Application Programming Interface: a defined contract by which one program asks another to do something, exposing the requests it accepts and responses it returns while hiding how it works inside.
- web API
- An API reached over HTTP across the network — a service on another computer your program calls with requests and reads responses from, instead of a local function.
- endpoint
- A specific URL that a web API answers at, usually standing for one resource or operation, such as /todos/1 or /users/1.
- request
- What a client sends to an API: a method (verb), a path/endpoint, optional query parameters, headers, and an optional body.
- response
- What the server sends back: a status code indicating the outcome, headers describing the answer, and a body carrying the data (usually JSON).
- payload
- The data carried in the body of a request or response — for example the JSON describing a thing to create in a POST, or the data returned in a response.
- parameter
- A value that refines a request, most often a query parameter appended after the path (such as ?userId=1) to filter or configure what the API returns.
- client
- The program that initiates an API call — it builds and sends the request and reads the response. Your curl command or your program is the client.
- server
- The machine and code that receives requests and fulfills them, implementing the API behind the contract while keeping its database and internals private.
- REST
- A widely used architectural style for web APIs, described by Roy Fielding in 2000, that maps operations onto HTTP methods and resource URLs (covered in depth on Day 23).
- documentation
- The human-written guide to an API that lists each endpoint, the parameters it accepts, and example requests and responses — what you read to learn how to call a new API.
- JSON
- JavaScript Object Notation, a simple text format of nested keys and values that is the near-universal way web APIs format their request and response bodies.
- rate limit
- A cap a service places on how many requests a caller may make per period; exceeding it returns HTTP 429 so that no single caller can overwhelm the shared service.
- API key
- A secret token a caller sends (usually in an Authorization header) to prove who they are; like a password, it must never be shared publicly or sent to an echo service.
Sources and further reading
- Introduction to web APIs — MDN Web Docs (accessed 2026-07-12)
- API — Wikipedia (accessed 2026-07-12)
- Web API — Wikipedia (accessed 2026-07-12)
- HTTP overview — MDN Web Docs (accessed 2026-07-12)
- JSONPlaceholder — Free fake REST API — JSONPlaceholder (accessed 2026-07-12)
Kept in this browser, no account needed. Your progress page turns the whole record into one link you can bookmark or open on another device.