Accessing Imgur API with Python 3.4.1 and Urllib3 - python

I am trying to wrap my head around the Imgur API. I have found some good examples of how to send the authorization header to Imgur, however they all use urllib2, and I apparently, using pyhton 3.4.1 can only use urllib3.
So I have tried a couple of things and none of them seem to be working.
from this post I tried using the basic_auth header:
http = urllib3.PoolManager()
header = urllib3.make_headers(basic_auth="Client-ID" + CLIENT_ID)
r = http.request('GET', 'https://api.imgur.com/3/gallery/r/pics', headers=header)
that gives me a 403 error.
from this post I tried this method instead:
http = urllib3.PoolManager()
header= {"Content-Type": "text", "Authorization": "Client-ID" + CLIENT_ID}
r = http.request('GET', 'https://api.imgur.com/3/gallery/r/pics', headers=header)
that also returns a 403.
Now however I have got a step closer by reading the urllib3 documents and tried sending the Authorization as a field instead.
http = urllib3.PoolManager()
r = http.request('GET', 'https://api.imgur.com/3/gallery/r/pics', fields={"Authorization": "Client-ID " + CLIENT_ID})
this however returns a 401.
so can some one help me to figure out basic anonymous interaction with the Imgur API using these, or other methods?

Per imgur's API documentation, you have to send the auth header as such:
Authorization: Client-ID YOUR_CLIENT_ID
In this line:
header = urllib3.make_headers(basic_auth="Client-ID" + CLIENT_ID)
you are sending it as:
Authorization: Client-IDYOUR_CLIENT_ID
You need a space between.

Related

Web API Requests Authentication

I am trying a get request using the following API info:
https://github.com/iblockin/pool_web_api_doc/blob/master/api_en.md
Can someone help me with what the headers should look like, or point out where I am messing up? I keep getting an unauthenticated response.
url = "https://api-prod.poolin.com/api/public/v1/subaccount"
r = requests.get(url, headers = {'authorization': 'accessToken tokenhere'})
Sorry in advance if this has been inevitably answered in 1000 other locations.
Severe noob here, trying to learn
use this
url = "https://api-prod.poolin.com/api/public/v1/subaccount"
r = requests.get(url, headers = {'authorization': 'Bearer tokenhere'})
As mentioned here accessToken should be passed in the headeras
{'authorization':'Bearer TOKEN'} # TOKEN is replaced with the token value to be transmitted
So correct your code accordingly.

GET requests to Zendesk API fail using Python 3.x with the HTTP code 401 Unauthorised

I'm simply testing out the capabilities of Zendesk API with the intention of creating a ticket-based Slack application but I cannot seem to get past the simple act of authenticating myself.
I am using a token for authentication and the requests library as instructed on Zendesk's help desk but I still seem to be getting the same
Status: 401 Problem with the request. Exiting.
error message.
I currently have two versions of a Python3 code that have the same output each time.
Passing the Authorization header
import requests
import base64
# Set the request parameters
url = 'https://domain.zendesk.com/api/v2/tickets.json'
user = 'email'
pwd = 'token'
# Create the basic auth header
auth = user + '/token:' + pwd
auth = auth.encode("utf-8")
auth = base64.b64encode(auth)
auth = auth.decode("utf-8")
headers = {'Authorization': 'Basic ' + auth}
# Do the HTTP get request
response = requests.get(url, headers=headers)
# Check for HTTP codes other than 200
if response.status_code != 200:
print('Status:', response.status_code, 'Problem with the request. Exiting.')
exit()
# Decode the JSON response into a dictionary and use the data
data = response.json()
print(data.text)
Using auth tuple in the requests.get function
import requests
# Set the request parameters
url = 'https://domain.zendesk.com/api/v2/tickets.json'
user = 'email' + '/token'
pwd = 'token'
# Do the HTTP get request
response = requests.get(url, auth=(user, pwd))
# Check for HTTP codes other than 200
if response.status_code != 200:
print('Status:', response.status_code, 'Problem with the request. Exiting.')
exit()
# Decode the JSON response into a dictionary and use the data
data = response.json()
print(data.text)
I have also tried cURL which seems to be working without any hiccups. My guess is that it has something to do with how requests library is coded, however, I could not seem to find the answer anywhere.
Any help would be much appreciated.
According to the docs you need to enable password and email as auth
https://developer.zendesk.com/documentation/ticketing/getting-started/zendesk-api-quick-start/#preparation

Python request gives 415 error while post data

