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!