I am trying to fetch a pdf stream through python requests from flipkart.
But on running label.status_code i am getting 415.
My code:
class FlipkartAPI:
def __init__(self, token):
self.token = token
self.session = self.get_session()
def get_session(self):
session = requests.Session()
session.headers.update({'Authorization': 'Bearer %s' % self.token,
'Content-type': 'application/json',})
return session
def fetch_labels(self, orderItemIds):
self.session.headers.update({'Content-type':'application/octet-stream'})
url = "https://api.flipkart.net/sellers/orders/labels"
payload = {'orderItemId':','.join(orderItemIds)}
return self.session.get(url, params=payload, stream=True)
Function call:
fk = FlipkartAPI(token)
label = fk.fetch_labels(oiids)
print label.status_code
print label.url
print label.content
I get:
415
https://api.flipkart.net/sellers/orders/labels?orderItemId=230005995
The link for documentation is: Documentation
I searched on internet and it says the error is for unsupported media type.
So what am i doing wrong?
Don't set a Content-Type header, you are sending a GET request, which has no body so has no content to set a type for.
Instead, set an Accept header, as detailed in the documentation. Do not set that header for the whole session, just for this request:
def fetch_labels(self, orderItemIds):
url = "https://api.flipkart.net/sellers/orders/labels"
headers = {'Accept': 'application/octet-stream'}
payload = {'orderItemId':','.join(orderItemIds)}
return self.session.get(url, params=payload, headers=headers, stream=True)
Related
I have the below requests for GET & POST and the GET's work fine and the post shows a 200 response but when i check the external program it has not received any data from the post.
import requests
import json
class BearerAuth(requests.auth.AuthBase):
def __init__(self, token):
self.token = token
def __call__(self, r):
r.headers["authorization"] = "Bearer " + self.token
return r
class BearerAuth2(requests.auth.AuthBase):
def __init__(self, token):
self.token = token
def __call__(self, s):
s.headers["authorization"] = "api " + self.token
return s
headers={'content-type': 'application/json'}
response = requests.get('https://api', auth=BearerAuth('123'))
response2 = requests.get('https://api2', auth=BearerAuth('123'))
splunktok = requests.post('https://http-inputs', data={response, respons2}, headers=headers, auth=BearerAuth2('456'))
print(response.json(), response2.json())
What i want to do is get all the response body data from response & response 2 and use it in the POST to my external program. im not sure if i need to store the response as raw in variables first?
You are sending the requests.Response objects as a set:
data={response, respons2}
Assuming you intend to send the JSON responses, you can do something like:
data={**response.json(), **respons2.json()}
Ive worked this out. I added the below
after the first request i add
payload=response.json()
and then on the post i added
data=json.dumps(payload)
Below is my code to your view:
import warnings
import contextlib
import json
import requests
from urllib3.exceptions import InsecureRequestWarning
old_merge_environment_settings = requests.Session.merge_environment_settings
#contextlib.contextmanager
def no_ssl_verification():
opened_adapters = set()
def merge_environment_settings(self, url, proxies, stream, verify, cert):
# Verification happens only once per connection so we need to close
# all the opened adapters once we're done. Otherwise, the effects of
# verify=False persist beyond the end of this context manager.
opened_adapters.add(self.get_adapter(url))
settings = old_merge_environment_settings(self, url, proxies, stream, verify, cert)
settings['verify'] = False
return settings
requests.Session.merge_environment_settings = merge_environment_settings
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore', InsecureRequestWarning)
yield
finally:
requests.Session.merge_environment_settings = old_merge_environment_settings
for adapter in opened_adapters:
try:
adapter.close()
except:
pass
with no_ssl_verification():
##350014,166545
payload = {'key1': '350014', 'key2': '166545'}
resp = requests.get('https://rhconnect.marcopolo.com.br/api/workers/data_employee/company/1/badge/params', params=payload, verify=False, headers={'Authorization': 'Token +++++private++++', 'content-type': 'application/json'})
print(resp.status_code)
print(resp.status_code)
j = resp.json()
##print(j)
jprint(resp.json())
how can I do a while or a for to send a list of personal id numbers and get a JSON result to witch one?
I tried pasting some parametres but it does not work, produce some errors...
I got this follow error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
if i put:
resp = requests.get('https://rhconnect.marcopolo.com.br/api/workers/data_employee/company/1/badge/350014',
with a single number, it works.
here the follow json:
200
[
{
"DT_INI_VIG_invalidez": null,
"DT_fim_VIG_invalidez": null,
"MODULO": "APOIO",
"chapa": 350014,
}
]
You have to add number to url manually
"https://rhconnect.marcopolo.com.br/api/workers/data_employee/company/1/badge/" + str(params)
or
"https://rhconnect.marcopolo.com.br/api/workers/data_employee/company/1/badge/{}".format(params)
or using f-string in Python 3.6+
f"https://rhconnect.marcopolo.com.br/api/workers/data_employee/company/1/badge/{params}"
Using params=params will not add numer to url this way but ?key1=350014&key2=166545
You can see url used by request using
print(resp.request.url)
Now you can run in loop
all_results = []
for number in [350014, 166545]:
url = 'https://rhconnect.marcopolo.com.br/api/workers/data_employee/company/1/badge/{}'.format(number)
resp = requests.get(url, verify=False, headers={'Authorization': 'Token +++++private++++', 'content-type': 'application/json'})
#print(resp.request.url)
print(resp.status_code)
print(resp.json())
# keep result on list
all_results.append(resp.json())
BTW: If you get error then you should check what you get
print(resp.text)
Maybe you get HTML with information or warning
So I have this code that send API request to upload a file to a server, after searching the web I came up with something like that where 'payload' is additional params I need to send and 'files' is a path to the file I want to upload :
def sendAPIRequest2(self, env, object, method, params, files):
apiPath = "/api/secure/jsonws"
headers = {'content-type': 'multipart/form-data'}
url = env + apiPath + object
payload = {
"method": method,
"params": params,
"jsonrpc": "2.0"
}
data = json.dumps(payload)
myFile = {'file': open(files,'rb')}
try:
r = requests.post(url, files=myFile, data=data, headers=headers,
auth=HTTPBasicAuth(self.user, self.password), verify=False)
print r.text
resjson = json.loads(r.text)
except:
print "no Valid JSON has returned from"+object+" API"
sys.exit(1)
return resjson
I get:
ValueError: Data must not be a string.
What am I doing wrong?
I am trying to post a HTTP request. I have managed to get the code to work but I am struggling returning some of the result.
The result looks like this
{
"requestId" : "8317cgs1e1-36hd42-43h6be-br34r2-c70a6ege3fs5sbh",
"numberOfRequests" : 1893
}
I am trying to get the requestId but I keep getting the error Response' object is not subscriptable
import json
import requests
workingFile = 'D:\\test.json'
with open(workingFile, 'r') as fh:
data = json.load(fh)
url = 'http://jsontest'
username = 'user'
password = 'password123'
requestpost = requests.post(url, json=data, auth=(username, password))
print(requestpost["requestId"])
The response object contains much more information than just the payload. To get the JSON data returned by the POST request, you'll have to access response.json() as described in the example:
requestpost = requests.post(url, json=data, auth=(username, password))
response_data = requestpost.json()
print(response_data["requestId"])
You should convert your response to a dict:
requestpost = requests.post(url, json=data, auth=(username, password))
res = requestpost.json()
print(res["requestId"])
the response is not readable so you need to convert that into a readable format,
I was using python http.client
conn = http.client.HTTPConnection('localhost', 5000)
payload = json.dumps({'username': "username", 'password': "password"})
headers = {'Content-Type': 'application/json'}
conn.request('POST', '/api/user/register', payload, headers)
response = conn.getresponse()
print("JSON - ", response.read())
and for request, you can see the answers above
sometimes you have to use json.loads() function to convert the appropriate format.
I am learning Python and I am trying to create a playlist using the Spotify web api but get a http 400 error: Error parsing json. I guess it has to do with an incorrect variable type in the token but I am having a really hard time debugging it as I can't figure out a way to see the post request in raw format.
Posting through the API requires authorizing and this is the script I've created for that:
import requests
import base64
requests.packages.urllib3.disable_warnings()
client_id = 'ID'
client_secret = 'SECRET'
redirect_uri = 'http://spotify.com/'
scope = 'playlist-modify-private playlist-read-private'
def request_token():
# 1. Your application requests authorization
auth_url = 'https://accounts.spotify.com/authorize'
payload = {'client_id': client_id, 'response_type':'code','redirect_uri':redirect_uri}
auth = requests.get(auth_url,params = payload)
print '\nPlease go to this url to authorize ', auth.url
# 2. The user is asked to authorize access within the scopes
# 3. The user is redirected back to your specified URI
resp_url = raw_input('\nThen please copy-paste the url you where redirected to: ')
resp_code= resp_url.split("?code=")[1].split("&")[0]
# 4. Your application requests refresh and access tokens
token_url = 'https://accounts.spotify.com/api/token'
payload = {'redirect_uri': redirect_uri,'code': resp_code, 'grant_type': 'authorization_code','scope':scope}
auth_header = base64.b64encode(client_id + ':' + client_secret)
headers = {'Authorization': 'Basic %s' % auth_header}
req = requests.post(token_url, data=payload, headers=headers, verify=True)
response = req.json()
return response
This is the function actually trying to create the playlist using the authorization token (import authorizer is the function above):
import requests
import authorizer
def create_playlist(username, list_name):
token = authorizer.request_token()
access_token = token['access_token']
auth_header = {'Authorization': 'Bearer {token}'.format(token=access_token), 'Content-Type': 'application/json'}
api_url = 'https://api.spotify.com/v1/users/%s/playlists' % username
payload = {'name': list_name, 'public': 'false'}
r = requests.post(api_url, params=payload, headers=auth_header)
But whatever I try it only leads to a 400 error. Can anyone please point out my error here?
Solved by adding a json.dumps for the input: json.dumps(payload) and changing the payload to be 'data' and not 'params' in the request.
So the new functioning request equals:
r = requests.post(api_url, data=json.dumps(payload), headers=auth_header)