I am getting 415 error while posting data to server. This is my code how can i solve this problem. Thanks in advance!
import requests
import json
from requests.auth import HTTPBasicAuth
#headers = {'content-type':'application/javascript'}
#headers={'content-type':'application/json', 'Accept':'application/json'}
url = 'http://IPadress/kaaAdmin/rest/api/sendNotification'
data = {"name": "Value"}
r = requests.post(url, auth=HTTPBasicAuth('shany.ka', 'shanky1213'),json=data)
print(r.status_code)
According to MDN Web Docs,
The HTTP 415 Unsupported Media Type client error response code
indicates that the server refuses to accept the request because the
payload format is in an unsupported format.
The format problem might be due to the request's indicated
Content-Type or Content-Encoding, or as a result of inspecting the
data directly.
In your case, I think you've missed the headers.
Uncommenting
headers={
'Content-type':'application/json',
'Accept':'application/json'
}
and including headers in your POST request:
r = requests.post(
url,
auth=HTTPBasicAuth('shany.ka', 'shanky1213'),
json=data,
headers=headers
)
should do the trick
import requests
import json
from requests.auth import HTTPBasicAuth
headers = {
'Content-type':'application/json',
'Accept':'application/json'
}
url = 'http://IPadress/kaaAdmin/rest/api/sendNotification'
data = {"name": "Value"}
r = requests.post(
url,
auth=HTTPBasicAuth('shany.ka', 'shanky1213'),
json=data,
headers=headers
)
print(r.status_code)
As a workaround, try hitting your api using Postman. When you can successfully hit the api in postman, generate python code in postman (button is present in the top right corner). You can copy the code in your python project.
Another possible cause is using requests.post when you should be using requests.get or vice versa. I doubt that this is a common problem, but in my case a server that was happy to accept an HTTP GET for a search rejects it with a 415 when HTTP POST is used instead. (Yet another site required that a search be requested using HTTP POST. It was reusing that code that caused my problem.)

Is this a Post request issue or an SSL verification issue

I'm trying to use a certain company's (not yet public) API. In their documentation they lay out the format of the Token request. Here's a copy of the documentation for a Token request:
POST
https://***.****.com/auth/realms/****/protocol/openid-connec
t/token
Headers:
Content-Type: application/x-www-form-urlencoded
Authorization: Basic {base64-encoded-key-and-secret}
Body: grant_type:client_credentials
The authorization key was given to me by them and is of the form 'Basic a3RhdmlfdG...'
I'm trying to write a Post request in python and I'm having issues and I'm not sure if it's my fault or their developers fault. Here's my code:
url = 'https://***.****.com/auth/realms/****/protocol/openid-connect/token'
headers = {'Content-Type':'application/x-www-urlencoded', 'Authorization':'Basic a3RhdmlfdG...'}
body = {'grant_type':'client_credentials'}
response = requests.post(url = url, data = json.dumps(body), headers = headers)
print response
At the line where response = ...I'm getting an SSL: CERTIFICATE_VERIFY_FAILED error. I've also tried changing the values in the headers to random values and I get the same error. I can think of three possibilities, either
I'm making the Post request incorrectly
There is a problem with the API
I'm missing a certificate which I have to send with the Post request
Is it one of these issues or is it something else?
They are probably using a self signed cert. You can bypass the verify check by adding 'verify=False'. I would remove that before going to production. It is important that SSL certs are valid.
response = requests.post(url = url, data = json.dumps(body), headers = headers, veryify=False)

Post request using Python urllib

I'm making a request to an api using python3 urllib. This is my code,
headers = {}
headers['Content-Type']='application/x-www-form-urlencoded; charset=UTF-8'
#headers['X-Csrf-Token']= {'mode: cors'}
req = urllib.request.Request(url=URL, headers=headers, method='POST')
res = urllib.request.urlopen(req)
print(res.read())
I get the following response,
urllib.error.HTTPError: HTTP Error 415: Unsupported Media Type
The API endpoint is working fine and I've tested it with Postman. This is the equivalent javascript code which gets the job done,
return fetch(url, { credentials : 'include', method: 'post'})
So I'm assuming I've to find a way to add credentials to the header. Can I do a credentials include parallel in Python or do I have to fetch the specific cookie and set it in the request. Any help appreciated.
The error 415 indicates an issue with 'Content-type'.
'application/x-www-form-urlencoded' does not have any parameters.
https://www.w3.org/TR/html5/iana.html#application/x-www-form-urlencoded
Regarding fetch()'s "credentials", you would need the ability to maintain a session (sending cookies as required).
It is much easier with the requests library's Session
http://docs.python-requests.org/en/master/user/advanced/#session-objects

Categories