Sooner or later a Python script needs to talk to the web: fetch the weather, pull a list of products, submit a form to an API, or check whether a page is online. Python ships with tools for this in its standard library, but most developers reach for the Requests library instead, because it reduces the whole job to a few readable lines.
These python requests examples cover the calls you will make most often: a basic GET, passing query parameters, reading JSON, sending POST data, adding headers, setting timeouts, and handling errors properly. Every example uses the same small set of functions, so once the pattern clicks the rest is variation. As with any third party library, install Requests inside a Python virtual environment so the project stays isolated and reproducible.
Installing Requests and Making a First GET Request
Requests is not part of the standard library, so install it with pip after activating your environment. One command is all it takes, and after that you import the library at the top of your script.
python -m pip install requests
import requests
response = requests.get("https://example.com")
print(response.status_code) # 200
print(response.text[:100])
The get function sends an HTTP GET request to the URL and returns a response object. The status_code attribute tells you how the server answered: 200 means success, 404 means not found, and 500 signals a server side problem. The text attribute holds the body of the response as a string, here sliced to the first hundred characters so the example output stays short. Nearly every Requests call follows this shape: call a function with a URL, then work with the returned response object.
The response also carries other useful information, such as the headers the server sent back and the final URL after any redirects. Requests follows redirects automatically for GET calls, which matches what a browser does when a page has moved.
Passing Query Parameters
Many URLs include a query string, the part after a question mark that carries search terms, page numbers, or filters. Building that string by hand with string formatting is error prone, especially when values contain spaces or symbols. Requests handles it with a params dictionary.
import requests
params = {"q": "python books", "page": 2}
response = requests.get("https://example.com/search", params=params)
print(response.url)
The params argument accepts a dictionary of keys and values. Requests encodes them correctly and attaches them to the URL, which you can confirm by printing response.url; it will show the full address including the encoded query string. Using a dictionary keeps your code readable and lets you build the parameters from variables elsewhere in the program, for example from user input or from values stored using the patterns in the Python dictionary guide. Encoding matters because characters like spaces and ampersands have special meanings in URLs, and Requests takes care of escaping them for you.
Working With JSON Responses
Most modern APIs return JSON, a text format that maps neatly onto Python dictionaries and lists. The response object has a json method that parses the body for you, so there is no need to handle the raw text manually.
import requests
response = requests.get("https://api.example.com/users/1")
data = response.json()
print(data["name"])
print(data["email"])
Calling response.json converts the JSON text into Python objects. If the top level of the JSON is an object, you get a dictionary and can access fields by key, as shown with name and email. If the API returns a list of items, you get a Python list and can loop over it or index into it as usual. A failed parse raises an error, which typically means the server did not actually return JSON, perhaps because of an error page, so experienced developers check the status code before parsing, a habit the error handling section below builds on.
Lists of records are the most common API shape. Combining a loop with the json method covers a large share of everyday API work.
import requests
response = requests.get("https://api.example.com/products")
products = response.json()
for product in products:
print(product["title"], product["price"])
Here the parsed result is stored in products and iterated directly. Each product is a dictionary, so the loop prints its title and price. If you need to reshape that data, comprehensions work well on it, turning the list of dictionaries into a list of just titles, for example, in the style covered by the list comprehensions article.
Sending Data With POST Requests
GET retrieves data. POST sends data to the server, for creating records, submitting forms, or logging in to an API. Requests offers two common ways to send the body: form data with the data argument, and JSON with the json argument. Choosing between them depends on what the receiving API expects, which its documentation will state.
import requests
form_data = {"username": "sara", "plan": "basic"}
response = requests.post("https://example.com/signup", data=form_data)
print(response.status_code)
The data argument sends the dictionary as form encoded data, the same format a browser uses when submitting a standard HTML form. The server reads the fields by name on its side. A successful creation often returns a 201 status code rather than 200, so check the API documentation for the expected success code instead of assuming one value.
import requests
payload = {"title": "New note", "done": False}
response = requests.post("https://api.example.com/notes", json=payload)
print(response.json())
The json argument serialises the dictionary to JSON and also sets the correct content type header automatically. That convenience is one reason Requests is popular for API work: a single keyword handles conversion and headers together. The response is parsed with the same json method used for GET calls, often returning the created record including any ID the server assigned.
Adding Headers and Authentication
Headers carry extra information with a request: the format you accept, a custom user agent, or an access token for APIs that require login. Pass a headers dictionary to any Requests call.
import requests
headers = {
"Accept": "application/json",
"Authorization": "Bearer YOUR_TOKEN_HERE"
}
response = requests.get("https://api.example.com/me", headers=headers)
print(response.status_code)
The Accept header tells the server you want JSON back. The Authorization header carries a bearer token, the most common scheme for API keys and login tokens. Replace the placeholder with a real token from the service you are using, and treat that token like a password: keep it out of shared code and public repositories, ideally reading it from an environment variable instead of writing it directly in the script. For basic authentication with a username and password, Requests provides an auth argument that takes a tuple of the two values and builds the proper header for you.
Reading response headers works in the other direction and is useful for checking content type or rate limit information.
print(response.headers.get("Content-Type"))
Response headers behave like a dictionary, so get with an optional default is a safe way to read one without risking a missing key error. The content type tells you whether the body is HTML, JSON, or something else, which helps a script decide how to process what came back.
Timeouts, Errors, and Checking Status
Networks fail in ordinary ways: a server is slow, a connection drops, a name does not resolve. Code that talks to the network needs to expect this. The two habits that matter most are setting a timeout on every call and checking for HTTP errors explicitly.
import requests
try:
response = requests.get("https://example.com/data", timeout=10)
response.raise_for_status()
data = response.json()
except requests.exceptions.Timeout:
print("The request took too long")
except requests.exceptions.HTTPError as err:
print("HTTP error:", err)
except requests.exceptions.RequestException as err:
print("Request failed:", err)
The timeout argument, in seconds, stops the call from hanging forever if the server never answers; without it, a stuck connection can freeze your script indefinitely. The raise_for_status method converts error status codes like 404 or 500 into an HTTPError exception, so failures cannot slip through silently as if they were successful responses. The except blocks catch the specific timeout case first, then HTTP errors, then the general RequestException class that all Requests errors inherit from. This structure lets a script retry, log the problem, or inform the user, instead of crashing with a traceback or, worse, processing an error page as if it were data.
You will not need every layer in a quick personal script, but timeout plus raise_for_status should be present in anything you plan to keep or share. Those two additions cost one short line each and prevent the most confusing class of bugs, where bad responses flow into the rest of the program disguised as good data.
Downloading Files and Using a Session
Requests can download files by reading the response content as bytes. For small files you can write response.content directly. For larger files, streaming the response and writing it in chunks keeps memory use low.
import requests
with requests.get("https://example.com/report.pdf", stream=True) as r:
r.raise_for_status()
with open("report.pdf", "wb") as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
The stream=True argument delays downloading the body until you start reading it. The iter_content method yields the file in chunks of the given size, and each chunk is written to a local file opened in binary write mode. Wrapping both the request and the file in with blocks ensures they close properly even if an error occurs midway. Saving what you download uses the same file writing ideas as the general Python file handling guide, just with bytes from the network instead of text from your own program.
When a script makes many calls to the same site, a Session object is worth using. A session remembers settings such as headers and cookies across requests, so you set them once instead of repeating them on every call.
import requests
session = requests.Session()
session.headers.update({"Accept": "application/json"})
first = session.get("https://api.example.com/items")
second = session.get("https://api.example.com/items/2")
The session is created once, its headers are updated in one place, and both get calls made through it share those headers automatically. Login based workflows benefit most, because cookies set by a login response are kept by the session and sent with later requests, mirroring how a browser stays logged in across pages.
Conclusion
The Requests library covers everyday HTTP work with a small, consistent set of tools: get and post for the calls themselves, params for query strings, json for sending and reading JSON, headers for tokens and preferences, and timeout with raise_for_status for safety. Start with those python requests examples as templates, adjust the URLs and fields for the service you are talking to, and your scripts will handle the web in a predictable, readable way.
Tagged: python http get python json api python post request python requests examples python snippets requests library



2 thoughts on “Make HTTP Requests in Python With the Requests Library”