Upload secure files to GitLab using requests python module

Question:

I’m trying to upload a secure file to my repository in GitLab.

While I am able to upload a secure file with curl, I encounter an error when using requests in Python.

my python code:

    r = requests.post("https://gitlab.com/api/v4/projects/10186699/secure_files",
                  headers={"PRIVATE-TOKEN": "glpat-TH7FM3nThKmHgOp"},
                  files={"file": open("/Users/me/Desktop/dev/web-server/utils/a.txt", "r"),
                         "name": "a.txt"}) 
    print(r.status_code,r.json())

Response:

400 {'error': 'name is invalid'}

The equivalent curl command I use that actually works:

curl --request POST --header  "PRIVATE-TOKEN: glpat-TH7FM3nThKmHgOp" https://gitlab.com/api/v4/projects/10186699/secure_files --form "name=a.txt" --form "file=@/Users/me/Desktop/dev/web-server/utils/a.txt"
Asked By: ADL

||

Answers:

The equivalent call will be

import requests

resp = requests.post(
    "https://gitlab.com/api/v4/projects/10186699/secure_files",
    headers={"PRIVATE-TOKEN": "glpat-TH7FM3nThKmHgOp"},
    files={"file": open("/Users/me/Desktop/dev/web-server/utils/a.txt", "rb")},
    data={"name": "a.txt"}
) 

print(resp.status_code,resp.json())

This is because the file= parameter is intended only for uploading files. On the other hand, name is your form data (you need to pass in the data= parameter).

It’s also recommended to open files in binary mode. (docs)

Answered By: Alexander Volkovsky