Schiphol flight api, get flight information with python gets error - python

I'm trying to get data from a public api from schiphol (airport in Amsterdam).
Im getting this api from https://api.schiphol.nl/public-flights/flights.
I'm using python to get the flight data. In my code I get the error that the "app_id" is none while this is filled in....
the full error from the console:
Usage: flight_info_api.py [options]
flight_info_api.py: error: Please provide an app id (-i, --app_id)
Can anybody see what is going wrong?
My code:
import requests
import sys
import optparse
def callPublicFlightAPI(options):
url = 'https://api.schiphol.nl/public-flights/flights'
headers = {
'resourceversion': 'v4',
'app_id': 'b209eb7f',
'app_key': '0b6c58b5ae4595dd39785b55f438fc70'
}
try:
response = requests.request('GET', url, headers=headers)
except requests.exceptions.ConnectionError as error:
print(error)
sys.exit()
if response.status_code == 200:
flightList = response.json()
print('found {} flights.'.format(len(flightList['flights'])))
for flight in flightList['flights']:
print('Found flight with name: {} scheduled on: {} at {}'.format(flight['flightName'],
flight['scheduleDate'],
flight['scheduleTime']))
else:
print('''Oops something went wrong Http response code: {}{}'''.format(response.status_code, response.text))
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option('-i', '--app_id', dest='app_id',
help='App id used to call the API')
parser.add_option('-k', '--app_key', dest='app_key',
help='App key used to call the API')
(options, args) = parser.parse_args()
if options.app_id is None:
parser.error('Please provide an app id (-i, --app_id)')
if options.app_key is None:
parser.error('Please provide an app key (-key, --app_key)')
callPublicFlightAPI(options)

You need to add this to your headers:
'Accept': 'application/json'
Good luck.
EDIT:
Basically, Since you would like to receive your data as json, You will have to add 'Accept': 'application/json' to your headers. In this case, your headers will look like this:
headers = {
'Accept': 'application/json',
'resourceversion': 'v4',
'app_id': YOUR_APP_ID,
'app_key': YOUR_APP_KEY
}
And when you are going to make a request, you have to add the headers in the parameter. Your request is going to look like this:
response = requests.get(URL, headers=headers)
I hope this helps!

Related

How do I use Riot Games API with an API key?

I was trying to connect to the Riot Games API with the Python requests module, and it keeps giving me a 401 error. I added an API key, but it still says unauthorized. If anyone knows what is wrong with the code it would be appreciated.
I have tried tinkering and all I have this code:
import os
import requests
API_KEY = os.getenv("riot-key")
URL = "https://americas.api.riotgames.com/riot"
headers = {
"Authorization": "Bearer " + API_KEY
}
response = requests.get(URL, headers=headers)
if response.status_code == 200:
print(response.json())
else:
print("Request failed with status code:", response.status_code)
All I really have concluded is that the API key itself is not the issue, it is the request call.
It looks like Riot Games API uses the header X-Riot-Token to pass the authentication token, not Authorization, for some reason.
import os
import requests
API_KEY = os.getenv("riot-key")
URL = "https://americas.api.riotgames.com/riot"
headers = {
"X-Riot-Token": API_KEY
}
response = requests.get(URL, headers=headers)
if response.status_code == 200:
print(response.json())
else:
print("Request failed with status code:", response.status_code)
You can also pass the API key as a query string parameter, however this can be slightly less secure in some scenarios.
import os
import requests
API_KEY = os.getenv("riot-key")
URL = "https://americas.api.riotgames.com/riot?api_key=" + API_KEY
response = requests.get(URL)
if response.status_code == 200:
print(response.json())
else:
print("Request failed with status code:", response.status_code)
Use your api key as a parameter rather than a header.
https://americas.api.riotgames.com/riot/?api_key=YOUR-API-KEY
Here is some help I found: https://apipheny.io/riot-games-api/#:~:text=All%20API%20calls%20to%20Riot,re%20making%20the%20request%20on.

Request data from Linkedin

I have Problem with scraping data from LinkedIn.
I think the documentation is too complicated ...
here the problem, I want to make a request (GET) and get for example data of my feed/posts/chats or whatever.
here is my code:
import json
import requests
# URL = "https://www.linkedin.com/voyager/api/voyagerMessagingDashConversationNudges"
URL = "https://www.linkedin.com/voyager/api/identity/dash/profiles"
cookies = {
#Cookies are here
}
params = {
'decorationId': 'com.linkedin.voyager.dash.deco.identity.profile.WebTopCardCore-6',
'memberIdentity': 'maria-albert-137632240',
'q': 'memberIdentity',
}
def get_group(url: str, cookies: dict, data:dict, header: dict):
response = requests.get(url=url, cookies=cookies, data=json.dumps(data), headers=header)
response.raise_for_status()
return response.json()
if __name__ == "__main__":
print("sending request to Server:\n")
get_group(url=URL, cookies=cookies, data=params, header=headers)
but I couldn't do it, the error --> raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: INKApi Error for url: https://www.linkedin.com/voyager/api/identity/dash/profiles
Thanks for your help.
You just need to set header like this:
header = {
"accept": 'application/vnd.linkedin.normalized+json+2.1',
"cookie": 'JSESSIONID="ajax:abcd"; li_at=abcdabcd',
}
and so fill the payload as the endpoint needed.
You don't have to Create App to access token or anything else.

