Calling Web APIs from Python
Fetch data from any web API with Python: requests, JSON, keys, pagination, timeouts and errors.
A taste of a lesson
My script calls an API in a loop and sometimes just freezes. Why?
Most likely one request is waiting forever. Many HTTP libraries have no timeout by default, so if the server never answers, your loop never moves on. Add a timeout to every call, for example ten seconds, and catch the timeout error so you can log it and retry or skip that item. While you are there, print the status code of each response so you notice 429 or 500 errors too. Can you show me the line where you make the request?
Written with AI under Skill Lab's direction as an example. In your lesson the tutor answers your own questions, and like any AI it can be wrong. Right now the AI model is not connected: replies come from a built in test engine on this site.
What you will be able to do
- Send GET and POST requests and read the status, headers and JSON body
- Pass API keys through environment variables and headers, never in code
- Handle timeouts, errors and rate limits with sensible retries
- Collect every page of a paginated API into a file
- Recognise an AI model call as an ordinary HTTP request with a JSON body
Lesson plan
- 1 Requests and responses Describe what an HTTP request and response contain and make a first GET call. Start
- 2 Reading JSON responses Parse JSON responses and pull out the fields you need safely. Start
- 3 Keys, headers and POST bodies Authenticate with an API key and send a JSON body in a POST request. Start
- 4 Timeouts, errors and retries Make requests that fail clearly and retry only when retrying can help. Start
- 5 Pagination and polite fetching Collect every result from a paginated API without hammering it. Start
- 6 A model API call is just HTTP Send a JSON request to a mock model API and read text and usage from the reply. Start
Try asking
About this tutor
For beginners who want their Python code to talk to the outside world, which is the step right before calling AI model APIs. You learn what an HTTP request is, how to send GET and POST requests with a common HTTP library, read JSON responses, pass API keys safely, page through results, set timeouts and handle errors and rate limits without crashing. Exercises use free public APIs, then a mock of a model API so you see that an AI call is just another HTTP request with a JSON body. You finish with a small, sturdy fetch script you can adapt.
Reviews
Students can review a tutor after a paid lesson. Nobody has yet.
More like this
Other tutors on the same or nearby topics.