Asking a Service for Data: an API and JSON
Ask the Wikipedia API about real hardware pages with requests: an endpoint and parameters, the status code, a user agent, an answer in JSON, nested dictionaries and lists, and a key that is missing.
Last updated:
In this lesson we learn what an API is, how a program asks one for data with parameters and a user agent, how it checks the status code, and how it reads an answer in JSON:
nested dictionaries and lists, and a key that is missing.
A summary and a count of links for a hardware term
Suppose we want a study glossary of hardware terms: for each term, one short summary and a count of the links of its page.
The count turns out to need care, because the service sends a long list of links in parts.
A page of Wikipedia is made for a reader: next to the text it has a table of facts, numbers of references in square brackets and menus, and Beautiful Soup would cut each of them away, one part at a time.
Wikipedia offers another way: an API (application programming interface), a way that a service offers to programs to ask for data.
A page is written for a person, with tags and layout; an API answers a program with the data itself, in a format that a program reads without cutting anything out.
The English Wikipedia answers such questions at one address, https://en.wikipedia.org/w/api.php, and its rules are in the documentation of the API.
Every service writes its own rules: which questions it answers, how a question is written, and what the answer looks like.
The examples run in your browser: select Run from top to bottom, because the boxes of this page share their variables with each other.
If you press Stop or reload, run the page again from the top.
The first run of the page loads the library, so it can take a moment.
The notebooks of this lesson have the tasks numbered in order:
- The notebook with tasks: download · open in Colab
- The notebook with solutions: download · open in Colab
Saved answers of the real service
The security settings of this site let its pages call only this site, so the boxes of this page cannot call Wikipedia.
The answers were asked from the real service once, on 16 November 2026, and saved unchanged as six files on this site.
Each file holds the answer to one question, so the parameters that we write in the boxes do not change it.
On the real service the call is the same, with the address https://en.wikipedia.org/w/api.php and the same parameters.
The notebooks run the same code on the saved copies; their cell for the real service is off (RUN_LIVE = False), because a class shares one address and the service asks programs to send few requests.
The text of Wikipedia is available under the Creative Commons Attribution-ShareAlike 4.0 license (CC BY-SA 4.0).
The titles, summaries, lists of links and sizes of pages in the saved answers are from the English Wikipedia, en.wikipedia.org, retrieved on 16 November 2026 through its API; their authors are the editors of Wikipedia, whom the history of each page lists.
The files are unchanged, and a text that is taken from them must keep this attribution and the same license.
An endpoint and its parameters
The address to which a program sends its questions is an endpoint.
A question is written as query parameters: pairs of a name and a value that are added to the address after a ? and separated by &.
The function requests.get takes the parameters as a dictionary in its argument params, and builds the final address from them.
In the first question the parameters ask for the introduction of the page of the field-programmable gate array.
The attribute url of the response is the address that was sent, and split('?')[1] keeps the text after the question mark.
What the parameters say
| Parameter | Value | Meaning |
|---|---|---|
action | query | Ask for data about pages |
format | json | Write the answer in JSON |
formatversion | 2 | The newer, simpler layout of the answer |
prop | extracts | The property of the page that we want: a text extract |
exintro | 1 | Only the introduction, the text before the first heading |
explaintext | 1 | Plain text, without tags |
titles | Field-programmable gate array | The title of the page |
The box below sends the question of the table to the saved copy and prints the part of the address after the ?, as the library wrote it.
import requests
copies = (
'https://dvirross.com/materials/courses/'
'intro-data-science/'
)
summary_params = {
'action': 'query', 'format': 'json', 'formatversion': 2,
'prop': 'extracts', 'exintro': 1, 'explaintext': 1,
'titles': 'Field-programmable gate array',
}
response = requests.get(
copies + 'wikipedia-fpga-summary.json',
params=summary_params,
)
print(response.url.split('?')[1])
action=query&format=json&formatversion=2&prop=extracts&exintro=1&explaintext=1&titles=Field-programmable+gate+array
The library wrote each pair as name=value and replaced the spaces of the title with +, because an address has no spaces.
On the real service the same question is a call to the endpoint of Wikipedia.
It is shown here and not run, because the boxes of this page cannot reach it:
response = requests.get(
'https://en.wikipedia.org/w/api.php',
params=summary_params,
)
The final address that requests sends is the endpoint, a ? and the parameters, all on one line.
The same address in the address bar of a browser shows the answer as text.
https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2&prop=extracts&exintro=1&explaintext=1&titles=Field-programmable+gate+array
The status code
Every answer of a server starts with a status code, which a program checks before it reads the rest.
The attribute status_code of the response holds it. A request for a file that does not exist on this site returns a response with the code 404.
print(response.status_code)
missing = requests.get(copies + 'wikipedia-no-such-copy.json')
print(missing.status_code)
200
404
The common codes that a program meets in an API are these:
| Code | Meaning and what the program does |
|---|---|
| 200 | The answer arrived: read it |
| 403 | The service refuses: check the user agent and the rules |
| 404 | There is no such address: check the endpoint |
| 429 | Too many requests: wait before asking again; the answer may say for how long |
A program that does not check the code reads an error message as if it were data.
It checks with if response.status_code != 200: (!= means “is not equal to”) and stops with a message.
Headers and the user agent
A request carries, besides the parameters, headers: pieces of information about the request itself, given to requests.get as a dictionary in the argument headers.
The header that names the sender is User-Agent, the name of the program that sends the request, the user agent.
The library sends python-requests unless we write another name, and the Wikimedia Foundation, which runs Wikipedia, asks in its user-agent policy for a name that says what the program is and how to reach its owner.
The argument timeout is the number of seconds to wait for an answer before giving up; without it a program can wait forever.
headers = {
'User-Agent': (
'IntroDataScienceCourse/1.0 '
'(teaching example; contact via dvirross.com)'
)
}
response = requests.get(
copies + 'wikipedia-fpga-summary.json',
params=summary_params,
headers=headers,
timeout=30,
)
if response.status_code != 200:
print('The service answered', response.status_code)
else:
print('The answer arrived')
The answer arrived
The saved copy does not read the header; the real service does.
A polite program also asks few questions, one at a time, and keeps the answers, as the saved copies of this lesson do, instead of asking again.
The answer is JSON
The answer of the API is text in a format called JSON (JavaScript Object Notation).
It is written with curly brackets that hold names and values, and square brackets that hold lists, dictionaries and lists like those of Python, with true, false and null in place of True, False and None.
The text of the answer is response.text, a string.
The method json() of the response reads the text and returns Python values:
a dictionary for the curly brackets, a list for the square brackets, and text, numbers, True and None for the rest.
The function type tells the type of a value, and a dictionary has a method keys() that returns its keys, the names, which list turns into a list.
data = response.json()
print(type(response.text), type(data))
print(list(data.keys()))
<class 'str'> <class 'dict'>
['batchcomplete', 'query']
Dictionaries and lists, one inside the other
The answer is a dictionary that holds a dictionary, which holds a list of dictionaries.
Here is the whole answer with the long text of the extract cut short:
{
"batchcomplete": true,
"query": {
"pages": [
{
"pageid": 10969,
"ns": 0,
"title": "Field-programmable gate array",
"extract": "A field-programmable gate array (FPGA) is a type of ..."
}
]
}
}
A value in the middle is reached one step at a time, with square brackets:
a key for a dictionary, and for a list the index, the place of the item, counted from 0.data['query'] is a dictionary; ['pages'] in it is a list with one item for each title that we asked about; [0] is its first item, a dictionary of one page; and ['title'] and ['extract'] are its values.
The method split('. ') cuts a text at every period that is followed by a space, so [0] of its result is the first sentence.
pages = data['query']['pages']
print(type(pages), len(pages))
page = pages[0]
print(page['title'])
print(len(page['extract']))
print(page['extract'].split('. ')[0])
<class 'list'> 1
Field-programmable gate array
1951
A field-programmable gate array (FPGA) is a type of configurable integrated circuit that can be repeatedly programmed after manufacturing
The summary of the page is 1,951 characters, and its first sentence says what an FPGA is.
The program did not cut anything out of tags: it walked down the structure by names and places.
Practice
Your turn. The variable data holds the answer about the field-programmable gate array.
Print the length of the summary of the page in characters and, after a space, the number of its words:
the number of words that split() finds in the extract.
# your code here
Show a hint
Walk down the answer as in the box above, to the extract of the first page.
The method split() without an argument cuts a text at its spaces and line breaks and returns a list of its words, and len counts a list.
Show a solution
text = data['query']['pages'][0]['extract']
print(len(text), len(text.split()))
1951 284
Show a common mistake and why it happens
text = data['query']['pages'][0]['extract']
print(len(text), len(text.split('. ')))
The argument '. ' cuts the text at the end of each sentence, so the second number, 8, is the number of sentences and not the number of words.
Several pages in one question
Self-study, importance 1 This part is for self-study: it is not taught in the lecture, and you read it on your own. Several titles in one question and the order of the answer. It helps with: asking a service about several items at once and finding the largest and the smallest by a key.
The parameter titles takes several titles, separated by |. The property info returns facts about a page, such as length, the size of its source text in bytes.
The answer holds a list with one dictionary for each page, and a for loop goes over it.
info_params = {
'action': 'query', 'format': 'json', 'formatversion': 2,
'prop': 'info',
'titles': (
'RISC-V|Hardware description language|'
'Field-programmable gate array'
),
}
info = requests.get(
copies + 'wikipedia-pages-info.json',
params=info_params,
).json()
info_pages = info['query']['pages']
for page in info_pages:
print(page['title'], page['length'])
Field-programmable gate array 68061
Hardware description language 36937
RISC-V 170750
The pages are not in the order of the question: the service returns them in its own order, here alphabetical.
So a program finds a page by its title and not by its place in the list.
Your turn. The list info_pages holds a dictionary for each of the three pages.
Find the longest page and the shortest page by length, and print the title of the longest page and, after a space, how many times it is longer than the shortest page, rounded to one digit after the decimal point.
# your code here
Show a hint
The function max returns the item with the largest value, and its argument key says what to compare:max(info_pages, key=lambda page: page['length']), where lambda page: page['length'] is a small function that takes a page and returns its length.
The function min works the same way.
Show a solution
longest = max(info_pages, key=lambda page: page['length'])
shortest = min(info_pages, key=lambda page: page['length'])
ratio = longest['length'] / shortest['length']
print(longest['title'], round(ratio, 1))
RISC-V 4.6
Show a common mistake and why it happens
longest = max(info_pages, key=lambda page: page['length'])
shortest = min(info_pages, key=lambda page: page['length'])
ratio = shortest['length'] / longest['length']
print(longest['title'], round(ratio, 1))
The division is the other way round, so it says how large the shortest page is as a fraction of the longest, 0.2, and not how many times the longest is longer.
The links of a page
The property links returns the pages that a page links to. The parameter pllimit is the largest number of links in one answer, and max asks for the largest that the service allows; plnamespace set to 0 keeps only links to articles, and not to pages of help or of discussion.
The answer holds, in the page, a list links, and each link is a dictionary with a title.
links_params = {
'action': 'query', 'format': 'json', 'formatversion': 2,
'prop': 'links', 'pllimit': 'max', 'plnamespace': 0,
'titles': 'Field-programmable gate array',
}
links_data = requests.get(
copies + 'wikipedia-fpga-links.json',
params=links_params,
).json()
links = links_data['query']['pages'][0]['links']
print(len(links))
print(links[0])
500
{'ns': 0, 'title': '20-sim'}
The answer has 500 links, and 500 is the limit of one answer for a program without special rights, not the number of links of the page.
The answer says so itself: it has a key continue, which holds the place where the next answer would start.
The operator in tests whether a key is in a dictionary.
print('continue' in links_data)
print(links_data['continue']['plcontinue'])
True
10969|0|Power_engineering_software
The links are ordered by their titles, and the next answer starts at “Power engineering software”.
So the number 500 describes the first part of the links, from the start of the alphabet to the letter P, and a program that reports “the page has 500 links” would be wrong.
Asking for the rest is a repetition of the request with the value of continue added to its parameters.
The method lower() returns a text in lowercase letters, and in also tests whether a text contains another one:'logic' in 'Logic gate' is False, because the capital letter is a different character, and 'logic' in 'Logic gate'.lower() is True.
Your turn. Among the links in links, how many have a title that contains the letters logic, with a capital letter or without?
Print how many there are, as one number.
# your code here
Show a hint
Build a list with a list comprehension, [link['title'] for link in links if ...], whose condition tests the lowercase title:'logic' in link['title'].lower(). Print the length of the list.
Show a solution
with_logic = [link['title'] for link in links if 'logic' in link['title'].lower()]
print(len(with_logic))
16
The count is of the first 500 links of the page, since this is what the answer holds.
Show a common mistake and why it happens
with_logic = [link['title'] for link in links if 'logic' in link['title']]
print(len(with_logic))
The test 'logic' in link['title'] is case sensitive, so it misses titles such as Logic gate and Logic block, which have a capital letter, and counts only 10 of the 16.
A key that is missing
Not every page that we ask about exists. The next question asks for the summaries of two titles:RISC-V, and RISC-VI, a title that no page has. For the missing title the service answers with an item that has the key missing and no key extract, and it comes first in the list.
missing_params = {
'action': 'query', 'format': 'json', 'formatversion': 2,
'prop': 'extracts', 'exintro': 1, 'explaintext': 1,
'exlimit': 'max', 'titles': 'RISC-V|RISC-VI',
}
answer = requests.get(
copies + 'wikipedia-summary-missing.json',
params=missing_params,
).json()
missing_pages = answer['query']['pages']
print(len(missing_pages))
print(missing_pages[0])
2
{'ns': 0, 'title': 'RISC-VI', 'missing': True}
Reading a key that is not there with square brackets stops the program with a KeyError.
This is what missing_pages[0]['extract'] does, and a program that reads many pages stops at the first missing one:
KeyError: 'extract'
The method get of a dictionary takes a key and a default value, and returns the default instead of an error when the key is missing.
With one argument, get('extract'), the default is None. A default value of the right kind lets the rest of the program go on:
an empty text '' for a text.
for page in missing_pages:
text = page.get('extract', 'no such page')
print(page['title'], '|', text.split('. ')[0])
RISC-VI | no such page
RISC-V | RISC-V (pronounced "risk-five") is a free and open standard instruction set architecture (ISA) for computer CPUs
The same care is needed for a whole answer. A question that the service cannot answer, here an action that does not exist, gets the status code 200 as well, and the answer holds a key error instead of the key query:
bad = requests.get(
copies + 'wikipedia-error.json',
params={'action': 'nonsense', 'format': 'json'},
).json()
print(bad.get('query', 'no query in the answer'))
print(bad['error']['info'])
no query in the answer
Unrecognized value for parameter "action": nonsense.
A program that reads an API checks the status code first, and then checks that the answer has the key that it needs.
Your turn. For each page in missing_pages, print its title and, after a space, the number of words of its summary:
the number of words that split() finds in the extract. A page that has no summary has 0 words.
# your code here
Show a hint
Take the extract with get and the default '', an empty text, and split it:len(page.get('extract', '').split()). The method split() of an empty text returns an empty list, whose length is 0.
Show a solution
for page in missing_pages:
words = page.get('extract', '').split()
print(page['title'], len(words))
RISC-VI 0
RISC-V 176
Show a common mistake and why it happens
for page in missing_pages:
words = page.get('extract', 'no such page').split()
print(page['title'], len(words))
The default 'no such page' is a text of three words, so the missing page gets the number 3 and not 0.
A default has to be a value that the next step can use and that stands for “nothing”:
for a text that is split into words, an empty text.
A search question
Self-study, importance 2 This part is for self-study: it is not taught in the lecture, and you read it on your own. A search question, repeating a request to get all the links of a page, and a Python package for the Wikipedia API. It helps with: reading search results, collecting the parts of an answer that comes in parts, and using a package that calls an API.
The answer to a search is a list too. The parameter list set to search asks the service to search for the words of srsearch, and srlimit is the number of results in the answer.
The answer has, besides the results, the number of all the hits, totalhits, inside the dictionary searchinfo.
search_params = {
'action': 'query', 'format': 'json', 'formatversion': 2,
'list': 'search', 'srlimit': 5,
'srsearch': 'hardware description language',
}
search = requests.get(
copies + 'wikipedia-search-hdl.json',
params=search_params,
).json()
print(search['query']['searchinfo']['totalhits'])
for hit in search['query']['search']:
print(hit['title'], hit['wordcount'])
18047
Hardware description language 3718
VHDL 4278
Altera Hardware Description Language 275
Ruby (hardware description language) 267
Verilog 4227
The answer holds the first five of the 18,047 pages that fit the words.
Each hit also has a snippet, a piece of its text with the found words wrapped in HTML tags.
All the links of a page
To get all the links of a page, the program repeats the request.
An answer that has a key continue says where the next one starts:
its values are added to the parameters of the next request, and the loop stops when an answer has none.
The code is shown and not run, because the saved copy holds only the first answer.
The call {**links_params, **extra} writes the pairs of two dictionaries into one new dictionary, and time.sleep(1) pauses for a second between requests, to stay polite.
import time
all_links = []
extra = {}
while True:
answer = requests.get(
'https://en.wikipedia.org/w/api.php',
params={**links_params, **extra},
headers=headers,
timeout=30,
).json()
page = answer['query']['pages'][0]
all_links += [link['title'] for link in page.get('links', [])]
if 'continue' not in answer:
break
extra = answer['continue']
time.sleep(1)
print(len(all_links))
The number of links of a page changes with every edit of the page, so a program that runs it gets the number of that day.
A package that asks for us
Some services have a Python package that writes the requests for us.
For Wikipedia it is Wikipedia-API, imported as wikipediaapi.
The code is shown and not run, because it calls the service.
The package builds the address, sends the user agent that we give it, and returns the page as an object with a summary and its links.
import wikipediaapi
wiki = wikipediaapi.Wikipedia(
user_agent=(
'IntroDataScienceCourse/1.0 '
'(teaching example; contact via dvirross.com)'
),
language='en',
)
page = wiki.page('Field-programmable gate array')
print(page.summary[:200])
print(len(page.links))
A package is shorter, and it hides the parameters and the structure of the answer; a service that has no package is still within reach for a program that makes the call itself.
Keep in mind
- An API is a way that a service offers for programs to ask for data; its answer is data, not a page to cut out of tags.
- A question is an endpoint and query parameters:
requests.get(url, params={...})writes the final address, withname=valuepairs after a?. headers={'User-Agent': ...}says who is asking, andtimeoutlimits the wait. A polite program asks few questions, one at a time, and keeps the answers.- Check
response.status_codefirst: 200 is an answer, and 429 means to wait. A service can also answer 200 with an error inside the JSON. response.json()returns dictionaries and lists, and a value is reached with keys and indexes:data['query']['pages'][0]['title'].- An answer can be a part of the data: the key
continuesays that there is more, and a count of the answer is not a count of the page. - A missing key stops the program with
KeyError;get(key, default)returns a default, and the default should be of the kind that the next step needs.