Request in Python
Request in Python
Requests - HTTP library for Python that allows to easily make HTTP requests to get information from
websites.
Example: r = requests.get('https://api.github.com/events')
Here,
2
Response Content
A response is received from the API after a request has been made. It will
have a header and response data. The response header consists of useful
metadata about the response, while the response data returns what was
requested.
print(r) >>>Response<200>
When this code example prints the response object to the console, it
returns the name of the object’s class and the status code the request
returned.
response.content() which returns the the raw bytes of the data payload
Binary data - unit can take on only Requests have built in JSON To get raw socket response from
two possible states, as 0 and 1. decoder server, you can access the
Response body can also be It’s used for transmitting data in response with r.raw as one of
accessed as bytes, for non-text web applications (e.g., sending the functions to get raw content.
requests:
some data from the server to Response.raw is a raw stream of
>>> r.content the client, so it can be displayed bytes - it does not transform the
on a web page, or vice versa response content
b'[{"repository":{"open_issues":0,"u
rl":"https://github.com/...
Eg: Create an image from binary Eg: >>> import requests >>> r = requests.get
data returned by a request: >>> r = requests.get ('https://api.github.com/events',
>>> from PIL import Image ('https://api.github.com/events') stream=True) >>> r.raw
>>> from io import BytesIO >>> r.json() <urllib3.response.HTTPResponse
>>> i = [{'repository': {'open_issues': 0, object at 0x101194810> >>>
Image.open(BytesIO(r.content)) 'url': 'https://github.com/... r.raw.read(10) 4
More Complicated POST Requests
>>> payload = {'key1': 'value1',
Send form-encoded data like an HTML form. 'key2': 'value2'}
Pass a dictionary to the data argument and dictionary of data will >>> r =
automatically be form-encoded requests.post("https://httpbin.or
The data argument can also have multiple values for each key. This can
g/post", data=payload)
be done by making data by either of the following: >>> print(r.text)
--------------------------------------
1. List of tuples payload_tuples = [('key1', 'value1'), ('key1', 'value2')] {
2. Dictionary with lists as values payload_dict = {'key1': ['value1', ...
'value2']} "form": {
"key2": "value2",
If non encoded data has to be auto encoded -> use JSON parameter "key1": "value1"
>>> payload = {'some': 'data'} },
...
>>> r = requests.post(url, json=payload) }
5
Response Headers and status codes
6
Cookies
7
Errors and Exceptions
In the event of a network problem (e.g. DNS failure, refused connection, etc) -> Requests raises
a ConnectionError exception.
8
THANK YOU