Module 6: Calling an AI service from Python · 10 min
Web requests and APIs
An API (application programming interface) lets one program talk to another over the internet. The requests package sends the message and reads the reply.
import requests
response = requests.get("https://api.github.com", timeout=10)
print(response.status_code) # 200 means success
data = response.json() # reply text -> Python data
print(list(data)[:3])
| Status code | Meaning |
|---|---|
| 200 | OK |
| 400 | Your request was wrong |
| 401 / 403 | Not allowed (check your key) |
| 429 | Too many requests, slow down |
| 500 | Problem on the server |
Always set a timeout, and check the status code before using the reply.