Start learning free

LESSON 5 OF 188 · BACKEND: HOW THE WEB WORKS

Send a Query String

Practice

A query string is the part of a URL after the ?. It carries options for the path as name=value pairs, joined with &. The server reads them and shapes its answer: /prices?max_price=5 asks the supplier for the products that cost 5 or less.

You don't have to glue the query string onto the address yourself. Give requests.get a dictionary with params=, and it builds the query string for you. response.url shows the address the request really went to:

response = requests.get(SUPPLIER + "/catalog", params={"page": 2})
print(response.url)   # http://127.0.0.1:8001/catalog?page=2

The supplier filters its list before it answers, so the products that cost more never leave the server. For /prices with max_price set to 5, your script must print:

URL: http://127.0.0.1:8001/prices?max_price=5
Mug costs 5
Notebook costs 3
Pen costs 1

Your task: ask for /prices with params={"max_price": 5}, print "URL:" and response.url, then print each product that came back: its name, "costs" and its price.


Assignment
Follow the Coding Tutorial to send the query string with params, print the URL requests built and print the products the supplier sent back.


Hint
params= goes inside the same requests.get(...), after the address and a comma. The answer is a list of products, so loop straight over response.json().


STEP 1 OF 4
    Ctrl + Enter to check