Get a sneak peek at APIs
By: Vivaldi Valentina
Tags: Python, Data Scientist, API

In the following I will show you how API requests can be easily made or how an API can be straightforwardly created with Python.

How to make API Requests in Python?

First of all, in order to make an API request, the request library has to be installed as in the following:

pip install request

There are many different types of requests, the most commonly used is the GET one which is utilized to retrieve data (here you can find all the available methods).

Whenever a request is made, the response from the API comes with a response code which tells whether the request was successful and a response data.

The following command describes how to make a request and get respectively the response code and the data. (For the below example I am using an open API: http://open-notify.org/Open-Notify-API/)

Sometimes, it can be also necessary to add some parameters to the request; a dictionary with the needed parameters can be defined, and then it can be passed into the requests.get function, as below:

However, everytime we need to make an API request, the API documentation gives us all the needed information such as the parameters required, the ones optional and the response format.

How to build an API in Python?

An API can be created using Python and the Flask web framework. After having installed flask, the following code creates a working web application and it allows us to implement an API.

import flask app = flask.Flask(__name__)

app.config["DEBUG"] = True

@app.route('/', methods=['GET'])

def home():

return "<h1>First API</h1><p>This site is a prototype API.</p>" app.run()

The simpler example is the one which returns a database. For example we can add some data as a list of Python dictionaries, replacing the previous code as following:

import flask

from flask import request, jsonify app = flask.Flask(__name__)

app.config["DEBUG"] = True # Create some test data for our catalog in the form of a list of dictionaries.

books = [

{'id': 0,

'title': 'A Fire Upon the Deep',

'author': 'Vernor Vinge',

'first_sentence': 'The coldsleep itself was dreamless.',

'year_published': '1992'},

{'id': 1,

'title': 'The Ones Who Walk Away From Omelas',

'author': 'Ursula K. Le Guin',

'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.',

'published': '1973'},

{'id': 2,

'title': 'Dhalgren',

'author': 'Samuel R. Delany',

'first_sentence': 'to wound the autumnal city.',

'published': '1975'}

]

@app.route('/', methods=['GET'])

def home():

return '''<h1>Distant Reading Archive</h1>

<p>A prototype API for distant reading of science fiction novels.</p>'''

# A route to return all of the available entries in our catalog.

@app.route('/books/all', methods=['GET'])

def api_all():

return jsonify(books) app.run()

Once the code has been run and the server is running, visiting the URL you will be able to view the data in the catalog. You should see JSON output for the three entries in our test catalog. Flask provides us with a jsonify function that allows us to convert lists and dictionaries to JSON format. At this point, the very first and easy API has been created.

Another easy, but more interesting example, about building a weather app can be found here.