0

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"
1
  • I think you are passing name double time. One in open method called a.txt and another time in "name" : "a.txt". Take a look at requests.post documents for more information. Commented Dec 26, 2022 at 9:36

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.