I was able to run your code and find the error, this happens because you are passing the data
parameter in the POST request instead of json
.
Make the following changes:
import requests
from pprint import pprint
import os
GIT_TOKEN = os.getenv('GITHUB_TOKEN')
payload = {
'name': 'vbk_test',
'private': 'true'
}
headers = {
"Authorization": f"Bearer {GIT_TOKEN}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28"
}
r = requests.post(
'https://api.github.com/user/repos', json=payload, headers=headers
)
pprint(r.json())
I continued the investigation because I wanted to know more about it and then I found this explanation on this point in more detail in the python requests library.
So from what I could understand, if you use the data
parameter, you must pass a string in the exact format you want to send them to the server, and when using the data parameter you are responsible for performing the JSON-Encoded.
When using the json
parameter, passing the dict object this will automatically be converted to JSON format, we can say the most comfortable way depending on your needs, the good thing about it is that currently Github API v3 supports JSON-Encoded POST/PATCH and that they deal with very well with either data or json requests.
See more about it here:
The example above I shared a solution using the json parameter (which automatically converts to JSON format), now I share the solution using the data parameter, the parameter of your question.
You must import JSON library and serialize your payload data string.
import os
import requests
from pprint import pprint
import json
GIT_TOKEN = os.getenv('GITHUB_TOKEN')
payload = {
'name': 'vbk_test',
'private': 'true'
}
headers = {
"Authorization": f"Bearer {GIT_TOKEN}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28"
}
r = requests.post(
'https://api.github.com/user/repos', data=json.dumps(payload), headers=headers
)
pprint(r.json())
Export the environment variable and then run:
export GITHUB_TOKEN=<your-github-token>
Hope this helps.