Start learning free

LESSON 6 OF 188 · BACKEND: HOW THE WEB WORKS

Headers

Practice

A response is more than its body. Before the body come the headers: lines of Name: value about the body, like the writing on an envelope around a letter. In Python, response.headers works like a dictionary of them. The header Content-Type says what kind of body this is: text/html for a web page, application/json for JSON.

Requests carry headers too, and you can add your own: pass headers= and a dictionary of them. The Accept header tells the server which kind of answer you want. After the call, response.request.headers are the headers your request carried. For example, to send an Accept-Language header that asks for French, and check that it went out:

reply = requests.get(SUPPLIER + "/catalog", headers={"Accept-Language": "fr"})
print(reply.request.headers["Accept-Language"])

When you pass no headers=, requests sends Accept: */*, which means anything will do. Your script asks for two paths and prints what their headers say:

GET /                                    →  Content-Type: text/html; charset=utf-8
GET /prices  (Accept: application/json)  →  Content-Type: application/json
Body: Supplier API. Try /prices
Content-Type: text/html; charset=utf-8
Sent Accept: application/json
Got Content-Type: application/json

Your task: the starting code asks for the home page and prints its body. Print its Content-Type. Then ask for /prices with an Accept header for JSON, and print the Accept header that went out and the Content-Type that came back.


Assignment
Follow the Coding Tutorial to read the Content-Type of two answers and send an Accept header of your own.


Hint
response.headers are the headers that came back; response.request.headers are the ones that went out. Read both like a dictionary, with the header's name in square brackets.


STEP 1 OF 4
    Ctrl + Enter to check