Prepared Requests

Whenever you receive a Response object from an API call or a Session call, the request attribute is actually the PreparedRequest that was used. In some cases you may wish to do some extra work to the body or headers (or anything else really) before sending a request. The simple recipe for this is the following:

  1. from requests import Request, Session
  2. s = Session()
  3. req = Request('POST', url, data=data, headers=headers)
  4. prepped = req.prepare()
  5. # do something with prepped.body
  6. prepped.body = 'No, I want exactly this as the body.'
  7. # do something with prepped.headers
  8. del prepped.headers['Content-Type']
  9. resp = s.send(prepped,
  10. stream=stream,
  11. verify=verify,
  12. proxies=proxies,
  13. cert=cert,
  14. timeout=timeout
  15. )
  16. print(resp.status_code)

Since you are not doing anything special with the Request object, you prepare it immediately and modify the PreparedRequest object. You then send that with the other parameters you would have sent to requests.* or Session.*.

However, the above code will lose some of the advantages of having a Requests Session object. In particular, Session-level state such as cookies will not get applied to your request. To get a PreparedRequest with that state applied, replace the call to Request.prepare() with a call to Session.prepare_request(), like this:

  1. from requests import Request, Session
  2. s = Session()
  3. req = Request('GET', url, data=data, headers=headers)
  4. prepped = s.prepare_request(req)
  5. # do something with prepped.body
  6. prepped.body = 'Seriously, send exactly these bytes.'
  7. # do something with prepped.headers
  8. prepped.headers['Keep-Dead'] = 'parrot'
  9. resp = s.send(prepped,
  10. stream=stream,
  11. verify=verify,
  12. proxies=proxies,
  13. cert=cert,
  14. timeout=timeout
  15. )
  16. print(resp.status_code)