I am trying to upload images to imgur, and I found the way to do it below:
img = requests.post(
'https://api.imgur.com/3/upload.json',
headers = {'Authorization': 'Client-ID <my client-id>'},
data = {
'key': '<my secret key>',
'title': 'test'
'image': <path to image>
}
)
j = json.loads(img.text)
print j
Imgur API for image upload: https://api.imgur.com/endpoints/image#image-upload
This works fine, but I want to be able to upload the images as a user. Where do I put my username and password?
You'll need to authenticate your requests to imgur via oauth2. The account that is used to authenticate will be the account that does the uploads.
A full description of oauth is a bit beyond the scope of this answer, but in short, you're using the right http library in requests because it is often simpler than other approaches.
I like requests-oauthlib library which is recommended by requests. It works well with twitter's api too.
I should also note that imgur has a sample python app called imgur-python. Check out main.py for a bit more of a lead on things.
Related
I want to upload files to Slack using Slack API and Python. I tried to use webhooks but it didn't help me send the file. I am able to send messages only but not files. Is there a way to achieve uploading the file?
Finally, this worked for me.
Steps
Create a Slack app. If you are not the admin you need to request the same.
Add the permissions to read, write.
Get the Authorization token from oauth & permissions
Use the following snippet to upload the file.
url = "https://slack.com/api/files.upload"
headers = {
"Authorization":"Bearer xxxx", ----> this is the token you receive from oauth & permissions. It generally starts with xox
}
payload = { "channels":"channelXYZ"}
file_upload = {
"file":("./hello-world.txt",
open("./hello-world.txt", 'rb'), 'text/plain')
}
response = requests.post(url, headers=headers, files=file_upload, data=payload)
I'm trying to access Google API services through a headless Linux server using Oauth2. I read through all the answers on this post: How do I authorise an app (web or installed) without user intervention? but none of them showed how to use the refresh token to generate an access token in python. pinnoyyid had a javascript example (https://stackoverflow.com/a/19766913/15713034) that went something like this:
function get_access_token_using_saved_refresh_token() {
// from the oauth playgroundfunction get_access_token_using_saved_refresh_token() {
// from the oauth playground
const refresh_token = "1/0PvMAoF9GaJFqbNsLZQg-f9NXEljQclmRP4Gwfdo_0";
// from the API console
const client_id = "559798723558-amtjh114mvtpiqis80lkl3kdo4gfm5k.apps.googleusercontent.com";
// from the API console
const client_secret = "WnGC6KJ91H40mg6H9r1eF9L";
// from https://developers.google.com/identity/protocols/OAuth2WebServer#offline
const refresh_url = "https://www.googleapis.com/oauth2/v4/token";
let refresh_request = {
body:`grant_type=refresh_token&client_id=${encodeURIComponent(client_id)}&client_secret=${encodeURIComponent(client_secret)}& refresh_token=${encodeURIComponent(refresh_token)}`;,
method: "POST",
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
})
}
JavaScript isn't really my best language, but I could decipher they were sending a POST request to the google server. So I tried to recreate the request in Python with the requests package:
import requests
result = requests.post("https://www.googleapis.com/oauth2/v4/token", body={'grant_type':'refresh-token', 'client_id':client_id, 'client_secret':client_secret, 'refresh_token': refresh_token}, headers={'Content-Type': 'application/x-www-form-urlencoded'})
And when I look at result it shows it has a 200 status code (success) but when I try to examine the response, there's nothing easy to read and I can't parse the result in JSON to get the access token. The other approach I tried was to spin up a Flask server using Google's suggested code: https://developers.google.com/identity/protocols/oauth2/web-server#python_5 but that doesn't work either because when I try to return the credentials from one of the functions (object that contains the access code) that won't return JSON no matter what. I'd prefer the post request method since it is cleaner and uses less code. Thanks!
In Python, one approach is to use requests-oauthlib to perform the Backend Application Flow. This is useful when you don't have a front-end to redirect someone to, in order to approve fetching a token.
This website (https://community.atlassian.com/t5/Bitbucket-questions/Refresh-Tokens-using-Python-requests/qaq-p/1213162) says solution could be something like this:
import requests
auth = ("<consumer_id>", "<consumer_secret>")
params = {
"grant_type":"refresh_token",
"refresh_token":"<your_refresh_token_here>"
}
url = "https://www.googleapis.com/oauth2/v4/token"
ret = requests.post(url, auth=auth, data=params) #note data=params, not params=params
Since none of the solutions above worked, I had to finally just give up and use a service account.
I am new at stackoverflow and to programming with python and I am trying to get an emotion analyses for images from my hard disk by using the service of skybiometry.com. The example link of them is like: "http://api.skybiometry.com/fc/faces/detect.json?api_key=aa754b54b37&api_secret=4b3a4c6d4c&urls=http://theweeklyworld.com/wp-content/uploads/2014/08/child-happy-face1.jpg&attributes=all" and I want to do this in my python-script with my image. On their website https://skybiometry.com/documentation/ on point 4.13 they said that the request has to be formed as a MIME if I want to analyze images from my hard disk. I do not know how to handle this. In an other project of mine I have done the request like this
import requests
auth_headers = {
'api_key': api_key,
'api_secret': api_secret,
}
url = 'http://api.skybiometry.com/fc/faces/detect'
files = { 'source': open(path + ".jpg", 'rb')
}
data = { 'timeout': 60
}
response = requests.post(url, files=files, data=data, headers=auth_headers)
print (response.json())
Can anyone help me to adjust this request to make it work?
Thanks a lot!
You need to change api_key and api_secret for your own skybiometry credentials to use that python script.
Anyway, I prefer installing the api client skybiometry first for python and then use your python scripts. To install it you need to follow these steps:
git clone git#github.com:SkyBiometry/python-face-client.git
cd python-face-client
python setup.py build
python setup.py install
Then you can use the api-client using import with your skybiometry credentials, for example:
from face_client import FaceClient
client = FaceClient('API_KEY', 'API_SECRET')
Changing the API_KEY and API_SECRET for your own skybiometry credentials.
For more examples and how to use the api-client, you can watch this: https://github.com/SkyBiometry/python-face-client
Greetings.
I'm attempting to post an image to a Slack channel utilizing web hooks. This basic setup has allowed me to post text to the channel, but I've been unable to post the image. Here's my code:
def posting():
import requests
import json
url = 'https://webhook'
image = {'media': open('trial.jpg', 'rb')}
r = requests.post(url, files=image)
r.json
When I post the text, a web hook bot appears in the channel and posts it. Do I need some further authentication to post? Or is it a matter of Slack having their own API for uploading and wants me to go through that? Or something something bots don't have rights to post images?
I took a look at some other questions here, but they didn't appear to be using web hooks or bots, so I'm not sure if my issue is something involving those.
You can do this through the Slack API using their files.upload method: https://api.slack.com/methods/files.upload
You will need an API auth token for this to work properly. You can set up a testing token or follow the instructions to register your program to get a long term one: https://api.slack.com/web#basics
Also, 'media' doesn't seem to be the right json key to use for file uploads:
http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file
Here's an example using requests to send an image to a channel. Use '#username' if you want the image to go to a specific user. I've included the content type and header but it should work without them as well.
This will print the response from Slack.
import requests
def post_image(filename, token, channels):
f = {'file': (filename, open(filename, 'rb'), 'image/png', {'Expires':'0'})}
response = requests.post(url='https://slack.com/api/files.upload', data=
{'token': token, 'channels': channels, 'media': f},
headers={'Accept': 'application/json'}, files=f)
return response.text
print post_image(filename='path/to/file.png', token='xxxxx-xxxxxxxxx-xxxx',
channels ='#general')
I've reviewed the examples posted in the Square Connect API documentation and the examples on GitHub, however, I can't seem to adapt these examples to the guidance on uploading images: http://docs.connect.squareup.com/#post-image
Part of the challenge is working with the Content-Type: multipart/form-data which only the image upload requires so the documentation is non-existent (with the connect-api docs).
My ultimate question is, can Square please post an example of how to upload images? Most relevant would be an example that shows how to update multiple items with images versus just one item. Any help is appreciated.
Thanks for pointing out this gap in the documentation. The function below uses the Requests Python library to upload an image for an item (this library makes multipart/form-data requests significantly simpler). Note that you'll need to install Requests first if you haven't.
import requests
def upload_item_image(item_id, image_path, access_token):
endpoint_path = 'https://connect.squareup.com/v1/' + your location + '/items/' + item_id + '/image'
# Don't include a Content-Type header, because the Requests library adds its own
upload_request_headers = {'Authorization': 'Bearer ' + access_token,
'Accept': 'application/json'}
# Be sure to set the correct MIME type for the image
files = [('image_data', (image_path, open(image_path, 'rb'), "image/jpeg"))]
response = requests.post(endpoint_path, files=files, headers=upload_request_headers)
# Print the response body
print response.text
item_id is the ID of the item you're uploading an image for.
image_path is the relative path to the image you're uploading.
access_token is the access token for the merchant you're acting on behalf of.
It isn't possible to upload images for multiple items in a single request to this endpoint. Instead, send a separate request for each item.