Sign in with Google to keep private notes

HTTP protocol methods

Header format: <method> <request-target> <protocol>
(e.g. POST /users HTTP/1.1)

Request headers provide additional context to a request or add extra logic to how it should be treated by a server (e.g., conditional requests).

Representation headers are sent in a request if the message has a body, and they describe the original form of the message data and any encoding applied. This allows the recipient to understand how to reconstruct the resource as it was before it was transmitted over the network.

HTTP/2 versus HTTP/1

HTTP/2 was introduced to solve the head-of-line blocking issues present in HTTP/1.x by enabling multiplexing of requests.

HTTP/2 allows you to use a single TCP connection for multiple requests and responses at the same time. This is done by wrapping messages into a binary frame and sending the requests and responses in a numbered stream on a connection. Data and header frames are handled separately, which allows headers to be compressed via an algorithm called HPACK. Using the same TCP connection to handle multiple requests at the same time is called multiplexing.

GET and POST

Property GET POST
Request has body No Yes
Successful response has body Yes Yes
Safe Yes No
Idempotent Yes No
Cacheable Yes Only if freshness information is included
Allowed in HTML forms Yes Yes

GET

Example of a GET request

GET /contact HTTP/1.1
Host: example.com
User-Agent: curl/8.6.0
Accept: */*

which follows the format of

GET <request-target>["?"<query>] HTTP/1.1

With Python, you can see that we can just pass a dictionary in for the kv pairs for a GET request.

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('https://httpbin.org/get', params=payload)

Any dictionary key whose value is None will not be added to the URL’s query string.

You can also pass a list of values as a value to one of your keys

payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.get('https://httpbin.org/get', params=payload)
print(r.url)

Prints: "https://httpbin.org/get?key1=value1&key2=value2&key2=value3"

Use r.status_code or r.raise_for_status() to check if it succeeded (don't reply on r.json()).

POST

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post('https://httpbin.org/post', data=payload)

and you may sometimes need to leave it as a string as is

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload))

POSTs also come with body components where you can send shit tgt with the header

--boundary123
Content-Disposition: form-data; name="file"; filename="report.xls"
Content-Type: application/vnd.ms-excel

<raw bytes of the file>
--boundary123--

To format it you can

url = 'https://httpbin.org/post'
files = {'file': open('report.xls', 'rb')} #rb means read binary 
#or, to ad dmore details

files = {'file': 
('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})
}
#ion understand shit
#oh wait. file name      file contents     content type            extra headers (dict as usual)

and most servers ignore custom per-part headers anyway.

You can stream multiple files with something called requests-toolbelt. lol.

Cookie Cookie. Cookie Cookie. Cook Cook Cook Cook Cook Coo Coo

A cookie is a small piece of data a server asks the client to remember and send back on later requests. The server sets it with a response header:

Set-Cookie: session_id=abc123; Domain=example.com; Path=/; Secure

and on later requests to that site, the client sends:

Cookie: session_id=abc123

Yes the whole cookie is stored on the server and yes the client only needs to keep and send the vname and the value to get the utility. Kind of

RequestsCookieJar

Requests library can make everyones life easier when they try to use Cookies, using a class called RequestsCookieJar. It look like this:

for c in jar:
    print(c.name, c.value, c.domain, c.path, c.expires, c.secure)
#but it allows dict style name -> value accessing too. Here we can interact with it a different way
r = requests.get(url)
r.cookies['example_cookie_name']          # dict-style access
r.cookies.get('example_cookie_name')      # also works
r.cookies.items()                         # [(name, value), ...]
r.cookies.get_dict()                      # convert to a real dict (loses domain/path info)

You may be asking yourself what the point of the other fields are:

Domain: does the request’s host match the cookie’s domain?

  • If the server set no Domain, the cookie is host-only: sent only to that exact host (example.com, not api.example.com).
  • If the server set Domain=example.com, it’s sent to example.com and all its subdomains (api.example.com, shop.example.com).
  • It is never sent to unrelated sites (other.com).

Path: does the request’s path start with the cookie’s path?

  • Path=/ matches every path on the site.
  • Path=/account matches /account and /account/settings, but not / or /accounts.

State

A cookie jar can actually contain multiple cookies to keep track of multiple states. So thats also pretty cool.

jar = requests.cookies.RequestsCookieJar()
jar.set('tasty_cookie', 'yum',   domain='httpbin.org', path='/cookies')
jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')

requests.get('https://httpbin.org/cookies', cookies=jar)

PUT or PATCH

So now we're going to go to the server side of the situation and learn a bit more about FastAPI.

Earlier we mostly used Requests to interact with the Server. Of course there has to be code from the Server side to handle this, and thats what we see below:

from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel

app = FastAPI()
class Item(BaseModel):
    name: str | None = None
    description: str | None = None
    price: float | None = None
    tax: float = 10.5
    tags: list[str] = []


@app.get("/items/{item_id}", response_model=Item) #<- Item blueprint
async def read_item(item_id: str):
    return items[item_id]


@app.put("/items/{item_id}", response_model=Item) #<- Item blueprint
async def update_item(item_id: str, item: Item): #<- Item blueprint
    update_item_encoded = jsonable_encoder(item)
    items[item_id] = update_item_encoded
    return update_item_encoded

yeah

yeah and like also if you dont provide the specific param in your response e.g. you dont include "tax" then that like leads to the tax being auto populated. possibly overwriting old values

{
    "name": "Barz",
    "price": 3,
    "description": None,
}

// when you have...

items = {
    "foo": {"name": "Foo", "price": 50.2},
    "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
    "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}

It turns out that if you want to replace it gently then you should use the PATCH method.

@app.patch("/items/{item_id}")
async def update_item(item_id: str, item: Item) -> Item:
    stored_item_data = items[item_id]
    stored_item_model = Item(**stored_item_data)
    update_data = item.model_dump(exclude_unset=True)
    updated_item = stored_item_model.model_copy(update=update_data)
    items[item_id] = jsonable_encoder(updated_item)
    return updated_item

Using this, you can drop values which were defaulted. (They're tracked by pydantic. Thanks Pydantic)

item = Item(name="Bar2")
print(item.model_fields_set)   # {'name'}
print(item.tax)                # 10.5  (default, but pydantic notes they were never "set")

item2 = Item(name="Bar2", tax=10.5)
print(item2.model_fields_set)  # {'name', 'tax'}
print(item2.tax)               # 10.5  (same value, but now it counts as set)

Articles to read next