SeaDude
SeaDude

Reputation: 4415

Python + Github REST API: Problems with the Update File Contents request

I'm getting a Status 400 from the Update File Contents Github API even though 400 isn't on the list of possible HTTP response statuses!

My problem is that the content key needs to be base64 encoded. But when I convert the content to base64, the API responds with "Problems parsing JSON" error.

Feels like it has something to do with the f strings. If I remove them and use the variable names, the request fails with the same error.

How do I successfully submit this response?


def convert_to_base64(md_payload):
    encoded_payload = base64.b64encode(md_payload.encode('utf-8'))
    return encoded_payload

def log_todo(username, repo_name, filename, api_key, sha, encoded_payload):
    response= requests.put(
        f'https://api.github.com/repos/{username}/{repo_name}/contents/{filename}',
        headers = {
            'Accept': 'application/vnd.github+json',
            'Authorization': f'Bearer {api_key}'
        },
        data = {
            "sha": f'{sha}',
            "message": "TEST",
            "committer": {
                "name": "TEST",
                "email": "[email protected]"
            },
            "content": f'{encoded_payload}'
        }
    )
    logging.error(f'##### Was TODO Logged in VCS?: {response.text}')
    return response.status_code

Results: There is nothing about this message nor the status 400 on the doc_url

{
    "message":"Problems parsing JSON",
    "documentation_url":"https://docs.github.com/rest/reference/repos#create-or-update-file-contents"
}

400

Upvotes: 1

Views: 332

Answers (1)

SeaDude
SeaDude

Reputation: 4415

I figured it out:

  1. Changed convert_to_base64 function to:
    • I have no idea why one has to encode to base64 then decode it, but this worked
def convert_to_base64(md_payload):
    encoded_payload = base64.b64encode(md_payload.encode('utf-8'))
    encoded_payload = encoded_payload.decode('utf-8')
    return encoded_payload
  1. Changed the data parameter to json
def log_todo(username, repo_name, filename, api_key, sha, encoded_payload):
    response= requests.put(
        f'https://api.github.com/repos/{username}/{repo_name}/contents/{filename}',
        headers = {
            'Accept': 'application/vnd.github+json',
            'Authorization': f'Bearer {api_key}'
        },
        json = {                       #<--This is all I changed
            "sha": f'{sha}',
            "message": "TEST",
            "committer": {
                "name": "TEST",
                "email": "[email protected]"
            },
            "content": f'{encoded_payload}'
        }
    )
    logging.error(f'##### Was TODO Logged in VCS?: {response.text}')
    return response.status_code

Upvotes: 1

Related Questions