Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

OS 6.3 (1 of 3): Connecting to data with an API

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

55 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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

WordWhat it meansExample
APIA way for one program to ask another for data or a job.a weather service
EndpointOne web address of an API that gives one kind of data./scores
RequestThe message your program sends to the API.
ResponseThe answer the API sends back.
HTTP methodThe word in a request that says what to do.
JSONA text format for data that programs read easily.{"player": "Aisha"}
ParseRead text and turn it into data your program can use.
API keyA secret code that tells the API who is asking.
Status codeA 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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Request methods

MethodJobExample
GETRead dataGet the list of scores
POSTCreate new dataAdd a new score
PUTReplace a whole itemReplace one player's record
PATCHChange part of an itemChange only the points
DELETERemove dataDelete one score

The cells students fill in are left blank in this preview.

Status codes to know

CodeMeaning
200OK. It worked
201Created. The new item was made
400Bad request. Your message has a mistake
401Unauthorized. Your key or sign-in is missing or wrong
404Not found. That address does not exist
500Server 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

Code: python
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

Code: web
<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

Command
export PGPASSWORD=shop

A command for the lesson’s lab terminal. It is shown here and not run.

2. Make a table

Command
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

Command
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

Command
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

Command
curl -s -w "\n" http://api:3000/scores

A command for the lesson’s lab terminal. It is shown here and not run.

6. GET with a filter

Command
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)

Command
curl -s -X POST -H "Content-Type: application/json" -d '{"player":"Ben","points":7}' http://api:3000/scores

A command for the lesson’s lab terminal. It is shown here and not run.

8. GET again: is Ben there?

Command
curl -s -w "\n" http://api:3000/scores

A command for the lesson’s lab terminal. It is shown here and not run.

9. PATCH: change a score

Command
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

Command
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

Command
curl -s -w "\n" http://api:3000/scores

A 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.

Code: python
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

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.