buildingapiinpython

Building APIs(Application Programming Interface) – Using Flask, FastAPI and Nodejs

In this tutorial we will be learning how to build an API.

What is an API?

An API refers to Application Programming Interface. API are like messengers that act as intermediary between two or more applications.

It is an interface for interacting and communicating with other softwares and devices.

Supposing I have a database or a service and I want to interact or communicate with that database, there are several ways I may choose to do so. In most cases I may use a GUI – Graphic User Interface like DB Browser  or a CLI (Command Line Interface) tool like sqlite. Both of these are the ways I can use. But what if I do not have enough resources for a GUI or I do not know how to work with the terminal. This is where an API comes to play. An API is another alternate way I can access and interact with the database.

In summary I can use

  • GUI -Graphical User Interface
  • CLI – Command Line Interface
  • API – Application Programming Interface

There are several libraries and frameworks that makes it easier to build production ready APIs. Some of these include

  • Flask (jsonsify,flask_restful,flask_restplus,etc)
  • FastAPI
  • Hug
  • Sanic

We will be building apis using the first two for now. Later we will see how to work with the rest.

Building API with Flask

Flask is a powerful microframework for building web applications. Flask provide several methods to build api. The simplest method is to use jsonify which comes with the standard flask package.

The other method is to use flask extensions such as Flask_Restful

First of all let us install our packages

pip install flask Flask_Restful

Flask jsonify allows us to convert dictionaries and json strings into jsons on the front-end in a nicer way. You can build a simple API using only flask and jsonify. Let us see a simple API meant for displaying books

# Core Pkg
from flask import Flask,jsonify,make_response,abort
import json

# Init
app = Flask(__name__)

# Using External Local Data
with open("books.json") as f:
	books = json.load(f)

@app.route('/')
def index():
	return 'API Tutorials with Flask.eg /api/v1/books to see books'

@app.route('/api/v1/books',methods=['GET'])
def get_books():
	return jsonify({"books":books})


@app.route('/api/v1/books/',methods=['GET'])
def get_book(title):
	book = [book for book in books if book["title"] == title ]
	if len(book) ==0:
		abort(404,"Book with title::{} does not exit".format(title))
	return jsonify({"books":book})

# Using JSONIFY ERROR
@app.errorhandler(404)
def not_found(error):
	return make_response(jsonify({'error':'Not Found'}),404)

if __name__ == '__main__':
	app.run(debug=True)

Building API with Flask Restful

What we built above can also be built with Flask Restful

In using Flask Restful, the most important things to know is how to create a Resource Class for our schema and building custom api routes.

Let us see the same api but with Flask Restful.

from flask import Flask,jsonify,make_response,abort
import json
from flask_restful import Api, Resource

# init app
app = Flask(__name__)
api = Api(app)


# Using External Local Data
with open("books.json") as f:
	books = json.load(f)

# Create Resource Class
class Books(Resource):
	def get(self,title):
		book = [book for book in books if book["title"] == title ]
		if len(book) ==0:
			abort(404,"Book with title::{} does not exit".format(title))
		return jsonify({"books":book})

class BooksList(Resource):
	def get(self):
		return jsonify({"books":books})

# Get All Books
api.add_resource(BooksList,'/api/v1/books')	

# Get Book By Title
api.add_resource(Books,'/api/v1/books/')


@app.route('/')
def index():
	return 'API Tutorials with Flask.eg /api/v1/books to see books'


# Using JSONIFY ERROR
@app.errorhandler(404)
def not_found(error):
	return make_response(jsonify({'error':'Not Found'}),404)

if __name__ == '__main__':
	app.run(debug=True)


Accessing the API

There are various ways we can access our api whiles we are in development mode. These methods include the use of

  • curl
  • wget
  • requests
  • postman/postman canary
  • postwoman
  • browser
  • using other languages

The basic endpoint and url we will be using will be http://127.0.0.1:5000/api/v1/books

With CURL

curl -i http://127.0.0.1:5000/api/v1/books

With Wget

wget http://127.0.0.1:5000/api/v1/books

With Requests

import requests

requests.get(“http://127.0.0.1:5000/api/v1/books”).json()

With Postman/Postwoman

With Your Browser

You can use any web browser such as chrome,firefox or brave and navigate to the url http://127.0.0.1:5000/api/v1/books

These are the main ways you can access and test your api endpoints whiles developing.

 

Building API with FastAPI

Now let us use another alternative to build an API. We will be using FastAPI, a high performance framework that combines the best of flask,go,requests,django and nodejs as well as other to build an API. FastAPI requires an ASGI server such as uvicorn or hypercorn to run hence you will need to also install them.

Installing FastAPI

pip install fastapi uvicorn

Let us build our simple books api with fastapi.


from flask import Flask,jsonify,make_response,abort
import json
from flask_restful import Api, Resource

# init app
app = Flask(__name__)
api = Api(app)


# Using External Local Data
with open("books.json") as f:
	books = json.load(f)

# Create Resource Class
class Books(Resource):
	def get(self,title):
		book = [book for book in books if book["title"] == title ]
		if len(book) ==0:
			abort(404,"Book with title::{} does not exit".format(title))
		return jsonify({"books":book})

class BooksList(Resource):
	def get(self):
		return jsonify({"books":books})

# Get All Books
api.add_resource(BooksList,'/api/v1/books')	

# Get Book By Title
api.add_resource(Books,'/api/v1/books/')


@app.route('/')
def index():
	return 'API Tutorials with Flask.eg /api/v1/books to see books'


# Using JSONIFY ERROR
@app.errorhandler(404)
def not_found(error):
	return make_response(jsonify({'error':'Not Found'}),404)

if __name__ == '__main__':
	app.run(debug=True)

 

With FastAPI , you can check for the openapi format of the documentation or the redoc format by adding docs and redoc to the endpoint respectively.

For Swagger UI

http://127.0.0.1:8000/docs

For the Redoc
http://127.0.0.1:8000/redoc

You can check out the video tutorial here.

Thanks For Your Time

Jesus Saves

By Jesse E.Agbe(JCharis)

4 thoughts on “Building APIs(Application Programming Interface) – Using Flask, FastAPI and Nodejs”

  1. Hi there! I’ve watched a couple of your Streamlit videos and I’ve recently discovered FastAPI as well. Would you mind explaining to me what the difference is between these two frameworks? I know that Streamlit seems to be more targeted to ML/Data Science applications/dashboards, but you also have several examples where you use FastAPI to create ML/Data Science APIs.

    Would you use these two together?
    Or would you pick one over the other?
    FastAPI is purely for back-end, right? I’d still have to build a front-end for it, correct?

    Thanks in advance for clarifying for me! You’re really highlighting some cool tools for Python so keep up the great work!

    1. Hello Gaylon,both are great frameworks but for different purposes. Streamlit is for building ML/Data Science Apps and Web Apps, whilst FastAPI is usually used for REST APIs but it can be used to serve your ML models as API as in the video tutorials.
      With FastAPI you can use normal html templates to design the front-end in case you want to add a front-end other than the Open Swagger UI.
      Hope it helps.

Leave a Comment

Your email address will not be published. Required fields are marked *