Calling Web APIs with requests
Talk to any web service from Python: send a request, read the response.
requests library turns that whole conversation into a few readable lines: you pick an HTTP verb, aim it at a URL, maybe attach parameters or a JSON body, and read back a response with a status code and data.
- send GET and POST requests with
requests, - attach query parameters the safe way with
params=, - send and read JSON bodies,
- read and act on status codes (2xx / 4xx / 5xx),
- handle timeouts and network errors without crashing.
1. What is a web API?
An API (Application Programming Interface) is a contract: a server publishes a set of URLs (called endpoints) and promises that if you send the right request, it will send back a useful response. A web API speaks over HTTP, the same protocol your browser uses.
Analogy: think of a restaurant. You (the client) do not walk into the kitchen. You give a waiter a specific order (the request); the kitchen prepares it and the waiter brings back a plate (the response). The menu is the API documentation: it tells you exactly what you can ask for and how.
The requests library is the de-facto standard way to be that client in Python. It is not in the standard library, so you install it once:
pip install requests
Then in your program you import it and make a call:
import requests
response = requests.get("https://api.example.com/status")
print(response.status_code)
2. HTTP verbs: what do you want to do?
Every request carries a verb (also called a method) that states your intent. requests gives you a function per verb:
| Verb | Function | Meaning | Typical use |
|---|---|---|---|
| GET | requests.get() | Read data | Fetch a weather report, a user profile |
| POST | requests.post() | Create something new | Submit a form, add a new record |
| PUT | requests.put() | Replace a resource fully | Overwrite an existing profile |
| PATCH | requests.patch() | Update part of a resource | Change just the email field |
| DELETE | requests.delete() | Remove a resource | Delete a saved item |
GET should never change anything on the server (it is "safe" and can be retried freely). The verb is a promise about intent, so pick the one that matches what you are really doing.