1 min read

Python Requests Module

The requests library is the de facto standard for making HTTP requests in Python. It abstracts the complexities of making requests behind a simple API so that you can focus on interacting with services and consuming data in your application.

Installation

pip install requests

Making Requests

GET Request

import requests

response = requests.get('https://api.github.com/events')
print(response.status_code)
print(response.text)

POST Request

r = requests.post('https://httpbin.org/post', data={'key': 'value'})

JSON Response Content

There is a builtin JSON decoder, in case you're dealing with JSON data.

import requests

r = requests.get('https://api.github.com/events')
events = r.json()
print(events[0]['id'])

Custom Headers

If you need to add HTTP headers to a request, simply pass a dict to the headers parameter.

url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}

r = requests.get(url, headers=headers)

programming/python/python