Your weather app has no weather
A weather app on your phone does not measure the weather. It asks a service that does.
It sends a short message: "What is the weather in Leeds?" A moment later it gets an answer. Then it draws the answer on your screen.
This way of asking is called an API (a way for one program to ask another for data).
Key words
| Word | What it means | Example |
|---|---|---|
| API | A way for one program to ask another for data or a job. | a weather service |
| Endpoint | One web address of an API that gives one kind of data. | /scores |
| Request | The message your program sends to the API. | |
| Response | The answer the API sends back. | |
| HTTP method | The word in a request that says what to do. | |
| JSON | A text format for data that programs read easily. | {"player": "Aisha"} |
| Parse | Read text and turn it into data your program can use. | |
| API key | A secret code that tells the API who is asking. | |
| Status code | A number in the response that says how it went. |
The cells students fill in are left blank in this preview.
A request and a response
sequenceDiagram
participant App as Your app
participant API as API
participant DB as Database
App->>API: GET /scores
API->>DB: read the scores table
DB-->>API: rows
API-->>App: 200 OK and JSON text
Note over App: parse the JSON and show it
Check: the words
Have a go
Check: the words
3 questionsRequest methods
| Method | Job | Example |
|---|---|---|
| GET | Read data | Get the list of scores |
| POST | Create new data | Add a new score |
| PUT | Replace a whole item | Replace one player's record |
| PATCH | Change part of an item | Change only the points |
| DELETE | Remove data | Delete one score |
The cells students fill in are left blank in this preview.
Status codes to know
| Code | Meaning |
|---|---|
| 200 | OK. It worked |
| 201 | Created. The new item was made |
| 400 | Bad request. Your message has a mistake |
| 401 | Unauthorized. Your key or sign-in is missing or wrong |
| 404 | Not found. That address does not exist |
| 500 | Server error. The fault is on the other side |
The cells students fill in are left blank in this preview.
Parsing turns JSON text into data
import json
text = '[{"player": "Aisha", "points": 12}, {"player": "Sam", "points": 30}]'
players = json.loads(text) # parse: text to a list of dictionaries
for one in players:
print(one["player"], "has", one["points"], "points")
# Add a third player to the text and run again.
Make a free account to save your work and track your progress.
Show parsed data on a page
<h2>Scores</h2>
<ul id="list"></ul>
Make a free account to save your work and track your progress.
Code in the browser is not hidden
Warning
Many people think a key inside browser code is hidden. It is not: anyone can read code that reaches the browser. With your key, they use the service as you, and you may pay. Keep the key on the server, outside the code. Never put it in a public repository (a place online where anyone can see your code).
Try a real API in the lab
Press Start the lab and wait. The lab has a database (an organised store of data) and a web API in front of it. You make a table, then read and change it only with web requests.
In the terminal, curl sends the requests. Each Run button below does one thing. -w "\n" ends each answer with a new line, so it sits on its own line.
In step 6, player=eq.Aisha means: only the rows where player equals Aisha.
1. Set the database password
export PGPASSWORD=shopA command for the lesson’s lab terminal. It is shown here and not run.
2. Make a table
psql -h db -U shop -c "create table if not exists scores (id serial primary key, player text not null, points integer not null)"A command for the lesson’s lab terminal. It is shown here and not run.
3. Add two rows
psql -h db -U shop -c "insert into scores (player, points) values ('Aisha', 12), ('Sam', 30)"A command for the lesson’s lab terminal. It is shown here and not run.
4. Tell the API to look again
psql -h db -U shop -c "notify pgrst, 'reload schema'"A command for the lesson’s lab terminal. It is shown here and not run.
5. GET: read the data
curl -s -w "\n" http://api:3000/scoresA command for the lesson’s lab terminal. It is shown here and not run.
6. GET with a filter
curl -s -w "\n" "http://api:3000/scores?player=eq.Aisha"A command for the lesson’s lab terminal. It is shown here and not run.
7. POST: add a score (nothing prints)
curl -s -X POST -H "Content-Type: application/json" -d '{"player":"Ben","points":7}' http://api:3000/scoresA command for the lesson’s lab terminal. It is shown here and not run.
8. GET again: is Ben there?
curl -s -w "\n" http://api:3000/scoresA command for the lesson’s lab terminal. It is shown here and not run.
9. PATCH: change a score
curl -s -X PATCH -H "Content-Type: application/json" -d '{"points":15}' "http://api:3000/scores?player=eq.Aisha"A command for the lesson’s lab terminal. It is shown here and not run.
10. DELETE: remove a score
curl -s -X DELETE "http://api:3000/scores?player=eq.Ben"A command for the lesson’s lab terminal. It is shown here and not run.
11. GET the final list
curl -s -w "\n" http://api:3000/scoresA command for the lesson’s lab terminal. It is shown here and not run.
Write up what you saw
Answer in your own words. 1. What did the GET request in step 5 return, and in what format? 2. After the POST in step 7, what did the GET in step 8 show? 3. Which method changed the points, and what did the last GET in step 11 show? 4. This lab API has no API key. Why would a real weather service ask for one? Add a copy of your terminal output if your teacher asks.
A teacher marks this in a college. Nothing you write here is kept: it goes when you leave the page.
Make a free account to save your work, or press Start lab to work through the whole lesson.
Use API data in Python
A game service sends scores as JSON text. Finish four functions. build_url makes the address of a request. top_player finds the winner. score_lines makes lines to show. with_key adds an API key to an address. Press Run Tests.
import json
def build_url(base, endpoint, params):
# Join the base address, a slash and the endpoint. If params is not empty,
# add a question mark and the parameters as name=value pairs joined by &.
# build_url("http://api.test", "scores", {"player": "Aisha"})
# gives "http://api.test/scores?player=Aisha"
return None
def top_player(json_text):
# json_text is a JSON list of players, such as
# '[{"player": "Aisha", "points": 12}, {"player": "Sam", "points": 30}]'
# Give back the name of the player with the most points.
return None
def score_lines(json_text):
# Give back a list of text lines like "Aisha: 12 points", in the same order.
return None
def with_key(url, key):
# Add the API key to the address. If the address already has a question mark,
# add &key=... , otherwise add ?key=...
return None
Make a free account to save your work, or press Start lab to work through the whole lesson.
Match each method or code to its meaning
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Exit quiz
Have a go