Here's some code that might help you out.

Examples:

Example 1 (auth):

username = 'user'
token = 'token'

login = requests.get('https://api.github.com/search/repositories?q=github+api', auth=(username,token))

Example 2 (headers):

headers = {'Authorization': 'token ' + token}

login = requests.get('https://api.github.com/user', headers=headers)
print(login.json())

Example 3 (delete repo):

user = 'username'
repo = 'some_repo' # Delete this repo

headers = {'Authorization': 'token ' + token}

login = requests.delete('https://api.github.com/' + 'repos/' + user + '/' + repo, headers=headers)

Example 4 (create repo):

repo = 'some_repo'
description = 'Created with api'

payload = {'name': repo, 'description': description, 'auto_init': 'true'}

login = requests.post('https://api.github.com/' + 'user/repos', auth=(user,token), data=json.dumps(payload))

You might want to take a look at the following docs:

Requests Docs

Github API docs

I hope this helps.

Answer from user6927293 on Stack Overflow
🌐
The Python Code
thepythoncode.com › article › using-github-api-in-python
How to Use Github API in Python - The Python Code
Using Github Application Programming Interface v3 to search for repositories, users, making a commit, deleting a file, and more in Python using requests and PyGithub libraries.
Top answer
1 of 5
51

Here's some code that might help you out.

Examples:

Example 1 (auth):

username = 'user'
token = 'token'

login = requests.get('https://api.github.com/search/repositories?q=github+api', auth=(username,token))

Example 2 (headers):

headers = {'Authorization': 'token ' + token}

login = requests.get('https://api.github.com/user', headers=headers)
print(login.json())

Example 3 (delete repo):

user = 'username'
repo = 'some_repo' # Delete this repo

headers = {'Authorization': 'token ' + token}

login = requests.delete('https://api.github.com/' + 'repos/' + user + '/' + repo, headers=headers)

Example 4 (create repo):

repo = 'some_repo'
description = 'Created with api'

payload = {'name': repo, 'description': description, 'auto_init': 'true'}

login = requests.post('https://api.github.com/' + 'user/repos', auth=(user,token), data=json.dumps(payload))

You might want to take a look at the following docs:

Requests Docs

Github API docs

I hope this helps.

2 of 5
39

For one, I would recommend using a wrapper for the API. You're asking a lot of questions on here that could be simplified by finding a wrapper whose API you appreciate. There's a list of wrappers written in Python here.

As for your actually answering your question, the GitHub documentation is fairly clear that you need to send the Authorization header. Your call would actually look like this:

self.headers = {'Authorization': 'token %s' % self.api_token}
r = requests.post(url, headers=self.headers)

Since it seems like you're using requests and a class, might I be so bold as to make a recommendation? Let's say you're doing something like making a client for the API. You might have a class like so:

class GitHub(object):
    def __init__(self, **config_options):
        self.__dict__.update(**config_options)
        self.session = requests.Session()
        if hasattr(self, 'api_token'):
           self.session.headers['Authorization'] = 'token %s' % self.api_token
        elif hasattr(self, 'username') and hasattr(self, 'password'):
           self.session.auth = (self.username, self.password)

    def call_to_the_api(self, *args):
        # do stuff with args
        return self.session.post(url)

The Session object will take care of the authentication for you (either by the tokens or username and password combination).

Also, if you end up deciding to use github3.py for your API wrapper needs, there's a tag on here for it.

Discussions

How to access the github API via requests in python? - Stack Overflow
I am trying to access the github API via requests with python (Answers in similar questions here and here do not help). Using curl, I am able to get a list of recent commits for a project, e.g. cur... More on stackoverflow.com
🌐 stackoverflow.com
A Python script which can fetch the contents of a GitHub repo using it's URL
You definitely do not need any github APIs to do it, to be honest. 2 lines of shell script suffices. 1st line is the curl call 2nd line is the unzlip call. Also, if you do have git installed then git clone apparently magically woks. So op u/Lost_Championship698 what is the purpose of this script? Here is the script for you: curl "https://$REPO/archive/refs/heads/$BRANCH.zip" -o "./$REPO_$BRANCH.zip" More on reddit.com
🌐 r/developersIndia
10
2
August 3, 2024
PyGithub iterate over public repos, exceeding rate limit too fast
I tried to query the GitHub API manually using curl, and it seems that the subscriber count and fork count are not included in the info returned, so I assume PyGithub does an additional query to get this additional info. More on reddit.com
🌐 r/learnpython
2
2
October 24, 2019
PyGitHub - how to get ALL repos?

