I have been trying to use requests to pull json data with client id and api key, but it won't work.
Here is the info I received from IT:
Request:
curl --location --request GET 'https://api.abc.com/def' \
--header 'clientid: testuser' \
--header 'Accept: application/json' \
--header 'apikey: testapikey1234' \
--header 'dc_session: UUID' \
--header 'dc_transaction_id: UUID'
I wrote the following code in python
import requests
import json
url = 'https://api.abc.com/def'
headers = {'Accept': 'application/json', 'clientid': 'testuser', 'apikey': 'testapikey1234', 'dc_session': 'UUID', 'dc_transaction_id': 'UUID'}
response = requests.get(url, verify = False, headers = headers)
print(response.status_code)
print(response.json())
Unfortunately the code returns 401 status code, with the error message:
{'error': {'type': 'INVALID_CLIENT_IDENTIFIER', 'message': 'Unauthorized. Missing or invalid clientID.'}}
Does anyone have any suggestions?
Related
I have API and I need to send a .csv file using cURL in python. I do not know how to write this command on python.
curl --location --request POST 'http://**************' \
--header 'Accept: application/json' \
--header 'API-AUTH-TOKEN: **************' \
--form 'list=#"/C:/Users/1288956/Downloads/ozon_search_query_test.csv"'
means I can't show it
R.J. Adriaansen gave me a good answer: curlconverter.com
import requests
headers = {
'Accept': 'application/json',
'API-AUTH-TOKEN': '**************',
}
files = {
'list': ('"/C:/Users/1288956/Downloads/ozon_search_query_test.csv"', open('"/C:/Users/1288956/Downloads/ozon_search_query_test.csv"', 'rb')),
}
response = requests.post('http:///**************', headers=headers, files=files)
I can access JWT secured Restful API using curl command as follows
#Get the access Token in a variable ID
export ID=`curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ "password": "admin", "rememberMe": true, "username": "admin" }' 'http://localhost:8080/api/authenticate' | jq -r .id_token`
#Use this token to access endpoint
curl 'http://localhost:8080/api/downloads' --header 'Content-Type: application/json' --header 'Accept: application/json' --header "Authorization: Bearer $ID"
My python script for authentication part and get bearer token is as follows:
import requests
LOGIN_URL = "http://localhost:8080/api/authenticate"
ENDPOINT_URL = 'http://localhost:8080/api/downloads'
PARAMS = {'password': 'admin','rememberMe': True, 'username': 'admin' }
r1 = requests.post(LOGIN_URL, data =PARAMS, headers={"Content-Type": "application/json","Accept": "application/json"})
print(r1)
When i am trying to do the same through python script,Authentication request fails with message <Response [400]>
Help needed !
You are passing a dictionary where you should be passing JSON.
Try using json not data and pass the dictionary:
import requests
LOGIN_URL = "https://httpbin.org/post"
PARAMS = {'password': 'admin','rememberMe': True, 'username': 'admin' }
r1 = requests.post(LOGIN_URL, json=PARAMS, headers={"Content-Type": "application/json","Accept": "application/json"})
print(r1.text)
or pass a string and use data:
import requests
LOGIN_URL = "https://httpbin.org/post"
PARAMS = '{"password": "admin", "rememberMe": true, "username": "admin"}'
r1 = requests.post(LOGIN_URL, data=PARAMS, headers={"Content-Type": "application/json", "Accept": "application/json"})
print(r1.text)
So I wrote this script in curl to generate a token
token=$(curl -s -H "Accept: application/json" -H "Content-Type: application/json" --data '{"identifier": "...", "password": "..."}' "$HOST:$PORT/login" | ggrep -Po '"token":"(\K[^"]+)')
which works fine. However with the simplicity of Python 3 I'd like to perform the same task using requests. As I understand running
import requests, json
http = '...'
head = {'accept': 'application/json', 'Content-Type':'application/json'}
data = { 'username' : '...', 'password' : '...' }
r = requests.post(http, data=json.dumps(data), headers=head, verify=False)
print(r.text)
should return the same but I get the error
{"id":"3bca1f46-0577-40a9-8e09-7d68557ad88f","rafalError":"WrongJson","message":"DecodingFailure at .identifier: Attempt to decode value on failed cursor"}
with r.status_code returning 422.
import requests
import json
import numpy as np
payload = {'query':json.dumps({
"per_page":12,
"sort":None,
"scroll_id":None,
"session_id":None,
"q":"diapers",
"shingle_active":False,
"location":"110005",
"types":["allopathy","brand","sku","udp"],
"country":"",
"is_query_suggestion_applicable":False,
"debug":False,
"filters":None,
"source_fields":["count"],
"query_filters":None,
"is_all":True
})}
headers = {'Content-Type': 'application/json'}
url = 'https://kjhghfjdslsls'
r = requests.post(url, params=payload, headers=headers)
print(r.text)
This gives error :
{"errors":[{"message":"Parameter per_page is required"}],"is_success":false,"status_code":400}
Though when using the below curl request it is working fine & returning required output-->
curl --location --request POST 'http://khjfhdksl' \
--header 'Content-Type: application/json' \
--header 'Content-Type: application/json' \
--data-raw '{
"sort":null,
"per_page":12,
"scroll_id":null,
"session_id":null,
"q":"diapers",
"shingle_active":false,
"location":"110005",
"types":["allopathy","brand","sku","udp"],
"country":"",
"is_query_suggestion_applicable":false,
"debug":false,
"filters":null,
"source_fields":["count"],
"query_filters":null,
"is_all":true
}'
You have a top-level key query in the payload for the python version. And you are passing the payload as params (query params)
Try removing that:
import requests
import json
import numpy as np
payload = json.dumps({
"per_page":12,
"sort":None,
"scroll_id":None,
"session_id":None,
"q":"diapers",
"shingle_active":False,
"location":"110005",
"types":["allopathy","brand","sku","udp"],
"country":"",
"is_query_suggestion_applicable":False,
"debug":False,
"filters":None,
"facets":[{"field":"sku.brand.raw","name":"brand","type":"facet","range":None},{"field":"product_form","name":"product_form","type":"facet","range":None},{"field":"rx_required","name":"rx_required","type":"facet","range":None},{"field":"uses","name":"uses","type":"facet","range":None},{"field":"age","name":"age","type":"facet","range":None},{"field":"recommended","name":"recommended","type":"facet","range":None}],
"source_fields":["count"],
"query_filters":None,
"is_all":True
})
headers = {'Content-Type': 'application/json'}
url = 'https://search-stag123api.example.com/search-new/search/v1/search/lambda'
r = requests.post(url, data=payload, headers=headers)
print(r.text)
I am able to run curl successfully but not worked with python request for mailchimp API.It gives an error like urllib2.HTTPError: HTTP Error 401: Unauthorized
CURL
curl --request POST \
--url 'https://us9.api.mailchimp.com/3.0/lists' \
--user 'anystring:6a983664930fc8ba1eecdsdf334344f40-us9' \
--header 'content-type: application/json' \
--data '{"name":"My test","contact":{"company":"Cool","address1":"Awesome place","city":"Lanka","state":"MH","zip":"43472","country":"IN","phone":""},"permission_reminder":"You'\''re receiving this email because you signed up.","campaign_defaults":{"from_name":"VD","from_email":"hey#sdfsdf.com","subject":"","language":"en"},"email_type_option":true}' \
--include
Python request :
import urllib2
import json
import requests
url = 'https://us9.api.mailchimp.com/3.0/lists/'
all_params={"user":"my_username:6a983664930fc8ba1eecd1d5d68f4f40-us9",
"name":"My test",
"contact":{"company":"Cool","address1":"Awesome place","city":"Lanka","state":"MH","zip":"43472","country":"IN","phone":""},"permission_reminder":"You'\''re receiving this email because you signed up.","campaign_defaults":{"from_name":"VD","from_email":"hey#sdfsdf.com","subject":"","language":"en"},
"email_type_option":'true'}
post_data = urllib2.quote(json.dumps(all_params))
headers = {'Content-Type': 'application/json'}
request = urllib2.Request(url, post_data, headers)
response = urllib2.urlopen(request)
I have referred Converting cURL to Python Requests but not worked.
I had solved it. It was problem of URL with data center. I was using us9.api... instead of us6.api.mailchimp.com/3.0/lists because my account was created under us6. So, I need to use data center where my account is registered with my URL in request.