Lesson 7 of 12 · Data on the Wire
Query Parameters and Bodies
Learn the ways to send details with an API request: path parameters, query parameters with URL encoding, and JSON request bodies, and when to use each. With Python examples.
- 7 min read
- Beginner
- Reviewed
- What path parameters and query parameters are
- How to build a query string safely with URL encoding
- What a request body is and when to use one
- How to choose between the query string and the body
Three places to put details
A request often needs details: which city, how many results, the text of a new message. There are three places to put them:
- In the path, such as
/users/42. - In the query string, such as
?city=Hyderabad&limit=5. - In the body, as JSON.
Path parameters
base = "https://jsonplaceholder.typicode.com"
for post_id in [1, 2, 3]:
print(f"{base}/posts/{post_id}")API documentation usually shows path parameters in curly brackets or after a colon, such as /posts/{id} or /posts/:id, meaning "put the real number here".
Query parameters
In https://api.example.com/search?q=python&limit=5, there are two query parameters: q is python and limit is 5.
URL encoding
URLs may only contain certain characters. A space, &, ? or = inside a value would confuse the server, because those characters have special meanings in a URL.
Never build a query string by gluing text together. Let Python's urlencode() do it:
from urllib.parse import urlencode, parse_qs
params = {"q": "fish & chips", "city": "New Delhi", "limit": 5}
query = urlencode(params)
print(query)
url = "https://api.example.com/search?" + query
print(url)
# The server does the opposite and gets the original values back:
print(parse_qs(query))The & inside "fish & chips" became %26, so the server will not mistake it for the start of a new parameter.
With requests, you simply pass a dictionary as params=, and it does the encoding for you. response.url shows the final address that was used:
import requests
response = requests.get(
"https://api.open-meteo.com/v1/forecast",
params={"latitude": 17.38, "longitude": 78.49, "current": "temperature_2m,wind_speed_10m"},
timeout=10,
)
print(response.url)
print(response.json()["current"])Notice the comma in temperature_2m,wind_speed_10m became %2C in the final URL.
The request body
GET requests normally have no body. POST, PUT and PATCH requests usually do. With requests, pass a dictionary as json=. It is turned into JSON text, and the Content-Type: application/json header is added for you.
import requests
new_post = {"title": "APIs are fun", "body": "Today I learned about request bodies.", "userId": 7}
response = requests.post("https://httpbin.org/post", json=new_post, timeout=10)
echo = response.json()
print("Content-Type sent:", echo["headers"]["Content-Type"])
print("Body the server received:")
print(echo["data"])httpbin's /post endpoint sends back exactly what it received, so you can see your dictionary arrive as JSON text.
Query string or body?
| Use the query string for... | Use the body for... |
|---|---|
reading data with GET | creating or changing data with POST, PUT, PATCH |
| short options: filters, sorting, page numbers | large or nested data |
| values you would not mind seeing in a link | private data such as passwords |
URLs are often saved in browser history and server logs, so never put secrets in a query string.
Common mistakes
Build a search URL safely from a dictionary of filters.
from urllib.parse import urlencode
base = "https://api.example.com/v1/courses"
filters = {"q": "machine learning", "level": "beginner", "free": "true", "limit": 5}
# 1. Build the full URL: base + "?" + the encoded filters.
# 2. Print the URL.
# 3. Print how many query parameters there are.
# Output must be exactly:
# https://api.example.com/v1/courses?q=machine+learning&level=beginner&free=true&limit=5
# Parameters: 4
You want to send a long chat message and some settings to an AI model with POST. Where should they go?
Summary
- Path parameters pick an item, such as
/posts/42. - Query parameters add options after
?, asname=valuepairs joined with&. - URL encoding makes values safe for URLs. Use
urlencode()orparams=instead of gluing text. - The request body carries larger data, usually JSON sent with
json=. - Never put secrets in a query string.
Next: proving who you are with API keys.
Finished reading? Tick it off to track your progress.