Convert curl command to http request in python - python

I'm new on REST API's and I'm unable to make run an http request.
If I try the curl command it works by terminal:
curl \
--request POST \
--header "X-OpenAM-Username: user" \
--header "X-OpenAM-Password: password" \
--header "Content-Type: application/json" \
--data "{}" \
http://openam.sp.com:8095/openamSP/json/authenticate
and the result:
{"tokenId":"AQIC5wM2LY4Sfczw67Mo6Mkzq-srfED3YO8GCSe0Be6wtPs.*AAJTSQACMDEAAlNLABM2NzQ5NjQ4Mjc0MDY0MzEwMDEyAAJTMQAA*","successUrl":"/openamSP/console"}
But now, from my web on Django I want to make a request and I'm unable to make it work, the code that I use it's:
import requests
headers = {'X-OpenAM-Username':'user', 'X-OpenAM-Password':'password', 'Content-Type':'application/json'}
data = {}
r = requests.get('http://openam.sp.com:8095/openamSP/json/authenticate', headers=headers, params=data)
and if I check the answer:
u'{"code":405,"reason":"Method Not Allowed","message":"Method Not Allowed"}'
What I'm doing wrong? I can't see where is my mistake.
Thanks and regards.

You are doing everything correct, except POST method just do this:
r = requests.post('http://openam.sp.com:8095/openamSP/json/authenticate', headers=headers, params=data)
The method URL receives is POST method not GET.

Related

API call to Fathom Analytics via Postman

I'm trying to make an API call to Fathom Analytics. But I cannot figure out the filtering option (e.g. filter reportings for specific pathname). Can someone help me figuring this out?
curl --location --request GET 'https://api.usefathom.com/v1/aggregations?entity=pageview&entity_id=[SITE_ID_HERE]&aggregates=visits, uniques, pageviews, avg_duration, bounce_rate' \
--header 'Authorization: Bearer [BEARER_TOKEN_HERE]'
How can I insert the json-payload here in order to use the Fathom Filter option (https://usefathom.com/api#aggregation)
Also, I rebuilt the api call in python, without success. When I remove the payload from the API call it works just fine.
import requests
endpoint = "https://api.usefathom.com/v1/aggregations?entity=pageview&entity_id=[SITE_ID]&aggregates=pageviews,visits,uniques,avg_duration,bounce_rate&date_from=2022-10-01&date_to=2022-10-31"
payload = [{"property": "pathname",
"operator": "is",
"value": "/[URL TO FILTER]"}]
headers = {
"Authorization": "[BEARER_TOKEN]"}
response=requests.get(endpoint, json=payload, headers=headers)
print(response.json())
I struggled a bit with this too, and in my case it worked when I included the "filter" key name in the JSON payload itself rather than the curl command.
Here's what worked for me:
curl https://api.usefathom.com/v1/aggregations \
-H "Authorization: Bearer [BEARER_TOKEN_HERE]" \
-H "Accept: application/json" \
-d entity="pageview" \
-d entity_id="[SITE_ID_HERE]" \
-d aggregates="pageviews" \
-d "{'filters': [{'property':'country', 'operator':'is', 'value':'UK'}]}" \
-G
Moving the JSON to its own file (payload.json) and updating that curl line to this also worked:
-d #payload.json \

How to translate curl command to urlfetch or request in general?

I'd like to issue an https request to an api from my gae-server, e.g. using urlfetch.
Example call is given as curl command.
curl <URL> \
-u <USER_KEY>: \
-d "infoa=123" \
-d "infob='ABC" \
-d "token=<SOME_TOKEN>" \
-d "description=Test"
All I want to know is, what the HTTPS request would look like, so I can replicate it using this documentation. Probably going about it wrong but I have used --trace-ascii - with curl but from the ouptut I still cannot 100% say what the request I am issuing looks like.
What aspect of an http-request do they translate to? Would it something like this work:
result = urlfetch.fetch(
url='<URL>',
payload={user: <USER_KEY>, data: {infoa=123, infob=ABC, ...}},
method=urlfetch.POST,
headers=headers)
So: -u for user goes into the authorization header. basic encryption is base64. -d for data goes into payload. Different -d are concatenated with a simple ampersand.
try:
headers = {'Content-Type': 'application/x-www-form-urlencoded',
"Authorization": "Basic %s" % base64.b64encode(<some_private_user_authentication>)} # base64 or similar needs to be imported
result = urlfetch.fetch(
url='<URL of endpoint>',
payload='infoa={}&infob={}&description=Test Transaction'.format(info_a, info_b),
method=urlfetch.POST,
headers=headers)
print repr(result.content) # do things..
except urlfetch.Error:
logging.exception('Caught exception fetching url')
print 'Caught exception fetching url' # do other things..

how to use below curl command in python

Below is the curl command and wanted to use in python by using request. I am beginner to python. Appreciate advice/help.
curl --header 'Content-Type: text/xml;charset=UTF-8' --data-binary #c:/abcd.xml -X POST http://www.dneonline.com/calculator.asmx
You can use Requests to POST data:
import requests
url = 'http://www.dneonline.com/calculator.asmx'
files = {'c': open('/abcd.xml', 'rb')}
r = requests.post(url, files=files)
Requests is now a defacto standard.
Either use requests module or call it from a shell.
So,
from subprocess import call
call("curl --header 'Content-Type: text/xml;charset=UTF-8' --data-binary #c:/abcd.xml -X POST",shell=True)

How to make curl post request from python

I am trying to make a post request using curl in python but the below script throws error
import os
first_name1 = "raj"
last_name1 = "kiran"
full_name = "raj kiran"
headline = "astd"
location1 = "USA"
current_company1 = "ss"
curl_req = 'curl -X POST -H "Content-Type: application/json" -d '{"first_name":"{0}","last_name":"{1}","current_company":"{2}","title":"{3}","campus":"","location":"{4}","display_name":"{5}","find_personal_email":"true"}' http://localhost:8090'.format(first_name1,last_name1,current_company1,headline,location1,full_name)
os.popen(curl_req)
Error:
SyntaxError: invalid syntax
How to make above program work?
The problem in your code is the quotes. Change it to:
curl_req = '''curl -X POST -H "Content-Type: application/json" -d '{"first_name":"{0}","last_name":"{1}","current_company":"{2}","title":"{3}","campus":"","location":"{4}","display_name":"{5}","find_personal_email":"true"}' http://localhost:8090'''.format(first_name1,last_name1,current_company1,headline,location1,full_name)
But, as mentioned in the comments, requests will always be a better choice.
Requests syntax:
import requests
post_data = {
# all the data you want to send
}
response = requests.post('http://localhost:8090', data=post_data)
print response.text
One good resource I've used for converting a cURL request to Python requests is curlconverter. You can enter your cURL request and it will format it for Python requests.
As a side note, it can also convert for PHP and Node.js.
Hope that helps!

Converting cURL to Python Requests

I need to convert the following cURL command to python requests.
curl 'https://test.com/api/v1/courses/xx/discussion_topics/xx/entries.json' \
-F 'message=<message>' \
-H "Authorization: Bearer <token>"
So far I have requests.post("https://test.com/api/v1/courses/xx/discussion_topics/xx/entries")
but how do I add the message and auth?
requests.post("https://test.com/api/v1/courses/xx/discussion_topics/xx/entries.json, data=json.dumps({"message": "<message>"}), headers={"Authorization": "Bearer <token>"})

Categories

Resources