This is not the place to ask for support on a particular library, a better avenue might be the library's issues page or r/learnpython if all else fails.

That being said, the direct equivalent to

curl -H "Authorization: Token <token>" https://githubserver/api/v3/repositories?visibility=all

seems to be

ghe_instance = Github(base_url=GHE_API_URL, login_or_token=GHE_ACCESS_TOKEN)
ghe_instance.get_repos(visibility='all')

https://github.com/PyGithub/PyGithub/blob/master/github/MainClass.py#L297

More on reddit.com
🌐 r/Python
1
1
September 18, 2019
🌐
Martin Heinz
martinheinz.dev › blog › 25
All the Things You Can Do With GitHub API and Python | Martin Heinz | Personal Website & Blog
June 15, 2020 - Both snippets above use the same API endpoint to retrieve all open issues for specified repository. In both cases we start by taking GitHub token from environment variable. Next, in the example with using PyGitHub we use the token to create instance of GitHub class, which is then used to get repository and query its issues in open state. The result is paginated list of issues, of which we print the first page. In the example that uses raw HTTP request, we achieve the same result by building API URL from username and repository name and sending GET request to it containing state as body parameter and token as Authorization header.
🌐
GitHub
github.com › PyGithub › PyGithub
GitHub - PyGithub/PyGithub: Typed interactions with the GitHub API v3 · GitHub
This library enables you to manage GitHub resources such as repositories, user profiles, and organizations in your Python applications. ... from github import Github # Authentication is defined via github.Auth from github import Auth # using ...
Starred by 7.7K users
Forked by 1.9K users
Languages   Python 99.6% | Shell 0.4%
🌐
GitHub
github.com › luminati-io › python-requests
GitHub - luminati-io/python-requests: Python's 'requests' library: learn HTTP methods, parsing responses, proxy usage, timeouts, and more for efficient web scraping. · GitHub
With over 50k stars on GitHub and millions of daily downloads, Requests represents the most popular HTTP client in Python. Some of the key features offered by this library include a comprehensive API covering all HTTP methods, dealing with server replies, request customization, login mechanisms, handling secure certificates, and more.
Author   luminati-io
🌐
Apify
blog.apify.com › python-github-api
How to use the GitHub API in Python
July 30, 2024 - import requests base_url = "https://api.github.com" def update_repo_descr(access_token, username, repo_name, new_description): url = f"{base_url}/repos/{username}/{repo_name}" headers = { "Authorization": f"token {access_token}", } data = { "description": new_description } response = requests.patch(url, headers=headers, json=data) if response.status_code == 200: updated_repo_data = response.json() return updated_repo_data else: return None access_token = "YOUR ACCESS TOKEN" username = "GITHUB USERNAME" repo_name = "apify_testing" new_description = "This is an updated description using PATCH re
🌐
Medium
medium.com › analytics-vidhya › getting-started-with-github-api-dc7057e2834d
Getting Started with Github API. REST API v3 using Python | by Gaganpreet Kaur Kalsi | Analytics Vidhya | Medium
July 20, 2020 - In this article, learn how to use Github API to create, delete a repository; create an issue, comment, and close an issue and many more using python. Learn how to read API documentation and make GET, POST and DELETE requests. Also learn how to generate a token. Getting Started with Github API from ...
Find elsewhere
🌐
Requests
requests.readthedocs.io
Requests: HTTP for Humans™ — Requests 2.33.1 documentation
Requests is an elegant and simple HTTP library for Python, built for human beings. Behold, the power of Requests: >>> r = requests.get('https://api.github.com/user', auth=('user', 'pass')) >>> r.status_code 200 >>> r.headers['content-type'] 'application/json; charset=utf8' >>> r.encoding 'utf-8' ...
🌐
Medium
medium.com › @nutanbhogendrasharma › how-to-make-a-github-api-call-in-python-507ac6a3fcbb
How to Make a GitHub API Call in Python | by Nutan | Medium
July 8, 2023 - How to Make a GitHub API Call in Python In this blog, we will learn how to make a GitHub API call in Python using the requests module. After that we will visualize repository name vs stars. What is …
🌐
Merge.dev
merge.dev › blog › get-all-issues-github-api-python
How to get all issues with the GitHub API in Python
February 13, 2024 - The /fetch_issues endpoint makes a request to the GitHub Search endpoint to look up all issues of a given repo and return one hundred items per page. If you're handling a repo with a large number of issues, you need to take care of API pagination ...
🌐
TechGeekBuzz
techgeekbuzz.com › blog › how-to-use-github-api-in-python
How to Use GitHub API in Python? [A Step by Step Guide]
We will use the Python requests library to send HTTP requests to access the GitHub REST APIs that are present at https://api.github.com/ .
🌐
GitHub
github.com › psf › requests
GitHub - psf/requests: A simple, yet elegant, HTTP library. · GitHub
Requests officially supports Python 3.10+.
Starred by 53.9K users
Forked by 9.8K users
Languages   Python 99.3% | Makefile 0.7%
🌐
Stack Overflow
stackoverflow.com › questions › 64430181 › how-to-access-the-github-api-via-requests-in-python
How to access the github API via requests in python? - Stack Overflow
Also, even for public data, unauthenticated requests are limited to only 60/hour per IP ... No Authentication is required. The following works: url = "https://api.github.com/repos/rsapkf/42/commits" headers = {"Accept": "application/vnd.github.inertia-preview+json"} r = requests.get(url, headers=headers)
🌐
GitHub
github.com › topics › python-requests
python-requests · GitHub Topics · GitHub
An authentication handler for using Kerberos with Python Requests. ... Bypass 4xx HTTP response status codes and more. The tool is based on Python Requests, PycURL, and HTTP Client.
🌐
PyPI
pypi.org › project › PyGithub
PyGithub · PyPI
This library enables you to manage GitHub resources such as repositories, user profiles, and organizations in your Python applications. ... from github import Github # Authentication is defined via github.Auth from github import Auth # using ...
      » pip install PyGithub
    
