I am a complete beginner in the use of API in python. I would like to access this data about Covid 19 vaccination : https://datavaccin-covid.ameli.fr/explore/dataset/donnees-de-vaccination-par-commune/api/
I tried some stuff and it's never working can someone please help me.
This the code I wrote :
import requests
import json
import pandas as pd
query = """{
"nhits":183120,
"dataset":"donnees-de-vaccination-par-commune",
"rows":10,
"start":0,
"facet":[
"semaine_injection",
"commune_residence",
"libelle_commune",
"classe_age",
"libelle_classe_age"
],
"format":"json",
"timezone":"UTC"
}"""
url = 'https://datavaccin- covid.ameli.fr/api/records/1.0/search/?dataset=donnees-de-vaccination-par-commune&q=&facet=semaine_injection&facet=commune_residence&facet=libelle_commune&facet=classe_age&facet=libelle_classe_age&refine.commune_residence=13001'
r = requests.post(url, json= query)
print(r.status_code)
print(r.text)
and I get an error 400
The url I used is the link at the end of the website, I am not sure it is the good one to use :
url used
Thank you
It looks like you're using the "POST" method when you need the "GET" method. The POST method lets you send information to their server. The GET method retrieves only.
r = requests.get(url, json=query)
Also, your query doesn't need all the """ outside the curly braces.
Thanks a lot #James for your help. This works
url = 'https://datavaccin- covid.ameli.fr/api/records/1.0/search/'
query = {"dataset":"donnees-de-vaccination-par-commune",
"rows":100,
"start":0,
"facet":[
"semaine_injection",
"commune_residence",
"libelle_commune",
"classe_age",
"libelle_classe_age"
],
"format":"json",
"timezone":"UTC"}
r = requests.get(url, params= query)
print(r.status_code)
print(r.text)
I had to use params, change the url and get rid of the triple quotes to make it work
Related
I am trying to build a simple record player with the spotify API and I would like to save the playlist id's in variables so it is easier to change or add in the future
import json
import requests
spotify_user_id = "...."
sgt_peppers_id = "6QaVfG1pHYl1z15ZxkvVDW"
class GetSongs:
def __init__(self):
self.user_id=spotify_user_id
self.spotify_token = ""
self.sgt_peppers_id = sgt_peppers_id
def find_songs(self):
query = "https://api.spotify.com/v1/me/player/play?
device_id=......"
headers={"Content.Type": "application/json", "Authorization": "Bearer
{}".format(self.spotify_token)}
data= '{"context_uri":"spotify:album:6QaVfG1pHYl1z15ZxkvVDW"}'
response = requests.put(query, headers=headers, data=data)
I would like to be able to have it like this:
data= '{"context_uri":f"spotify:album:{sgt_peppers_id}"}'
but sadly it doesnt work and all the other methods for inserting variables into strings dont work either. Hope somebody has the anser to this. thank you in advance!
The Spotify API is expecting the request body to be json, which you're currently building by hand. But, it looks like you're using a misspelled header: Content.Type instead of Content-Type (dot instead of dash).
Luckily, the python requests library can encode python objects into json for you and add the Content-Type headers automatically. It can also add the parameters to the url for you, so you don't have to create the ?query=string manually.
# We can add this to the string as a variable in the `json={...}` arg below
album_uri = "6QaVfG1pHYl1z15ZxkvVDW"
response = requests.put(
"https://api.spotify.com/v1/me/player/play", # url without the `?`
params={"device_id": "..."}, # the params -- ?device_id=...
headers={"Authorization": f"Bearer {self.spotify_token}"},
json={"context_uri": f"spotify:album:{album_uri}"},
)
Let the requests library do the work for you!
I managed to import queries into another account. I used the endpoint POST function given by Redash, it sort of just applies to just “modifying/replacing”: https://github.com/getredash/redash/blob/5aa620d1ec7af09c8a1b590fc2a2adf4b6b78faa/redash/handlers/queries.py#L178
So actually, if I want to import a new query what should I do? I want to create a new query that doesn’t exist on my account. I’m looking at https://github.com/getredash/redash/blob/5aa620d1ec7af09c8a1b590fc2a2adf4b6b78faa/redash/handlers/queries.py#L84
Following is the function which I made to create new queries if the query_id doesn’t exist.
url = path, api = user api, f = filename, query_id = query_id of file in local desktop
def new_query(url, api, f, query_id):
headers ={'Authorization': 'Key {}'.format(api), 'Content-Type': 'application/json'}
path = "{}/api/queries".format(url)
query_content = get_query_content(f)
query_info = {'query':query_content}
print(json.dumps(query_info))
response = requests.post(path, headers = headers, data = json.dumps(query_info))
print(response.status_code)
I am getting response.status_code 500. Is there anything wrong with my code? How should I fix it?
For future reference :-) here's a python POST that creates a new query:
payload = {
"query":query, ## the select query
"name":"new query name",
"data_source_id":1, ## can be determined from the /api/data_sources end point
"schedule":None,
"options":{"parameters":[]}
}
res = requests.post(redash_url + '/api/queries',
headers = {'Authorization':'Key YOUR KEY'},
json=payload)
(solution found thanks to an offline discussion with #JohnDenver)
TL;DR:
...
query_info = {'query':query_content,'data_source_id':<find this number>}
...
Verbose:
I had a similar problem. Checked redash source code, it looks for data_source_id. I added the data_source_id to my data payload which worked.
You can find the appropriate data_source_id by looking at the response from a 'get query' call:
import json
def find_data_source_id(url,query_number,api)
path = "{}/api/queries/{}".format(url,query_number)
headers ={'Authorization': 'Key {}'.format(api), 'Content-Type': 'application/json'}
response = requests.get(path, headers = headers)
return json.loads(response.text)['data_source_id']
The Redash official API document is so lame, it doesn't give any examples for the documented "Common Endpoints". I was having no idea how I should use the API key.
Instead check this saviour https://github.com/damienzeng73/redash-api-client .
I've been looking around and trying to get a post request to work, but I haven't found any luck. I keep getting a MISSING_REQUIRED_PARAM each time the request is being made. My following code is shown below.
def create_sign_group(group_name, header, url):
temp_header = header
temp_header['Content-Type'] = 'application/json'
temp_header['Accept'] = 'application/json'
data = {
"GroupCreationInfo": {
"groupName": group_name
}
}
res = requests.post(url + 'groups', headers=temp_header, data=json.dumps(data))
if res.status_code == 200:
print('{} Group Created...'.format(group_name))
else:
print(res.status_code)
print(res.headers)
print(res.text)
exit(res.status_code)
I've tried using json instead of data, but still getting the same error. Using a the REST API client I was able to successfully make the call. The rest client is shown below:
If anyone can point shine some knowledge and point me in the right direction I would greatly appreciate it. Take care.
You should assign headers=temp_header not headers=header. MISSING_REQUIRED_PARAM is often griping about the content type header, which, as you can see IS being included in your screenshot test.
So I figured it out, I guess I was passing the wrong payload into the data param. I changed the code to:
data = {
"groupName": group_name
}
It looks like I didn't need the "GroupCreationInfo" parameter.
I am trying to learn Requests and practicing by connecting to the weather API. But for some reason I can't get it to work? It is clear the weather API is wanting the param in a certain way that I cannot seem to figure out how it translates to Requests.
Here is my code:
r = requests.get('http://api.openweathermap.org/data/2.5/weather', q={'Anderson'})
Here is the link to the API page:
https://openweathermap.org/current
I see the weather pages wants the param in terms of q = city, but the error I get is:
TypeError: request() got an unexpected keyword argument 'q'
Also here the the Requests page that I am referring to: http://docs.python-requests.org/en/master/
Thanks for the help!
Please review the requests user manual, at least the quickstart guide.
The RESTful API you are about to use expects GET request with q="City Name" parameter. Moreover you must have the appid and add it for every request.
Register you application and choose a pricing plan https://openweathermap.org/price
Pass both q="City Name" and APPID=xxx parameters
Here is corresponding request:
api_url = 'http://api.openweathermap.org/data/2.5/weather'
appid = ...
r = requests.get(url=api_url, params=dict(q='Anderson', APPID=appid))
You need an appid for openweather, which for individual use is free (https://openweathermap.org/appid#get)
>>> import requests
>>> r = requests.get('http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1')
>>> loc_weather = r.content.strip()
>>> loc_weather
'{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200}'
Try changing your call to the one that follows (by adding the api key to the params):
r = requests.get('http://api.openweathermap.org/data/2.5/weather', params={'q': 'Anderson', 'APPID': YOUR_API_KEY})
This worked for weatherbit.
The url:
url = "https://api.weatherbit.io/v2.0/history/daily"
Create a payload:
payload = {'key':'12345fcfa0hjde13a7896fbdae1ghjkjh',
'city_id': '1261481', # This is New Delhi
'start_date': '2021-03-13',
'end_date': '2021-03-14'}
Call it using GET (the website specifies that GET call is supported):
data = requests.get(url, params=payload)
assert data.status_code == 200
assert 'error' not in data.json().keys()
Your data:
data.json() # Or text or content
My sys specs: Python 3.8, Request 2.25.1
I'm connecting to a login protected API with a Python script here below.
import requests
url = 'https://api.json'
header = {'Content-Type': 'application/x-www-form-urlencoded'}
login = ('kjji#snm.com', 'xxxxx')
mnem = 'inputRequests':'{'inputRequests':'[{'function':'GDSP','identifier':'ibm','mnemonic':'IQ_TOTAL_REV'}]}}
r = requests.post(url, auth=login, data=mnem, headers=header)
print(r.json())
The connection is established but I am getting an error from the API because of the format of the data request.The original format is here below. I cannot find a way to enter this in the mnem here above:
inputRequests={inputRequests:
[
{function:"xxx",identifier:"xxx",mnemonic:"xxx"},
]
}
The error given is
C:\Users\xxx\Desktop>pie.py
File "C:\Users\xxx\Desktop\pie.py", line 6
mnem={'inputRequests':'{'inputRequests':'[{'function':'xxx','identifier':'xx','mnemonic':'xxx'}]}}
^
SyntaxError: invalid syntax
I am unsure on how to proceed from here. I cannot find anything in the requests documentation that points to how to insert several variables in the data field.
The requests module in Python receive protogenic Python dict as the JSON data in post request but not a string. Therefore, you may try to define mnem like this:
mnem = {
'inputRequests':[
{'function':'GDSP',
'identifier':'ibm',
'mnemonic':'IQ_TOTAL_REV'
}
]}
the data parameter should be a dictionary.
therefore to pass the three parameters try using:
mnem = {'function':'GDSP','identifier':'ibm','mnemonic':'IQ_TOTAL_REV'}