What a Web API Is
A web API is a server that answers requests sent to its addresses, and every request and answer has the same parts: a URL with a path and query string, a method, a status code and, usually, JSON.
Apprentice · JavaScript · REST API · Web Development · Updated
After this lesson you can
- Name the parts of a web API address, the domain, the path and the query string, and say what each one does
- Explain what an HTTP method and a status code tell you, for GET, POST, 200, 404 and 500
- Find the value you need in an API's JSON response
Key takeaways
- A web API is a program on a server that answers requests sent to its web addresses, like an order window with a fixed menu.
- A URL names the server (the domain), what you want (the path) and any options (the query string, after the ?).
- The method says what you want done (GET reads, POST sends something new), and the status code says how it went (200 worked, 404 not found, 500 the server broke).
- Most web APIs answer in JSON, text shaped like a JavaScript object, and you can open an API's address in a browser to see it.
The weather on your phone's lock screen, the map on a pizza place's site, live game scores, the "Pay with card" button on a checkout page: none of that data lives in the page you're looking at. The page asks another computer for it, over the internet, while you watch. That other computer is a web API, and asking one for data is part of almost every app you'll build, from a class project that "must use a public API" to a job where the page talks to your own company's server.
This chapter builds a dog breed explorer for Riverbend Animal Shelter. Visitors who are thinking about adopting want to see what a breed looks like, and the shelter can't photograph 100 breeds. A free API can: the Dog CEO API has thousands of dog photos, sorted by breed. This lesson is about how an API works before you write any code for it.
An order window for data
Picture a takeout window at a busy restaurant. There's a menu on the wall, so you know what you can ask for. You ask in a set way ("number 4, large, no onions"), and you get a set answer: a bag with your food, or "sorry, we're out of that."
A web API is an order window for data:
- The menu is the API's documentation: the list of things you can ask for.
- Asking is a request: your program sends a message to an address on the internet.
- The bag is the response: the API's answer.
API stands for application programming interface: the set of rules one program uses to ask another program for something. A web API is one you call over the internet. The program that asks (your page) is the client, and the computer that answers is the server. In your textbook, this whole back-and-forth may be called the client-server model.
The address: a URL
Every request goes to an address, a URL (read "U-R-L", for uniform resource locator). It's the same kind of address you type into a browser. Here's the one that lists every breed the Dog CEO API knows:
https://dog.ceo/api/breeds/list/all
└─────┘└──────┘└──────────────────┘
scheme domain path
https://is the scheme: how to talk to the server. Thesmeans the conversation is encrypted.dog.ceois the domain: which server to ask, like the restaurant's street address./api/breeds/list/allis the path: what you're asking for, like the item on the menu.
Each address an API offers is called an endpoint. The Dog CEO API has an endpoint for each breed's photos, and part of its path changes with the breed:
https://dog.ceo/api/breed/beagle/images/random
https://dog.ceo/api/breed/husky/images/random
The part that changes, beagle or husky, is a path parameter: a value you put into the path yourself.
Options on the order: the query string
"Large, no onions" isn't a different menu item; it's an option on one. A URL carries options in its query string: everything after a ? (read "question mark"). Each option is a key=value pair, and an & (read "and") joins two options.
The Open Trivia Database, a free trivia API, takes its options this way:
https://opentdb.com/api.php?amount=10&category=27&difficulty=easy
| Key | Value | What it asks for |
|---|---|---|
amount |
10 |
ten questions |
category |
27 |
animal questions (27 is the API's number for that category) |
difficulty |
easy |
easy ones |
The path, /api.php, stays the same. The query string changes what comes back. Search pages, filters and "page 2 of 10" links on sites you use every day work this way.
The answer: JSON, in your browser
You can call an API without writing a line of code. Try it. Paste this into your browser's address bar and press Enter:
https://dog.ceo/api/breed/beagle/images/random
Instead of a web page, you get text that looks like this:
{
"message": "https://images.dog.ceo/breeds/beagle/n02088364_852.jpg",
"status": "success"
}
That text is JSON (read "jay-son"), short for JavaScript Object Notation: data written the way you write a JavaScript object, with every key in double quotes. You met it in JSON: Data You Can Save and Send. Here, message holds the address of a beagle photo, and status says the request worked. Reload the page and you get a different beagle: the endpoint picks a random photo each time.
Now open the breed list, https://dog.ceo/api/breeds/list/all. Its message is an object with one key per breed, and each breed's value is an array of its sub-breeds. Firefox shows JSON as a tidy tree, and Chrome and Edge have a Pretty-print box. Shortened, it starts like this:
{
"message": {
"affenpinscher": [],
"african": ["wild"],
"airedale": [],
"bulldog": ["boston", "english", "french"],
"hound": ["afghan", "basset", "blood", "english", "ibizan", "plott", "walker"]
},
"status": "success"
}
To find a value, follow the keys from the outside in: the sub-breeds of a bulldog are at message, then bulldog. In JavaScript, once the text is turned into an object, that's data.message.bulldog:
const text = '{ "message": { "beagle": [], "bulldog": ["boston", "english", "french"] }, "status": "success" }';
const data = JSON.parse(text);
console.log(data.status);
console.log(data.message.bulldog);
console.log(data.message.bulldog[2]);
success
[ 'boston', 'english', 'french' ]
french
The method: what you want done
The order window needs to know whether you're ordering food or returning a wrong order. Every request carries a method, a verb that says what the client wants. The language browsers and servers use for requests and responses is HTTP (hypertext transfer protocol), so these are HTTP methods:
| Method | Read it as | It asks the server to | At the shelter |
|---|---|---|---|
GET |
"get" | send data back, changing nothing | show a photo of a beagle |
POST |
"post" | take some new data and save it | save a visitor's request to meet a dog |
PUT or PATCH |
"put", "patch" | change data that's already saved | change the visit to Sunday |
DELETE |
"delete" | remove data | cancel the visit |
Typing an address into a browser always sends a GET. Most of this chapter uses GET; Sending Data with fetch sends a POST.
The status code: how it went
Every response starts with a status code: a three-digit number that says how the request went, before you read anything else. The first digit tells you the kind of answer:
| Code | Name | What it means |
|---|---|---|
200 |
OK | It worked, and the answer is in the response. |
201 |
Created | It worked, and something new was saved (an answer to a POST). |
404 |
Not Found | There's nothing at that address. Codes from 400 to 499 mean the request had a problem. |
500 |
Internal Server Error | Something broke on the server. Codes from 500 to 599 mean the server had a problem, not you. |
Try it. Ask for a breed that doesn't exist: https://dog.ceo/api/breed/unicorn/images/random. The API still answers, with JSON that says what went wrong:
{"status":"error","message":"Breed not found (main breed does not exist)","code":404}
To see the status code itself, open DevTools (F12), click the Network tab and reload the page. The Status column says 404. Then go back to the beagle address and reload: 200.
Check yourself
2 questions to try on the lesson page.
So what
A URL to ask, a method for what to do, a status code for how it went and JSON for the answer: that's the same for the dog API, a weather service, a payment company and your own server, so once you can read one API, you can read them all.