Published   Mar 22, 2026
Version   2.9.0
🌐
GitHub
github.com › WilliamQLiu › python-examples › blob › master › requests › example_requests.py
python-examples/requests/example_requests.py at master · WilliamQLiu/python-examples
"User-Agent": "python-requests/2.5.3 CPython/2.7.9 Darwin/14.1.0" }, "json": null, "origin": "74.71.230.126", "url": "http://httpbin.org/post" } """ · · def pass_headers_in_request(): """ Add HTTP headers to a request by adding a dict to the 'headers' param · """ url = 'https://api.github.com/some/endpoint' payload = { 'some': 'data' } headers = { 'content-type': 'application/json' } r = requests.post(url, data=json.dumps(payload), headers=headers) print r ·
Author   WilliamQLiu
🌐
Reddit
reddit.com › r/developersindia › a python script which can fetch the contents of a github repo using it's url
r/developersIndia on Reddit: A Python script which can fetch the contents of a GitHub repo using it's URL
August 3, 2024 -

GitHub's API provides basic data about a repository and its contents but does not offer detailed contents of each file unless you specify it in the path while sending the request.

I was working on a project that required extracting code from public repositories using their URLs, and we couldn't find a reliable method to retrieve the repository contents in JSON format.

So i decided to make a script for it. When you run the script it will ask for a url and then it will return the file structure of that repo and the contents in each file. Planning to make it into a package for py and js.

🌐
iProyal
iproyal.com › blog › python-github-api
Mastering the Python GitHub API: A Practical Guide for Developers
December 22, 2025 - It is necessary to build solid error management structures within GitHub API interactions to handle network failures, authentication errors, resource-not-found errors , and rate limit errors. Python try-except blocks successfully manage exceptions that occur in code operations. Response.raise_for_status() from the requests library detects HTTP errors, including 401 Unauthorized and 404 Not Found cases.