Lesson 12 of 145 min
Calling an API
A program asks an API for data with a request; the answer comes back with a status code and JSON, which Python reads as dicts and lists, and a key that proves who is asking stays outside the code.
After this lesson you can send a request, read the JSON that comes back, and keep a key out of the code.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Stop on a bad status
r.json() reads whatever came back, an error too. Real code adds one line after every request: raise_for_status() stops at once on a status in the 400s or 500s, and says which. The Hub answers 401 for a name it doesn't know, so strangers can't tell which private models exist.
import requests
r = requests.get("https://huggingface.co/api/models/gtp2")
r.raise_for_status()
info = r.json()requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://huggingface.co/api/models/gtp2
Set the key in a terminal
On your own computer, a terminal gives its settings to every program you start from it. This line is for a Mac or Linux. On Windows, in PowerShell, write $env:HF_TOKEN = "hf_...". The setting lasts until you close that terminal. You make your key on huggingface.co, in Settings, under Access Tokens.
export HF_TOKEN=hf_...
python my_program.pyOr keep it in a .env file
A file named .env, beside your code, holds the key. python-dotenv copies it into the settings when your program starts, so the line that reads it stays the same. Keep the file to yourself: never share it or upload it with your code.
HF_TOKEN=hf_...pip install python-dotenvimport os
from dotenv import load_dotenv
load_dotenv()
key = os.environ["HF_TOKEN"]In Colab: the Secrets panel
Colab keeps keys in its Secrets panel, behind the key icon on the left. Add one named HF_TOKEN with your key as its value, and turn on its notebook access. Then one line reads it. Without that access, it stops with NotebookAccessError.
from google.colab import userdata
key = userdata.get("HF_TOKEN")Too many requests: 429
Without a key, the Hub answers 500 requests from you in each five minutes. With a free account's key, 1,000. Past that, the status is 429, Too Many Requests: wait for the five minutes to end. Every response says how many you have left (r) and how many seconds until the count starts again (t).
r = requests.get("https://huggingface.co/api/models/gpt2")
print(r.headers["RateLimit"])"api";r=497;t=283
httpx reads the same way, almost
You will also meet httpx, a newer library some AI tools use underneath. It reads like requests, with one difference. The Hub sends a request for gpt2 on to its full name, openai-community/gpt2. requests follows it there; httpx stops with status 307 unless you add follow_redirects=True.
import httpx
url = "https://huggingface.co/api/models/gpt2"
r = httpx.get(url, follow_redirects=True)
r.raise_for_status()
print(r.json()["cardData"]["license"])mit
Run on Python 3.13, requests 2.34.2, httpx 0.28.1 and python-dotenv 1.2.4. Checked on .
Quiz
Two questions on this lesson. Answer as often as you like.
1 of 2
print(r.status_code) shows 401. Then info["downloads"] stops with KeyError: 'downloads'. What happened?
2 of 2
r.json() gave this dict. What does the last line do?
info = {"id": "openai-community/gpt2", "downloads": 34394889,
"cardData": {"license": "mit"}}
print(info["license"])The ideas in this lesson
- A request and its response
- requests.get asks an API's address for data. The response has a status code: 200 means it worked.
- JSON
- An API answers in JSON, text of dicts and lists. r.json() turns it into Python's, read key by key.
- A key out of the code
- A key stays out of your code: it lives in an environment variable, and os.environ reads it like a dict.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
What comes back?
Here's a question. A program can ask a website for data. It's like your browser asking for a page. This line asks the Hugging Face Hub about one model. The Hub is the site where AI models are shared. So what comes back? A web page, one number, or something else?
A request
Keep your guess. First, the request. How does a program get data from a website? A browser asks an address for a page. A program asks an address too, but one made for programs. That address is an API.
Line one brings in requests, the Python library for asking.
Line three is the Hub's API. Line four adds the model's name, GPT-2, to make the address of its entry.
And line five sends a request there. The response comes back.
The status
Did it work? Line six prints the response's status code: two hundred. Every response carries a number like this. Two hundred means it worked. A number in the four hundreds means the API could not give what you asked for.
JSON
The response is the Hub's answer about GPT-2, with status two hundred. Now, back to the question. What came back?
Not a page. Text, in a form called JSON... written like Python's dicts and lists.
Curly brackets around keys and values. Square brackets around a list.
Line seven turns the text into them. Now info is a dict, like any other.
If you said a web page: browsers get pages. Programs get data.
One key
So how do you read one value?
By its key, as in any dict. Line eight reads the downloads: how many times GPT-2 was downloaded in the last month. Tens of millions, for one of the first models that writes text.
Two keys
But GPT-2's license isn't at the top. It's inside card data: a dict inside the dict.
So how do you reach it?
Two keys, one after the other. First card data, then license.
And the license is MIT.
A value inside a value: you read it key after key.
A wrong name
Now the same request, with two letters of the name in the wrong order.
Will line eight print the downloads?
Line six prints four oh one. That means not allowed. GPT-2 needed no key, so this is not about a key. Four oh one is the Hub's answer for any model it won't show you. And a model that doesn't exist is one of them.
Read the status
But Python didn't stop on line six.
It stops on line eight, with a KeyError: the error a dict gives for a key it doesn't hold. The dict holds the Hub's error message, and no downloads.
The message talks about a password, which doesn't help much... but the status already told you.
So read the status... before the data.
A key out of the code
A request goes to an API, and the answer comes back.
The Hub answered anyone. Some APIs also want an API key. That's another meaning of the word key: a password for programs. It says who is asking... and who pays.
Written in your code, a key goes wherever your code goes: to a friend, or onto GitHub. And anyone who has it can use it, on your bill.
So where should a key go?
Outside the code. It lives in an environment variable: a setting your computer gives every program it starts.
Python's os module holds those settings, like a dict.
Not set
On this Mac, the setting called HF token isn't there. So the line stops, with a KeyError: the same error a dict gives. That's a good thing. The error says which key is missing.
Set it once, outside the code, and the same line finds it. This lesson's page shows how, in Colab and on your own computer.
Then the request carries the key with it, in the form the API asks for. These two lines do it.
Your code names the key. It never holds it.
Status first
So here's what you saw. A request gets a response. Read its status first. Then read its JSON, key after key.
And a key lives outside your code.
Talk to the models
This is how your code will talk to AI models. Now try it on this lesson's page, and take the quiz. Read the model's first tag.
You use this lesson in Lab 5: On your own computer, after Git and GitHub.
Facts last checked on .
