Python Requests Module Github
Python requests module is a powerful library used for making HTTP requests in Python. It simplifies the process of sending HTTP requests and handling responses. In this post, we will focus on using the requests module for accessing data from Github API.
Installation
Before we start using the requests module, we need to install it. It can be installed using pip which is the package installer for Python.
$ pip install requests
Accessing Github API using Requests
Github provides an API that allows programmatic access to its resources. We can retrieve information about repositories, users, organizations, and more using Github API. To access the API, we need to make HTTP requests to Github's API endpoints.
Authentication
Before we can make requests to Github API, we need to authenticate ourselves. Github provides two ways of authentication: Basic authentication and OAuth2 token authentication. We will use OAuth2 token authentication for this example.
import requests
# Set the API endpoint
url = 'https://api.github.com/user'
# Set the authentication header
headers = {'Authorization': 'Token '}
# Make request to API
response = requests.get(url, headers=headers)
# Print response body
print(response.json())
The above code snippet retrieves information about the authenticated user. It sets the authentication header using the Github token and sends a GET request to the Github API endpoint.
HTTP Methods
The requests module supports all HTTP methods: GET, POST, PUT, DELETE, and more. Here is an example of making a POST request to create a new repository:
import requests
# Set the API endpoint
url = 'https://api.github.com/user/repos'
# Set the authentication header
headers = {'Authorization': 'Token '}
# Set the request body
data = {
"name": "my_new_repository",
"description": "This is my new repository"
}
# Make request to API
response = requests.post(url, headers=headers, json=data)
# Print response body
print(response.json())
The above code snippet creates a new repository using the Github API. It sets the authentication header using the Github token and sends a POST request to the Github API endpoint with the request body in JSON format.
Conclusion
The requests module is a powerful library for making HTTP requests in Python. It simplifies the process of sending HTTP requests and handling responses. We can use it to access Github API and retrieve information about repositories, users, organizations, and more.