Every HTTP request targets a specific address. Understanding URL structure means you can read requests like plain text instead of guessing what’s going on.
Anatomy of a URL
https://api.chucknorris.io/jokes/random?category=dev&limit=5
โ โ โ โ
โ โ โ โโโ query parameters
โ โ โโโโโโโโโโโโโโ path
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ host
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ scheme (protocol)
- Scheme (
https://) โ the data transfer protocol. Always usehttps, nothttp - Host (
api.chucknorris.io) โ the server address - Path (
/jokes/random) โ the specific resource on the server - Query parameters (
?category=dev) โ additional data for filtering or configuration
Query Parameters: Syntax
Query parameters start with ? and are written as key=value pairs:
?category=dev
Multiple parameters are separated by &:
?category=dev&limit=5&lang=ru
The Problem with Building URLs Manually
Assembling URLs by hand with f-strings is error-prone:
# Bad โ manual construction
city = "New York"
url = f"https://api.example.com/weather?city={city}"
# Result: ?city=New York โ the space will break the request!
Spaces and special characters (&, /, #, ?) in parameter values need to be URL-encoded:
- space โ %20
- & โ %26
- / โ %2F
Doing this by hand is a common source of bugs.
The Right Way โ params= in requests
The requests library handles encoding automatically:
import requests
response = requests.get(
"https://api.chucknorris.io/jokes/random",
params={"category": "dev"}
)
# Resulting URL: .../jokes/random?category=dev
Spaces are handled correctly too:
response = requests.get(
"https://api.example.com/search",
params={"q": "New York", "lang": "ru"}
)
# Resulting URL: .../search?q=New+York&lang=ru
Inspecting the Final URL
It’s sometimes useful to check what URL requests actually built:
response = requests.get(url, params=params)
print(response.url) # prints the full URL with parameters
Path Parameters vs Query Parameters
There are two ways to pass data in a URL:
Path parameter โ part of the path itself, required:
/repos/torvalds/linux/issues
โ โ
owner repo
Query parameter โ after ?, usually optional:
/repos/torvalds/linux/issues?state=open&per_page=10
The API documentation always specifies which type is used for each parameter.
Summary
| Element | Example | Purpose |
|---|---|---|
| Scheme | https:// |
Protocol |
| Host | api.github.com |
Server address |
| Path | /user/repos |
Resource |
| Query parameters | ?sort=updated |
Filters and options |
Use params= in requests instead of building URLs manually โ it’s more reliable and more readable.
๐ฌ Comments (0)
No comments yet
Be the first to share your opinion about this article!