02 Dec Python API Tutorials| Getting Started with API’s
API is the acronym for Application Programming Interface, which is a software middleman that allows two applications to interact with each other. Each time we use an application like Facebook, send an instant message or check the weather on your phone and any other apps, you’re using an API.
Another example of an API is when you use an application on your mobile phone. The application connects to the Internet and sends data to a particular server. The server will redeem that data, demystify it, and send it back to your phone. The application then interprets that data and presents you with the information you need in a readable way .In this article, you will learn the basics of Python API and the step-by-step process to get started with APIs.
How to Get Started with Python APIs
To use an API, you have two options. The first option is to authenticate and the second option is not to authenticate and it depends on the kind of API you’re working with. We will demonstrate with two different examples.
For us to get started with getting data or pulling data via the API, we will use a particular library in Python known as the Requests Library. This library is a standard package for making HTTP Requests in Python. There are other libraries for making HTTP Requests such as httplib, urllib, httplib2, treq.
We can install Requests using the command;
pip install requests conda install requests
We also have different standard HTTP Methods;GET; to request data from the server.
-
POST; to submit data to be processed to the server.
-
PUT: Update an API resource
-
DELETE: Delete an API resource
A request is also made up of different parts:
The method – these are the methods which we just discussed now and they
are the GET, POST, PUT and DELETE
The Endpoint – when sending a request to the server, we have an endpoint known as the URL which we used for communicating to that server.
The headers – The headers in a request are used to provide information about the request context so the server can know how to tailor our response such as the content type = application/JSON, authentication keys, and so on.
The data/body – The data/body is usually used in both POST and PUT, with this, we can parse in the credentials we want to use to authenticate with the server.
We must also not forget the status code returned after we sent our request. This status code helps in knowing if our request was successful or not. Examples of these different status codes are; 200(Ok), 201(Created), 404(Not found), 401(Unauthorized), 500(Internal Server Error) etc.
Getting the Data
We’ll demo this with two different options we mentioned earlier which is getting data with Authentication or not, we will use these two APIs to implement this:
-
IPify – a free API that allows you to get your current IP address(No Authentication)
-
Google Calendar – An API used for tracking events and more(With Authentication)
No Authentication
We will use Ipify API with our Requests library to get data. With this API, we will observe that we don’t need any credentials to perform authentication before we can use the API. The reason for this is that the API is an open one which makes it not require authentication.
Sample API Request:
#import the request library import requests #we then use the GET methods
along with the requests library
to retrieve data from the ipify
server data= requests.get('https://api.
ipify.org?format=json') #we now convert our response data
to json json_response=data.json() #we also extract our values we
want it to return back to us. my_ip=json_response['ip'] #Then print our result print(my_ip)
With Authentication
To implement this, we will use the Google Calendar API. To get started, we need to create a new project under the google developer account by using this URL https://console.cloud.google.com and then set our details under Oauth Consent screen and Credentials tab.
After you have completed the whole setup, we will download the credentials.json from the console page and use that to authenticate with the server.
We will write a code to retrieve our calendar events after we have gained access to the API.
Sample code
#import the libraries needed from __future__ import print_
function import datetime import os.path from googleapiclient.discovery
import build from google_auth_oauthlib.flow
import InstalledAppFlow from google.auth.transport.
requests import Request from google.oauth2.credentials
import Credentials # If modifying these scopes,
delete the file token.json. SCOPES = ['https://www.googleapis.
com/auth/calendar.readonly',
'https://www.googleapis.com/auth/
calendar.readonly',
'https://www.googleapis.com/auth/
calendar','https://www.googleapis.
com/auth/calendar.events.readonly'
,
'https://www.googleapis.com/auth/
calendar.events'] #we create an empty list all_events=[] #we create a function main which
has all our functionality def main(): creds=None #this if statement checks if
we have a token.json file in
our working path if os.path.exists('token.
json'): #when token.json exist,
it execute function to recognize
/authorize this user creds = Credentials.
from_authorized_user_file('token.
json', SCOPES) #this is another if
statement which checks if we
don't have the credentials or
the credentials has expired or
not valid if not creds or not creds.
valid: if creds and creds.
expired and creds.refresh_token: creds.refresh
(Request()) #this else is to perform
an authentication with the
server using our credentials.
json file and the SCOPES
we specified else: flow = InstalledAppFlow.
from_client_secrets_file
('credentials.json', SCOPES) creds= flow.run_local_
server(port=0) #After authenticating,
it writes out our result which
contains an access token and
other details which we can
use often in our project with open('token.json',
'w') as token: token.write(creds.to
_json()) #we then read in the token
file which has the access token
and use this with the build
method to access our
calendar events service = build('calendar',
'v3', credentials=creds) now = datetime.datetime.
utcnow().isoformat() + 'Z' #we use the service method to
check our events using our
primary calendarId events = service.events().
list(calendarId='primary',
timeMin=now, singleEvents=True,
orderBy='startTime').execute() all_events.append(events) print(all_events) if __name__ == '__main__': main()
No Comments