LinkedIn API request with Python returns "Unpermitted fields present in PARAMETER: Data Processing Exception while processing fields"

I am trying to Retrieve Statistics for Specific UGC Posts using the official documentations
My request looks like this:
requests.get(f'https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A00000&ugcPosts[0]=urn%3Ali%3AugcPost%3A111111&ugcPosts[1]=urn%3Ali%3AugcPost%3A222222', headers = headers)
"00000" is the company ID
"111111" and "222222" - are ugcPosts URNs
The headers look like this:
def headers(access_token):
'''
Make the headers to attach to the API call.
'''
headers = {
'Authorization': f'Bearer {access_token}',
'cache-control': 'no-cache',
'X-Restli-Protocol-Version': '2.0.0'
}
I have also passed the scope as one of the parameters, when authorizing:
def authorize(api_url,client_id,client_secret,redirect_uri):
# Request authentication URL
csrf_token = create_CSRF_token()
params = {
'response_type': 'code',
'client_id': client_id,
'redirect_uri': redirect_uri,
'state': csrf_token,
'scope': 'r_liteprofile,r_emailaddress,w_member_social,r_organization_social,r_1st_connections_size,r_ads_reporting,rw_organization_admin,r_basicprofile,r_ads,rw_ads,w_organization_social'
}
response = requests.get(f'{api_url}/authorization',params=params)
Unfortunately this particular request doesn't give me the response I was expecting:
{'serviceErrorCode': 100, 'message': 'Unpermitted fields present in PARAMETER: Data Processing Exception while processing fields [/ugcPosts[1], /ugcPosts[0]]', 'status': 403}
It works ok, when requesting a list of all ugcPosts
requests.get('https://api.linkedin.com/v2/ugcPosts?q=authors&authors=List(urn%3Ali%3Aorganization%3A00000)&sortBy=CREATED&count=100', headers = headers)
I have no clue what am I don't wrong. Can you please help me with my predicament?
The full request code is here
import requests
import json
from liapiauth import auth, headers
def organization_info(headers):
response = requests.get(f'https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A00000&ugcPosts[0]=urn%3Ali%3AugcPost%3A1111111&ugcPosts[1]=urn%3Ali%3AugcPost%3A2222222', headers = headers)
organization_info = response.json()
return organization_info
if __name__ == '__main__':
credentials = 'credentials.json'
access_token = auth(credentials)
headers = headers(access_token)
organization_info = organization_info(headers)
with open('lisharelist.json', 'w') as outfile:
json.dump(organization_info, outfile)
So it turns out, that the problem is in request formatting. The documentation is outdated.
The sample request looks like this:
GET https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn:li:organization:2414183&ugcPosts[0]=urn:li:ugcPost:1000000&ugcPosts[1]=urn:li:ugcPost:1000001
Apart from changing ":" to "%3A" we also have to edit the list of ugcPosts. Here is the correct looking sample request:
GET https://api.linkedin.com/v2/organizationalEntityShareStatistics?q=organizationalEntity&organizationalEntity=urn%3Ali%3Aorganization%3A2414183&ugcPosts=List(urn%3Ali%3AugcPost%3A1000000,urn%3Ali%3AugcPost%3A1000001)

401 Client Error: Unauthorized url. Flask python

