Python POST Request with an Image - python

I'm trying to request to my flask webserver with an image using python and just can't get it to work.
Using cURL it's simple:
curl -XPOST -F "file=#image.jpg" http://127.0.0.1:5001
But in python using my code:
import requests
with open("image.jpg", "rb") as a_file:
file_dict = {"image.jpg": a_file}
response = requests.post("http://127.0.0.1:5001", files=file_dict)
print(response.text)
print(response.status_code)
I simply get the HTML of the site returned and status 200. Not the JSON that returns using cURL (and is what I want returned).
Any help would be appreciated, Thanks.

you can use follow code
files = {'file': open('image.jpg', 'rb')}
r = requests.post('http://127.0.0.1:5001', files=files)
print(r.text)

Related

Routing an image through GroupMe's image service with Python

I'm using requests to make a POST request to GroupMe's image service that should return a URL of the hosted image that I can use to post to a GroupMe thread. The documentation mentions that I need my access token and the binary image data in the payload in order to do this.
Here is a very simple example of how my code to do this currently looks:
import requests
access_token = 'my_access_token'
img_path = 'picture_name.jpg'
img_service_url = 'https://image.groupme.com/pictures'
r = requests.post(img_service_url, files={'file': img_path})
EDIT:
I looked at the documentation and source for the groupy.api.endpoint module Groupy(https://groupy.readthedocs.io/en/v0.6.2/_modules/groupy/api/endpoint.html#Images) and updated my script (reflected above) to use the same requests function parameters, but to no avail. Now the code returns a 500.
This worked for me (avatar.jpeg is in the same folder as my testing.py code below)
# curl 'https://image.groupme.com/pictures'
# -X POST
# -H "X-Access-Token: $GM_TOKEN"
# -H "Content-Type: image/jpeg"
# --data-binary #AwesomePicture.jpg
import requests
data = open('./avatar.jpeg', 'rb').read()
res = requests.post(url='https://image.groupme.com/pictures',
data=data,
headers={'Content-Type': 'image/jpeg',
'X-Access-Token': 'ACCESS_TOKEN'})
print(res.content)
OUTPUT
b'{"payload":{"url":"https://i.groupme.com/100x100.jpeg.5b71f15633f6454ca6a3a6b3e267a3fb","picture_url":"https://i.groupme.com/100x100.jpeg.5b71f15633f6454ca6a3a6b3e267a3fb"}}\n'

post request with Python requests lib returning status 405

I am uploading a file to server using requests lib in Python. I read its documentation and some stackoverflow questions and implemented following code:
url = "http://example.com/file.csv"
id = "user-id"
password = "password"
headers = {'content-type': 'application/x-www-form-urlencoded'}
with open(file_path, 'rb') as f:
response = requests.post(url=url, files={'file':f}, auth=HTTPBasicAuth(username=id, password=password),headers=headers)
But this code is not working, response.status_code returning 405 and response.reason returning Method Not Allowed. When i upload file using curl command on terminal it works fine and file gets uploaded:
curl -u user-id:password -T file/path/on/local/machine/file.csv "http://example.com/file.csv"
Can someone please help here.
Related question here. In reality, curl --upload-file performs a PUT not a POST. If you want to mimic what curl does, you might want to try:
with open(file_path, 'rb') as f:
response = requests.put(url=url, files={'file':f}, auth=HTTPBasicAuth(username=id, password=password), headers=headers)

How to upload a pdf by sending a POST Request to an API

I have tried to upload a pdf by sending a POST Request to an API in R and in Python but I am not having a lot of success.
Here is my code in R
library(httr)
url <- "https://envoc-apply-api.azurewebsites.net/api/apply"
POST(url, body = upload_file("filename.pdf"))
The status I received is 500 when I want a status of 202
I have also tried with the exact path instead of just the filename but that comes up with a file does not exist error
My code in Python
import requests
url ='https://envoc-apply-api.azurewebsites.net/api/apply'
files = {'file': open('filename.pdf', 'rb')}
r = requests.post(url, files=files)
Error I received
FileNotFoundError: [Errno 2] No such file or directory: 'filename.pdf'
I have been trying to use these to guides as examples.
R https://cran.r-project.org/web/packages/httr/vignettes/quickstart.html
Python http://requests.readthedocs.io/en/latest/user/quickstart/
Please let me know if you need any more info.
Any help will be appreciated.
You need to specify a full path to the file:
import requests
url ='https://envoc-apply-api.azurewebsites.net/api/apply'
files = {'file': open('C:\Users\me\filename.pdf', 'rb')}
r = requests.post(url, files=files)
or something like that: otherwise it never finds filename.pdf when it tries to open it.

How to set media type with Python requests?

I am trying to reproduce this curl statement with Python requests:
curl -T data/Graph.obj -X POST localhost:8080
My Python code is the following:
files = {'Graph.obj': open('data/Graph.obj', 'rb')}
r = requests.post('http://localhost:8080', files=files)
The curl statement works fine. But for the Python code I get the error HTTP 415 Unsupported Media Type HTTP.
How do I set the media type properly? Or what else am I missing?
You can do something like that:
url = 'http://httpbin.org/post'
files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file

Sending JSON request with Python

I'm new to web services and am trying to send the following JSON based request using a python script:
http://myserver/emoncms2/api/post?apikey=xxxxxxxxxxxxx&json={power:290.4,temperature:19.4}
If I paste the above into a browser, it works as expected. However, I am struggling to send the request from Python. The following is what I am trying:
import json
import urllib2
data = {'temperature':'24.3'}
data_json = json.dumps(data)
host = "http://myserver/emoncms2/api/post"
req = urllib2.Request(host, 'GET', data_json, {'content-type': 'application/json'})
response_stream = urllib2.urlopen(req)
json_response = response_stream.read()
How do I add the apikey data into the request?
Thank you!
Instead of using urllib2, you can use requests. This new python lib is really well written and it's easier and more intuitive to use.
To send your json data you can use something like the following code:
import json
import requests
data = {'temperature':'24.3'}
data_json = json.dumps(data)
payload = {'json_payload': data_json, 'apikey': 'YOUR_API_KEY_HERE'}
r = requests.get('http://myserver/emoncms2/api/post', data=payload)
You can then inspect r to obtain an http status code, content, etc
Even though this doesnt exactly answer OPs question, it should be mentioned here that requests module has a json option that can be used like this:
import requests
requests.post(
'http://myserver/emoncms2/api/post?apikey=xxxxxxxxxxxxx',
json={"temperature": "24.3"}
)
which would be equivalent to the curl:
curl 'http://myserver/emoncms2/api/post?apikey=xxxxxxxxxxxxx' \
-H 'Content-Type: application/json' \
--data-binary '{"temperature":"24.3"}'
Maybe the problem is that json.dumps puts " and in the json you put in the url there are no "s.
For example:
data = {'temperature':'24.3'}
print json.dumps(data)
prints:
{"temperature": "24.3"}
and not:
{temperature: 24.3}
like you put in your url.
One way of solving this (which is trouble prone) is to do:
json.dumps(data).replace('"', '')

Categories

Resources