Python Master Course V2 — 096. API Query Parameters and Headers
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 09 — WEB AND API ENGINEERING · LESSON 096 / 200
API Query Parameters and Headers
Study time: 90–120 minutes. Prerequisites: HTTP, JSON, functions, exceptions and Lesson 95.
Video lesson
Video not yet available. This is a reserved space for a verified video URL/player.
Outcomes
Encode parameters and understand request metadata. You should also be able to identify security implications, test expected and error behavior, and explain your design choices.
Detailed concepts
Query parameters convey filtering, sorting and pagination; headers carry metadata such as content types and authorization. Never place secrets in URLs because URLs can be logged.
Professional API workflow: model the resource, define request and response schemas, validate inputs, enforce authorization, choose suitable status codes, set timeouts and resource limits, and test normal and failure scenarios. Treat all network data as untrusted. Avoid leaking credentials in logs, URLs or error responses.
Maintainability: separate transport code from business logic, document assumptions, use dependency injection for testable clients, and prefer bounded operations over unbounded retries or pagination loops.
Understand and apply: API Query Parameters and Headers
Encode values without changing their meaning
Query parameters describe filters, sorting and pagination on a resource. A space, ampersand or plus sign inside a value must be encoded so it is not mistaken for URL syntax. Build parameters as data and let urlencode serialize them. Manual string concatenation can split one search phrase into unintended parameters or corrupt Unicode text.
Repeated values need an explicit convention. Some APIs expect tag=python&tag=sql; others expect a single comma-separated value. urlencode with doseq=True supports repeated list values, but the client still must follow the server’s contract. A Python dictionary cannot preserve duplicate keys by itself, so use a sequence of key-value pairs when duplicates or their order are meaningful.
Python example
from urllib.parse import urlencode
from urllib.request import Request
def search_request(term, tags, page=1, limit=20):
if not isinstance(term, str) or not term.strip():
raise ValueError("search term required")
if type(page) is not int or page < 1:
raise ValueError("page must be a positive integer")
if type(limit) is not int or not 1 <= limit <= 100:
raise ValueError("limit must be between 1 and 100")
if not isinstance(tags, list) or any(not isinstance(t, str) or not t for t in tags):
raise ValueError("tags must be nonempty strings in a list")
query = urlencode({"q": term.strip(), "tag": tags, "page": page, "limit": limit}, doseq=True)
return Request("https://example.org/products?" + query,
headers={"Accept": "application/json", "User-Agent": "InventoryLesson/1.0"})
request = search_request("pen & paper", ["blue", "sale"], page=2, limit=10)
print(request.full_url)
print(request.get_header("Accept"))
from urllib.parse import parse_qs, urlsplit
assert parse_qs(urlsplit(request.full_url).query) == {"q": ["pen & paper"], "tag": ["blue", "sale"], "page": ["2"], "limit": ["10"]}
for term in ["a+b", "Café"]:
encoded = search_request(term, []).full_url
assert parse_qs(urlsplit(encoded).query)["q"] == [term]
for settings in [{"page": 0}, {"page": True}, {"limit": 101}]:
try:
search_request("pen", [], **settings)
except ValueError:
pass
else:
raise AssertionError("invalid pagination accepted")
Expected output
https://example.org/products?q=pen+%26+paper&tag=blue&tag=sale&page=2&limit=10
application/json
The plus signs represent spaces; %26 preserves the ampersand as part of q rather than a separator. Both tag values become separate parameters. The page and limit are checked before serialization, which avoids accepting True as a page number or sending a huge requested page size. This function constructs a request but does not send it.
Headers describe the exchange
Accept asks for a JSON response. Content-Type describes an outgoing body and is appropriate when sending JSON bytes in a POST or PUT. An ordinary bodyless GET does not need Content-Type merely because the response should be JSON. Authorization belongs in the approved authentication header rather than the query string; URLs often appear in logs, browser history and monitoring systems.
Do not confuse percent encoding with encryption or input validation. Anyone who can see the URL can decode its query parameters. Encoding makes values syntactically safe for that position; it does not make arbitrary destinations trustworthy or grant permission to access data. Build the base URL from controlled configuration and do not let a search term replace the host.
Pagination limits protect both client and server only if both enforce them. A client should also bound the number of pages it consumes and stop according to the API’s next-page contract. Repeated or circular page tokens must not create an endless loop. For the project, test spaces, ampersands, literal plus signs, non-ASCII text, repeated tags, page zero, boolean page and a limit above one hundred. Verify parsed parameter values as well as the exact encoded URL.
Progressive runnable example
Python 3.10+. Save as lesson96.py and run locally. The sample is deterministic and does not make external requests.
from urllib.parse import urlencode
query=urlencode({'search':'python basics','page':2})
print(query)
Expected output:
search=python+basics&page=2
Walkthrough
Trace the input value, the library operation and the output. Explain what the same concept would mean for a real HTTPS request. Change one input and predict the effect. For real services, check timeouts, response status, content type and JSON structure before trusting the response.
Additional validation example
def validate_page(page):
if isinstance(page,bool) or not isinstance(page,int) or page < 1:
raise ValueError("page must be a positive integer")
return page
assert validate_page(2)==2
print("Page accepted")
Expected: Page accepted. Validation prevents invalid pagination requests.
Guided real-world project
Design paginated search requests with validation and explicit response limits.
- Write a requirements specification and sample JSON schema.
- Separate transport, validation, domain logic and persistence layers.
- Implement the simplest successful request/response scenario.
- Handle malformed input, missing resources and authorization failures.
- Test pagination boundaries, timeouts or rate limits where applicable.
- Document setup, security assumptions and rollback procedures.
Acceptance criteria: predictable behavior, no exposed credentials, tests for at least three failure conditions and documented error responses. This project is assigned for implementation; it has not been independently deployed or tested.
Common mistakes and debugging
- Sending credentials through query parameters or printing them in logs.
- Retrying non-idempotent operations without safeguards.
- Ignoring response status, timeouts or malformed JSON.
- Using unchecked URLs from untrusted sources.
- Assuming client-side validation replaces server-side authorization.
Debug by reproducing the request with a safe mock, checking status and headers, inspecting sanitized payloads, and adding regression tests.
Practice with explained answers
Make a prediction before opening each answer. Then trace the example and explain the result in your own words.
Optional hint for question 1
Treat the ampersand inside a search phrase as data, then look at the separator syntax.
1. Why does the ampersand become %26?
A raw ampersand separates query parameters. Encoding preserves it as data inside the search phrase instead of creating an unintended second parameter.
2. What does doseq=True do for tags?
It emits one parameter per list member, such as tag=blue&tag=sale. This is correct only when the API supports that repeated-key convention.
3. Should a bodyless GET set Content-Type to request JSON?
Use Accept for the desired response format. Content-Type describes a body being sent, so it is not needed just to ask for JSON in a GET response.
4. Does percent encoding hide an API token in a URL?
No. It is reversible syntax encoding, not encryption. Secrets should not be placed in query strings.
5. Why does a page-size cap not prevent an infinite client loop?
The client might still request unlimited pages or repeat a token forever. Bound total page consumption and detect repeated pagination states too.
Mastery checkpoint
Reproduce the sample, explain the protocol implications, complete the project specification, and write at least three meaningful tests. Video and account-synchronized completion are not yet available.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.