I have a program that Authenticate with API and when logged in search by Id in contacts on this API.
logging in works fine but when I try to find contact this error happen:
401 Client Error: Unauthorized for url:https://api.moxiworks.com/api/contacts/12345678
and same problem happen when try it on Postman like in this image:
after log in I redirected to home route and here is the code:
#app.route('/home', methods=["GET", "POST"])
#login_required
def home():
if request.method == "POST":
found = request.form.get('id')
#base64 encoded Partner ID and Partner Secret
sample_string = ('%s:%s' % (os.getenv("CLIENT_ID"), os.getenv("CLIENT_SECRET"))).replace('\n', '')
sample_string_bytes = sample_string.encode("ascii")
base64_bytes = base64.b64encode(sample_string_bytes)
base64_string = base64_bytes.decode("ascii")
if not found:
return render_template('apology', err='must provide id')
try:
token = session['token']
response = moxi.get(f'https://api.moxiworks.com/api/contacts/{found}',
token=token,
headers={
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic %s' % base64_string,
'Accept': 'application/vnd.moxi-platform+json;version=1',
'Cookie': '_wms_svc_public_session'
})
if response.status_code == 429:
flash('too many requests, wait for 60 seconds then will get your results')
time.sleep(60)
response = moxi.get(f'https://api.moxiworks.com/api/contacts/{found}',
token=token,
headers={
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic %s' % base64_string,
'Accept': 'application/vnd.moxi-platform+json;version=1',
'Cookie': '_wms_svc_public_session'
})
# If the response was successful, no Exception will be raised
response.raise_for_status()
except HTTPError as err:
return render_template('apology.html', err=err)
except Exception as err:
return render_template('apology.html', err=err)
else:
try:
contact = response.json()
return render_template('data.html',
contact1=contact['agent_uuid'], contact2=contact['moxi_works_agent_id'],
contact3=contact['partner_contact_id'], contact4=contact['contact_name'],
contact5=contact['primary_email_address'], contact6=contact['secondary_email_address'],
contact7=contact['primary_phone_number'], contact8=contact['secondary_phone_number'])
except (KeyError, TypeError, ValueError) as err:
return render_template('apology.html', err=err)
else:
return render_template('home.html')
What I miss? or what is wrong in my code?
here is the auth register:
moxi = oauth.register(
name='moxi',
client_id=os.getenv("CLIENT_ID"),
client_secret=os.getenv("CLIENT_SECRET"),
access_token_url='https://sso.moxiworks.com/oauth/token',
access_token_params={'grant_type': 'authorization_code'},
authorize_url='https://sso.moxiworks.com/oauth/authorize',
authorize_params={'response_type': 'code'},
api_base_url='https://api.moxiworks.com/api/contacts/',
userinfo_endpoint='https://sso.moxiworks.com/agent/profile', # This is only needed if using openId to fetch user info
client_kwargs = {
'scope': 'profile',
'token_endpoint_auth_method': 'client_secret_basic',
'token_placement': 'header',
}
)
please help me to figure out how to fix this?
thanks in advance.
The error shows that you have not included your authorisation header. According to the Basic Authentication standard (RFC 7617) used here, you should include the access token in the Authorization header instead of the parameter. As such, it should look something like this enter image description here.
Or on the python code, it will look like this
import requests
url = "https://example.com/api/contacts/1234"
payload = {}
headers = {'Authorization': 'Basic <access_token>'}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)

Basic Authentication returns 401 Client Error but works in postman

I have gone through number of similar posts related to firing GET requests with Basic Auth (eg: Python, HTTPS GET with basic authentication), still can't figure out the problem. I keep getting the error requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url
With the same credentials, headers tried the same in postman it works as expected. Verified that base64encoded value for the api_key, password is exactly same as the value used in postman, so I don't think its encoding or resource access permission problem.
python -V
Python 3.6.4 :: Anaconda, Inc.
Approach 1
api_key = 'some_api_key'
password = 'some_password'
headers = {'accept': 'application/json'}
url = 'https://test.access.com/this/url'
api_key_password = "%s:%s" % (api_key, password)
b64_encoded = b64encode(bytes(api_key_password, 'utf-8')).decode("ascii")
headers['authorization'] = 'Basic %s' % b64_encoded
response = requests.get(url,
headers=headers)
if (response.ok):
json_data = json.loads(response.content)
print (json_data)
else:
print (response)
response.raise_for_status()
Approach 2
api_key = 'some_api_key'
password = 'some_password'
url = 'https://test.access.com/this/url'
headers = {
'accept': 'application/json',
}
response = requests.get(url, headers=headers, auth=(api_key, password))
print (response.ok)
if (response.ok):
json_data = json.loads(response.content)
print (json_data)
else:
print (response)
response.raise_for_status()
Can you please provide some pointers?
I had a similar issue (although in .NET Framework).
In my case the reason was that I was using the url without a forward slash in the end and the API apparently does not support that.
So https://test.access.com/this/url
Throws 401 error Unauthorized
but
https://test.access.com/this/url/
Returns 200 OK.
Older post but I had a similar issue. Postman will cache your JSESSIONID. Be sure you are clearing out that cookie while testing. If you are hitting an API that requires a login API call to establish a session before you can make subsequent API calls, this Postman behavior can produce a false sense of security.
In this situation with Python requests, it can be handled with code similar to what I've provided below:
import requests,json
loginAPI = "https://myapi.myco.comv/someuri/someuri/users/login"
someHTTPGetAPI = "https://myapi.myco.com/someuri/someuri/someservice"
username = "myuser"
password = "mypass"
headers = {
"Content-Type": "application/json",
"login": username,
"password": password
}
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
verify=False
session = requests.Session()
sessionResponse = session.get(url=loginURL,headers=headers, verify=verify)
if sessionResponse.status_code == 200:
getResponse = session.get(url=someHTTPGetAPI)
if getResponse.status_code == 200:
responseJSON = agentStatus.json()

Categories

Resources