I would like to make a python query with this data but I can not convert the 'data-urlencode' interpretable for the python query.
It's my curl request :
curl \
--compressed \
-H 'Accept-Encoding:gzip' \
-H 'Accept-Language:fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7' \
--get '**myurl**' \
--data-urlencode 'app_code=xxxxxx' \
--data-urlencode 'app_id=xxxxxx'
And this this my actual python request:
import requests
headers = {
'Accept-Encoding': 'gzip',
'Accept-Language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7',
}
data = {
'app_code': 'xxxxx',
'app_id': 'xxxxx'
}
response = requests.post('https://places.cit.api.here.com/places/v1/autosuggest', headers=headers, data=data)
I have trouble encoding the data to get the json.
Thanks
Isn't that curl command a GET request?
I'm not able to try your example but could you please try using the code below.
import requests
url = "https://places.cit.api.here.com/places/v1/autosuggest"
h = {
"Accept-Encoding":"gzip",
"Accept-Language":"fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7"
}
params = {
"app_code":"xxxxx",
"app_id":"xxxxx"
}
r = request.get(url, headers=h, params=params).json()
Related
I want to create a pull request on github using the API. The following curl command does work
curl \
-X POST \
-H "Accept: application/vnd.github.v3+json" -H "Authorization: token ghp_abc...123" \
https://api.github.com/repos/alex4200/hello-world/pulls \
-d '{"head":"copyright_updater","base":"master","title":"Test PR curl"}'
but this python snippet does not work:
import requests
headers = {
"Accept": "application/vnd.github.v3+json",
"Authorization": "token ghp_abc...123"
}
data = {
"head": "copyright_updater",
"base": "master",
"title": "Test PR python"
}
response = requests.post(
"https://api.github.com/repos/alex4200/hello-world/pulls",
headers=headers,
data=data
)
print(response.text)
This command, with the exact same data as the curl, returns a 400 error with the message
{"message":"Problems parsing JSON","documentation_url":"https://docs.github.com/rest/reference/pulls#create-a-pull-request"}
What is the problem here?
For some reasons my requests to an API is failing. This is the code:
def create_alert(alert_dict)
url = host + '/api/alerts'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer tokengen'
}
response = requests.request('POST', url, headers = headers, data=json.dumps(alert_dict))
return response
alert_dict = {
"priority": "1",
"to": to,
"from": from_
}
response = create_alert(alert_dict)
print(response)
The way I'm doing it is saving everything to a dictionary, then making the POST request with it. But for some reason im getting a 500 error.
This is the curl that is working
curl --location --request POST "http://newhost.com/api/alerts" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer tokengen" \
--data "{
\"to\": \"sample#email.com\",
\"from\": \"from#email.com\",
\"priority\": \"1\",
}"
How should I convert my dict in a way that it would work just like the curl --data when requested
I need to retrieve a JWT (JSON Web Token) from a Microsoft API using Python (check this API documentation for Microsoft Graph)
The following Python code using the requests library does not work giving HTTP response code 400, however, the equivalent cURL command does work giving back the expected JSON containing the JWT.
Python / requests code:
tenant = "<MY_FOO_TENANT>"
token_url = "https://login.microsoftonline.com/{}/oauth2/v2.0/token".format(tenant)
http_headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
http_query_params = {
"client_id": "<MY_FOO_C_ID>",
"scope": "<MY_FOO_SCOPE>",
"client_secret": "<MY_FOO_C_SECRET>",
"grant_type": "client_credentials",
}
http_response = requests.post(token_url, params=http_query_params, headers=http_headers)
cURL command:
curl -v -X POST \
--data-urlencode 'client_id=<MY_FOO_C_ID>' \
--data-urlencode 'scope=<MY_FOO_SCOPE>' \
--data-urlencode 'client_secret=<MY_FOO_C_SECRET>' \
--data-urlencode 'grant_type=client_credentials' \
-H 'Content-Type: application/x-www-form-urlencoded' \
'https://login.microsoftonline.com/<MY_FOO_TENANT>/oauth2/v2.0/token'
From the verbose output of the requests library I can see that it is URL encoding all those HTTP query parameters, so I tend to think that should not be the problem.
what's wrong with the Python implementation?
how to make it work?
you should pass http_query_params as data instead of params. try the following code:
tenant = "<MY_FOO_TENANT>"
token_url = "https://login.microsoftonline.com/{}/oauth2/v2.0/token".format(tenant)
http_headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
http_body = {
"client_id": "<MY_FOO_C_ID>",
"scope": "<MY_FOO_SCOPE>",
"client_secret": "<MY_FOO_C_SECRET>",
"grant_type": "client_credentials",
}
http_response = requests.post(token_url, data=http_body, headers=http_headers)
hope this helps
I have this curl command:
curl -X GET --header 'Accept: application/vnd.pagerduty+json;version=2' --header 'Authorization: Token token=y_NbAkKc66ryYTWUXYEu' 'https://api.pagerduty.com/services?time_zone=UTC&sort_by=name'
I need to convert it to python using requests library
import requests
def support(self):
services_list = requests.get('I need to convert the link to pass it here as a parameter')
import requests
def support():
headers = {
'Accept': 'application/vnd.pagerduty+json;version=2',
'Authorization': 'Token token=y_NbAkKc66ryYTWUXYEu'}
payloads = (
('time_zone', 'UTC'),
('sort_by', 'name'),)
services_list = requests.get('https://api.pagerduty.com/services', headers=headers, params=payloads)
I need to write Python equivalent code for below mentioned working curl(I have replaced the credentials for obvious reason, but it gives back 200 status.).
curl -X POST \
'https://api.lever.co/v1/candidates?dedupe=true&perform_as=user_123' \
-H 'Authorization: Basic token_123' \
-H 'Cache-Control: no-cache' \
-H 'Content-Type: multipart/form-data' \
-H 'Postman-Token: 58cafa90-7ae4-47db-a144-4e9d430ffc94' \
-H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
-F 'files[]=#/Users/gaurav/lever_resume.pdf' \
-F 'emails[]=a#b.com'
So, I ended up in writing this snippet.
user_email = 'user#domain.com'
admin_id = '20f3975a-543f-4ca8-b215-2f851232a0ad'
client_id = '893728937298'
client_secret = '32032'
file_path = '/Users/ttn/Desktop/a.txt'
file_name = 'a.txt'
logging.basicConfig(level=logging.DEBUG)
url = "https://api.lever.co/v1/candidates"
files = {
'files[]': (file_name, open(file_path,'rb')),
}
auth = HTTPBasicAuth(client_id, client_secret)
querystring = {
"perform_as": admin_id,
"dedupe": 'true'
}
payload = {
'emails[]': user_email
}
headers = {
'Content-Type': "multipart/form-data",
"Cache-Control": "no-cache",
"content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
}
response = requests.post(url,
headers=headers,
params=querystring,
data=payload,
auth=auth,
files=files)
req = response.request
# print(curlify.to_curl(req))
print('\n==== Headers', req.headers)
print('\n==== Body', req.body)
print('\n==== form-data', str(req))
print(response.text)
Question
Since Python version of Curl is not working(giving 502 error instead of 200), so How can I compare the two? Can I generate the Curl out of Python's request`?
Can someone spot mistake in my Python version? I am suspecting some problem at form-data being passed (to collect evidence, I need answer to above question)
Edit
There seems to be a curlify package. But It looks like it does not support distinction between -d and -F parameters.
Try this:
import requests
headers = {
'Authorization': 'Basic token_123',
'Cache-Control': 'no-cache',
'Content-Type': 'multipart/form-data',
'Postman-Token': '58cafa90-7ae4-47db-a144-4e9d430ffc94',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW',
}
params = (
('dedupe', 'true'),
('perform_as', 'user_123'),
)
files = {
'files[]': ('/Users/gaurav/lever_resume.pdf', open('/Users/gaurav/lever_resume.pdf', 'rb')),
'emails[]': (None, 'a#b.com'),
}
response = requests.post('https://api.lever.co/v1/candidates', headers=headers, params=params, files=files)
#NB. Original query string below. It seems impossible to parse and
#reproduce query strings 100% accurately so the one below is given
#in case the reproduced version is not "correct".
# response = requests.post('https://api.lever.co/v1/candidates?dedupe=true&perform_as=user_123', headers=headers, files=files)oduced version is not "correct".
# response = requests.post('https://api.lever.co/v1/candidates?dedupe=true&perform_as=user_123', headers=headers, files=files)
Reference: https://curl.trillworks.com/#python