I went to the Skyscanner API documentation page, and selected "Python (Requests)" in the language selector. Then I copied the code snippet and changed the inbound and outbound dates to valid dates (i.e., dates later than today). But after running the code, I get blank results. Why is that?
import requests
url = "https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/pricing/v1.0"
payload = "inboundDate=2020-05-20&cabinClass=business&children=0&infants=0&country=US¤cy=USD&locale=en-US&originPlace=SFO-sky&destinationPlace=LHR-sky&outboundDate=2020-05-15&adults=1"
headers = {
'x-rapidapi-host': "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com",
'x-rapidapi-key': "MY_API_KEY", # need to fill up a form to get the Key
'content-type': "application/x-www-form-urlencoded"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
>>> {}
Did you checked response example of that API?
Most of time when API have to return True then response blank also.
Related
I got the following code for fetching all events from a specific calendar.
This code works for me.
I would like to add a variable to get the events of today's date.
I'm using the GET HTTP Request: https://www.googleapis.com/calendar/v3/calendars/calendarId/events
from developers.google.com/calendar/api/v3/reference/events
My code:
import requests
url = "https://www.googleapis.com/calendar/v3/calendars/***calendarId***/events"
payload={}
headers = {
'Authorization': 'Bearer *************************************************'
}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
Building on the comment already posted, you can refer to Google's events list documentation. It explains that you can use the timeMin and timeMax parameters to specify a minimum and maximum date. Note that you have to enter the date in RFC3339 format or you will get an error. Here's an example based on your code:
import requests
url = "https://www.googleapis.com/calendar/v3/calendars/***calendarId***/events"
headers = {
'Authorization': 'Bearer *************************************************'
}
params= {
"timeMin":"2022-09-19T00:00:00-06:00",
"timeMax":"2022-09-19T23:59:59-06:00"
}
response = requests.request("GET", url, headers=headers, params=params)
print(response.text)
You don't need a payload for this method so I removed it from the sample. As explained in the documentation, the offset is mandatory so you have to keep that in mind. There are many ways to generate the datetime, but you can refer to this answer for some samples using the datetime module.
I am trying to access the cites species api to get information on a input species name.
Reference document: http://api.speciesplus.net/documentation/v1/references.html
I tried to use the api with the provided API Key.
I get error code 401.
Here is the code
import requests
APIKEY='XXXXXXXXXXXX' # Replaced with provided api key
r = requests.get('https://api.speciesplus.net/api/v1/taxon_concepts.xml?name=Mammalia&X-Authentication-Token={APIKEY}')
r
As #jonrsharpe said in comment:
"Headers and query parameters aren't the same thing..."
You have to set APIKEY as header - don't put it in URL.
You may also put parameters as dictionary and requests will append them to URL - and code will be more readable.
import requests
APIKEY = 'XXXXXXXXXXXX'
headers = {
"X-Authentication-Token": APIKEY,
}
payload = {
"name": "Mammalia",
}
url = "https://api.speciesplus.net/api/v1/taxon_concepts.xml"
response = requests.get(url, params=payload, headers=headers)
print(response.status_code)
print(response.text)
EDIT:
If you skip .xml in URL then you get data as JSON and it can be more useful
url = "https://api.speciesplus.net/api/v1/taxon_concepts"
response = requests.get(url, params=payload, headers=headers)
print(response.status_code)
print(response.text)
data = response.json()
for item in data:
print(item['citation'])
I'm working on an API for my application to send a POST request to an external API. So for example, if my app hits endpoint /myapp/api I want it to call out to an external API and grab some data. In this case, I need this to be a POST request because in order to get the data that I want, I need to pass in some values.
I have made this POST call directly to the external API via Postman successfully many times, and I'm now trying to reproduce that in my python code.
In my views.py, I have this:
class MyAPPViews(APIView):
def post(self,request):
crt = 'path/to/crtfile'
key = 'path/to/keyfile'
#here I tried to reproduce the headers from the postman call
#as best as I could just to be extra specific
headers = {
'Content-Type': 'application/json',
'Accept': '/*/',
'Accept-Encoding': 'gzip,deflate,br',
'Connection': 'keep-alive'
}
payload = {
"unitList": [
"CFQU319303"
]
}
res = requests.post('external/api/url', headers=headers, data=payload, cert=(crt,key))
print('this is the true http resonse: ',res.status_code)
data = res.json()
return Response({"status": "success", "data": data})
in my urls.py I have this
path('externalAPI',MyAPPViews.as_view()),
Now, when I try to go into postman and hit http://127.0.0.1:8000/myapp/externalAPI
I get a 500 status code returned and the JSONDecodeError of Expecting value: line 1 column 1 (char 0). I understand that this means that basically the json response was empty and there was nothing for it to parse.
Is there anything blatantly wrong with my views.py code?
EDIT Within the res = requests.post('external/api/url', headers=headers, data=payload, cert=(crt,key)), I had to change data=payload to data=json.dumps(payload). I'm assuming it didn't like the way I formatted my payload initially. After that, I also deleted everything but the Content-Type: application/json out my headers dictionary.
I'd say, it's just a wrong URL in your call of the external API, as you are using some path without a domain.
So instead of
res = requests.post('external/api/url', headers=headers, data=payload, cert=(crt,key))
it should be sth. like
res = requests.post('https://SOMEDOMAIN.ORG/external/api/url', headers=headers, data=payload, cert=(crt,key))
Within the res = requests.post('external/api/url', headers=headers, data=payload, cert=(crt,key)), I had to change data=payload to data=json.dumps(payload). I'm assuming it didn't like the way I formatted my payload initially. After that, I also deleted everything but the Content-Type: application/json out my headers dictionary.
Here is the code I have, it works fine, but how could I make it that there is a new variable that is equal to the Image URL of the GIF so that the user can get the Source URL of the GIF?
import requests
url = "https://giphy.p.rapidapi.com/v1/gifs/search"
searchtag = input()
querystring = {"api_key":"secret_key","q":searchtag,"limit":"1","offset":"0","rating":"pg-13"}
headers = {
'x-rapidapi-key': "4005b98f9bmsh977c629b89034a7p19b52fjsn22b7fb5ce3bb",
'x-rapidapi-host': "giphy.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring)
print(response.text)
First off you should probably remove your api key for your own personal safety . I'd recommend looking into environmental files for storing private information that doesn't belong in a database. Second off to answer your question you could just declare the url as a variable if you're feeling ever so inclined, here:
import requests
url = "https://giphy.p.rapidapi.com/v1/gifs/search"
searchtag = input()
querystring = {"api_key":process.env.APIKEY,"q":searchtag,"limit":"1","offset":"0","rating":"pg-13"}
headers = {
'x-rapidapi-key': "4005b98f9bmsh977c629b89034a7p19b52fjsn22b7fb5ce3bb",
'x-rapidapi-host': "giphy.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring)
gifurl = response.text
print(gifurl)
I have simulated successfully API calls with my postman client.
Postman client automatically populates the required JSESSIONID, COOKIE, and CLIENT ID.
However, when I try to realize the same with python I get 401. It looks like the session variable of the request API does not hold the required information
I would like to replicate the entire step below with both Postman generated python script and my script
Postman script
In the first POST call, I use my secretKey to request the secret
import requests
url = "https://url.com/v1/session/auth/token?X-Requested-By=Maddy&Content-Type=application/x-www-form-urlencoded"
payload="secret_key=zxcvfc-103f-950d-856d-cxvfdgh&username=myuser001&access_level=FULL"
headers = {
'X-Requested-By': 'Maddy', #This is my header
'Content-Type': 'application/x-www-form-urlencoded', #My header
'Cookie': 'route=e7esaafb42ce234234242347482341f; clientId= zxcvfc-103f-950d-856d-cxvfdg; JSESSIONID=e34cc53d-e99c-4296-a4fe-0d70a246bd11' #Postman generated
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
I get a secret JHNXZasdasdasdasjdakdasdjdalsdjasdladasdlalsdjajsdjaskdjaksjdaskjdjaskdljasj very long
then the second GET call is done with the secret I have received.
import requests
url = "https://url.com/callosum/v1/session/login/token?username=myuser001&auth_token=JHNXZasdasdasdasjdakdasdjdalsdjasdladasdlalsdjajsdjaskdjaksjdaskjdjaskdljasj&redirect_url=https://url.com/callosum/v1/tspublic/v1/user/list"
payload={}
headers = {
'Cookie': 'route=e78as0dad9009q029420349249f; clientId=s0255-6598-5103-dec3-defererer090; JSESSIONID=dfgas8484-659595656-6526-5626-7589898ads'
}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
#The response contains JSON output with a list of users
Not the above header junk that contains id and session and cookie is generated by the postman
Now this is how my Python script looks like
url = "https://url.com/callosum/v1/session/auth/token?X-Requested-By=Maddy&Content-Type=application/x-www-form-urlencoded"
payload="secret_key=zxcvfc-103f-950d-856d-cxvfdgh&username=myuser001&access_level=FULL"
headers = {
'X-Requested-By': 'Maddy', #These one is mine
'Content-Type': 'application/x-www-form-urlencoded' #these one is mine
}
with requests.session() as s:
secret = s.post(url, data=payload, headers=headers,verify=False).text
#secret contain the lengthy secret for the get call stored in the variable secret
payload1 = {}
#The url2 contains login url and redirect url that contains the user API for get method
url2 = "https://url.com/callosum/v1/session/login/token?username=myuser001&auth_token={}&redirect_url=https://url.com/callosum/v1/tspublic/v1/user/list".format(secret)
r = s.get(url2,data=payload1,verify =False)
#Also tried without payload and with and without header results are the same
print(r.cookies)
print(r.text) #401 unauthroized
I get the secret but not the data. Do let me know if there is something that needs to be added.
Best Regards,
Gabby