0

Can you please help me convert the following CURL command into a command for Python's requests library?

curl -F pdb_file[pathvar]=@/path/myfile.pdb -X POST https://proteins.plus/api/pdb_files_rest -H "Accept: application/json"

I've tried many things, like this:

import requests
file = open("3w32.pdb", "rb")
url = "https://proteins.plus/api/pdb_files_rest"
response = requests.post(url, data=file)
response.json()

or this:

import requests
file = open("3w32.pdb", "rb")
url = "https://proteins.plus/api/pdb_files_rest"
response = requests.post(url, data={"pdb_file[pathvar]": file}, json={"Accept": "application/json"})
response.json()

but I can't make it work. I either get an error from the server, or a JSONDecodeError in Python.

Qunatized
  • 197
  • 1
  • 9
  • import requests file = open("3w32.pdb", "rb") url = "https://proteins.plus/api/pdb_files_rest" response = requests.post(test_url, data=file) response.json() In this change test_url to url and are you sure you want to read the file in binary mode ? with "rb" option ?? – Pratap Alok Raj May 21 '21 at 10:33
  • Does this answer your question? [python requests file upload](https://stackoverflow.com/questions/22567306/python-requests-file-upload) – Pratap Alok Raj May 21 '21 at 10:34
  • @AlokRaj oh sorry I had pasted it wrong, but I'm executing it the way you said. I've updated the code in the question. – Qunatized May 21 '21 at 10:37
  • Wrote an answer, please let me know if that works for you :) – Pratap Alok Raj May 21 '21 at 11:23

3 Answers3

0

Try this answer https://stackoverflow.com/a/22567429/4252013 Instead of using "data" argument try with "file"

AnD
  • 156
  • 5
0

The problem in your code is that you have only opened the file and passed the pointer. you can pass the file contents by having file.read() in place.

Please refer this block of code:

import requests
file = open("3w32.pdb", "rb")
url = "https://proteins.plus/api/pdb_files_rest"
response = requests.post(url, data=file.read())
response.json()
halfer
  • 19,824
  • 17
  • 99
  • 186
Pratap Alok Raj
  • 1,098
  • 10
  • 19
  • Thank you, but that did not solve the issue. I'm still getting an error from the server: {'status_code': 'bad_request', 'message': 'Invalid number of parameters or incorrect parameter name'} – Qunatized May 21 '21 at 12:45
0

Ok, I managed to solve it at last. The problem was that the 'pdb_file[pathvar]' part in the curl command should've been added to the request, like this:

import requests
file = open("3w32.pdb", "rb")
url = "https://proteins.plus/api/pdb_files_rest"
response = requests.post(url, files={'pdb_file[pathvar]':file})
response.json()

Now it works!

Qunatized
  • 197
  • 1
  • 9