HTTP Requests & APIs (requests)
An API lets your program talk to other programs over the internet — weather data, currency rates, your own backend. The requests library makes calling them feel as easy as calling a function.
Learn HTTP Requests & APIs (requests) in our free Python course — a beginner-friendly interactive lesson with runnable examples, a practice exercise and a…
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
In this lesson you'll send GET and POST requests, read JSON responses, pass parameters and headers, and handle errors like a professional.
Every time you load a webpage, your browser sends an HTTP request to a server and gets a response back. Your Python program can do exactly the same thing — but instead of HTML, APIs usually return JSON data your code can use.
🌐 The four most common HTTP methods (verbs):
First, install the library (it's not built in):
A GET request fetches data. The response object gives you the status code, the raw text, and a handy .json() method:
response.json() is the bridge to the last lesson — it runs json.loads on the response body for you and hands back a normal Python dict or list.
Every response carries a status code. You only need to recognise the families:
Rather than checking codes by hand, let requests raise an exception on failure:
Most APIs accept parameters to filter or page results. Pass a dict to params= and requests builds the URL correctly (including escaping special characters):
To create something on a server, send a POST with a JSON body. The json= argument serializes your dict and sets the right header automatically:
Use json= for JSON bodies (the common case) and data= for form-encoded bodies (like an HTML form submission).
Networks fail. Servers go down. A professional request always has a timeout and a try/except around it:
This is what a clean, reusable API client looks like — parameters, headers, error handling and a tidy return value all in one place:
Notice how the messy nested JSON ( data["main"]["temp"] ) gets flattened into a clean dict the rest of your program can use without knowing the API's structure.
These lines fetch an API and print one field, but they're scrambled. Find the correct order:
Import, define the URL, make the request, check for errors before trusting the body, then parse and use it.
Success — a 200 status makes response.ok True (any 2xx code is OK).
json= — passing json=your_dict serializes it and sets the Content-Type to application/json. params= is for URL query strings; data= is for form-encoded bodies.
4xx — client error — 404 // 100 is 4, the "your mistake" family (resource not found).
Your programs can now talk to the whole internet!
You can send GET and POST requests, pass params and headers, read JSON responses, and handle timeouts and errors gracefully. APIs are how modern software connects — this skill opens thousands of doors.
🚀 Up next: Reading CSV & Excel Files — work with the spreadsheet data that runs the business world.
Practice quiz
What does response.json() do?
- Saves the response to a .json file
- Parses the JSON body into a Python dict or list
- Converts a dict to a JSON string
- Validates the JSON schema
Answer: Parses the JSON body into a Python dict or list. It runs json.loads on the response body and hands back a normal Python dict or list.
Which HTTP method fetches data (read) from an API?
- GET
- POST
- PUT
- DELETE
Answer: GET. GET retrieves data; POST creates, PUT/PATCH update, DELETE removes.
A response with status_code 200 makes response.ok equal to what?
- False
- True
- None
- 200
Answer: True. Any 2xx status (including 200) makes response.ok True.
Which argument sends a JSON body in a POST request?
- data=
- params=
- json=
- body=
Answer: json=. json=your_dict serializes it and sets Content-Type to application/json. params= is for query strings.
What does the params= argument do in requests.get?
- Sends a JSON body
- Builds and escapes the URL query string
- Sets request headers
- Adds a timeout
Answer: Builds and escapes the URL query string. params={'q': 'python'} becomes ?q=python in the URL, with special characters escaped for you.
What status family is a 404?
- 2xx — success
- 3xx — redirect
- 4xx — client error
- 5xx — server error
Answer: 4xx — client error. 404 // 100 is 4 — the 'your mistake' client-error family (resource not found).
What does response.raise_for_status() do on a 404 response?
- Returns False
- Raises requests.HTTPError
- Retries the request
- Returns the JSON
Answer: Raises requests.HTTPError. It raises an HTTPError for any 4xx or 5xx status, turning failures into catchable exceptions.
Why should every request include timeout=?
- It makes requests faster
- Without it, a stuck server can hang your program forever
- It is required syntax
- It caches the response
Answer: Without it, a stuck server can hang your program forever. A timeout makes a slow/unresponsive server fail cleanly instead of freezing your script.
Which exception is the parent of Timeout, ConnectionError, and HTTPError?
- requests.RequestException
- requests.Error
- Exception
- requests.HTTPError
Answer: requests.RequestException. requests.RequestException is the base class, making it a safe catch-all in a try/except.
A successful POST that creates a resource typically returns which status code?
- 200 OK
- 201 Created
- 204 No Content
- 400 Bad Request
Answer: 201 Created. 201 Created signals that the server made a new resource (e.g. jsonplaceholder returns id 101).