Flask API Using Python | Learn Python

Introduction

In this article, we are going to learn about flask API using the python code base. 

What is Flask and what is the difference compared to traditional API

Flask is a popular micro framework for building a web application. It's a python code base that takes less time to develop web applications compared to a conventional stack. On top of that, it's a lightweight library, so it doesn't have many external dependencies, it has a couple of dependencies such as the WSGI utility library and template engine. 

WSGI

The WSGI is a protocol, is used to communicate python applications into the web server.

Template engine

A template engine is nothing but it is used to set a basic layout of your web pages, which can be consumed across your application, for eg., Header, and footer pages common across the app.

Comparatively traditional, it's easy to develop and lightweight module, able to accommodate any environment. 

Who is using this API at this moment

More Data Science folks are using python, its suits them to easy to adapt this stack to their project. A few companies are using flask APIs such as Netflix, Uber, Samsung and Airbnb and etc.,

Prerequisite

Python available in your system 

Folder structure

  • API/api.py
  • API/mockup/books.json

How to Implement

pip install Flask
[
    {
      "id": 1,
      "title": "Basic Python learning in 30 days",
      "author": "Aravind"  
    },
    {
      "id": 2,
      "title": "API using Python",
      "author": "Aravind"
  
    },
    {
      "id": 3,
      "title": "Database Connection using Python",
      "author": "Aravind"
    }
  ]

File Name: app.py

import flask
from flask import request, jsonify
import os,json

app = flask.Flask(__name__)
app.config["DEBUG"] = True

# get books collection from mockup/ books.json

# Opening JSON file
mockup_json_path = '../api/mockup/'

json_file = open(mockup_json_path + "books.json")
books = json.load(json_file)


# Test Method - Health Check
@app.route('/', methods=['GET'])
def home():
    return 'I am up and running'


# Return all the books 
@app.route('/api/v1/books/all', methods=['GET'])
def api_all():
    return jsonify(books)

# Return book(s) based on Id
@app.route('/api/v1/books', methods=['GET'])
def api_id():
  
    if 'id' in request.args:
        id = int(request.args['id'])
    else:
        return "no id exists..."
    results = []
  
    for book in books:
        if book['id'] == id:
            results.append(book)

    return jsonify(results)

#this tag is used to run 
app.run()

Once done enter the below script in your command prompt, now you go copy and paste the listener link. your API is ready to go :)

python app.py

I hope this article gives an idea about python based API using the flask micro-library. Looking forward to see you all in next session.


Similar Articles