rest api with flask

REST API With Flask

Create A REST API In Python Flask

In this article, we shall create a REST API with Flask and then deploy it to Heroku.

What is REST API and Why do we need Rest API?

Let us look into an example before proceeding with REST API. Suppose you need to get a information related to latest Anime news. You search related to it from your web browser. And a server gives a response to your search request. An application programming interface (API) plays an important role here. API acts as an interface between server and client. We shall look about the working later. REST stands for Representational State Transfer, which is a client-server structure that is based on a request/response design. REST APIs are built to take advantage of pre-existing HTTP protocols.

Let’s say you are building an application in Python. Using Python you have saved the important data into the database. Now when some other guy needs to form on that data but is not familiar with Python but good n JavaScript, then he/she could use the API to access the data. REST APIs act as transfer data. It uses HTTP protocol to convey data in several data formats (like XML and JSON) which ensures a quick process.

Suppose you want to watch One Piece on Crunchyroll. You go toCrunchyroll and search One Piece. Now you get a list of all episodes. A REST API works similarly, you request for the endpoint, to which you get back the response from the server, let’s see how it works. 🤫

How do Rest API work?🤔

rest api with flask_python

A REST API is essentially a way how machines or applications can talk to each other. A client i.e., the web browser tries to communicate with the server by sending it a request. In the communication between the client and server API acts as an intermediate. On receiving the request server then sends back the response to the client. The most common output format of the REST API is JSON(JavaScript Object Notation). The structure of JSON looks similar to objects in JavaScript:

{  
  "id": 2,  
  "name": "Code Geass",  
  "description": "A high-schooler who's granted Geass powers to make anyone instantly obedient dons a mask to lead Japan's rebellion against a long-invading Britannia",  
  "genre": "fantasy, thriller"
}

The REST API uses the HTTP requests method to make the communication i.e., receive and response functionality. These HTTP requests include GET, POST, PUT, and DELETE. Now suppose you have more Anime API data in JSON form just like the above example. In order to retrieve the response, we request the server with the help of the API GET endpoint: https://animevyuh.org/api/animes/7. Here are getting data with help of /api/animes/<id> endpoint.

We are now sending the request for Anime details with id 7. To this server shall provide the response in JSON form. Sample response output:

{  
  "id": 7,
  "name": "Mushishi",
  "description": "Ginko a mushi master travels across the cities to cure people that are affected by creature named Mushi.",
  "genre": "slice of life, adventure"
}

The POST request method is used to add/insert new data into the database. A PUT request is used to update the data and a DELETE request is used to remove the specifically requested data from the database. Don’t worry we shall look into this in detail with code examples using Python. I hope you have some idea of how API works. These HTTP requests are pretty useful to perform CRUD operations. C stands for create, R- Read, U- Update, and D- Delete.

Example

Some of the best examples include YouTube API, Twitter API, Facebook API, Twilio (communications API), Stripe (payments API), Sendgrid (email API), and so on.

Advantages Of REST API:

  • Lightweight
  • Stateless
  • Layered System
  • Human Readable Results
  • No Toolkit required.

Let us create a REST API using Python Flask.😊

Create A REST API With Flask Python

Flask is a lightweight Python web Framework. We shall create our own Rest API using Python Flask. SQLAlchemy is a library that facilitates the communication between Python programs and databases. This article presumes you are familiar with both Python and Flask.

SQLAlchemy In Flask

First, let us create a database model to save all the Anime details. We create an SQLite database that is very much similar to MySQL. Once you import SQLAlchemy from flask_sqlalchemy, create a Class to initialize the database model. db.Column creates the table for us, id is an integer value and we assign it to be the primary key.

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///anime.db'
db = SQLAlchemy(app)

class Anime(db.Model):
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(80),unique=True,nullable=False)
    description = db.Column(db.String(150),nullable=False)
    genre = db.Column(db.String(50),nullable=False)

Main App Code

Now let us create the home page and render the index.html template.

@app.route('/')
def index():
    return render_template('index.html')

Since Anime is the database model, we can loop those to the entire query and return the jsonify form of the database query.

@app.route('/api/animes')
def display_name():
    anime_name = Anime.query.all()
    store_data = []
    for data in anime_name:
        store_data.append({"anime name":data.name,"description":data.description,"genre":data.genre})
    return jsonify({"animes":store_data})

HTTP Requests: CRUD Operation

C – CREATE🥶

We shall create an HTML form and use the POST method to add/create new data in our database.

Syntax to add new data to the database:

add_details = Anime(name=get_name,description=get_desc,genre=get_genre)
db.session.add(add_details)
db.session.commit()

With help of the flask request method, we receive the data that is submitted through the form. Since the HTML form uses the POST method, using the name attribute of the form input tag, we add these details to our database:

@app.route("/addanime",methods=['POST','GET'])
def post_animename():
    if request.method == "POST":
        #retrieve form data from name attribute
        get_name = request.form['animename'].lower().strip()
        get_desc = request.form['description'].lower().strip()
        get_genre = request.form['genre'].lower().strip()
        
        #create the database
        db.create_all()
        #declare the receieved data to database model i.e., Anime
        add_details = Anime(name=get_name,description=get_desc,genre=get_genre)
        db.session.add(add_details)
        db.session.commit()
        flash("Successfully Added")
        return redirect(url_for('index'))
    else:
        return render_template('add.html')

This is how HTML forms look like:

We have two input tags for text to add name and genre. And we have a text area to add descriptions and finally a submit button.

<form method="POST">
        <div class="form-group">
          <label for="animeBoy">Enter Anime Name</label>
          <input type="text" name="animename" class="form-control" id="exampleFormControlInput1" placeholder="Enter Anime Name" required>
        </div>
        <div class="form-group">
          <label for="exampleFormControlTextarea1">Enter Description</label>
          <textarea class="form-control" name="description" id="exampleFormControlTextarea1" rows="3" required></textarea>
        </div>
        <div class="form-group">
            <label for="genrebased">Enter Anime Genre</label>
            <input type="text" name="genre" class="form-control" id="exampleFormControlInput1" placeholder="Enter Genre" required>
          </div>
          <input type="submit" name="btn" value="Add">
</form>

R- Read🔥

Now we perform the GET method, here user enters the endpoint by adding an id number to retrieve the specific Anime information.

Syntax: display_id = Anime.query.get_or_404(id)
@app.route("/api/animes/<id>")
def get_anime_by_id(id):
    #get the id data
    display_id = Anime.query.get_or_404(id)
    return {"anime name":display_id.name,"description":display_id.description,"genre":display_id.genre}

Handling 404 Error In Flask💀

Give the user a direction when he/she encounters a 404 error in Flask. The URL endpoint to be added here is@app.errorhandler(404).

@app.errorhandler(404)
def not_found(error):
    return """
    <h2>Seems Like You Are Lost</h2>

    <a href="/api/animes">Click here to check all Anime List API</a><br/>
    <a href="/addanime">Add new Anime</a><br/>
    <a href="/">Home</a>
    """, 404

Putting In All Together

from flask import Flask,render_template,flash,request,redirect,url_for,jsonify
from flask_sqlalchemy import SQLAlchemy
import os

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///anime.db'
app.secret_key = os.urandom(16)

db = SQLAlchemy(app)

class Anime(db.Model):
    // config the SQLAlchemy database model
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(80),unique=True,nullable=False)
    description = db.Column(db.String(150),nullable=False)
    genre = db.Column(db.String(50),nullable=False)

    // a representation model to provide the meaning when user checks the data
    def __repr__(self):
        return f"Name of the Anime:{self.name}\nDescription:{self.description}"

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/animes')
def display_name():
    anime_name = Anime.query.all()
    store_data = []
    for data in anime_name:
        store_data.append({"anime name":data.name,"description":data.description,"genre":data.genre})
    return jsonify({"animes":store_data})

@app.route("/api/animes/<id>")
def get_anime_by_id(id):
    display_id = Anime.query.get_or_404(id)
    return {"anime name":display_id.name,"description":display_id.description,"genre":display_id.genre}

@app.route("/addanime",methods=['POST','GET'])
def post_animename():
    if request.method == "POST":
        get_name = request.form['animename'].lower().strip()
        get_desc = request.form['description'].lower().strip()
        get_genre = request.form['genre'].lower().strip()
        db.create_all()
        add_details = Anime(name=get_name,description=get_desc,genre=get_genre)
        db.session.add(add_details)
        db.session.commit()
        flash("Successfully Added")
        return redirect(url_for('index'))
    else:
        return render_template('add.html')

@app.errorhandler(404)
def not_found(error):
    return """
    <h2>Seems Like You Are Lost</h2>

    <a href="/api/animes">Click here to check all Anime List API</a><br/>
    <a href="/addanime">Add new Anime</a><br/>
    <a href="/">Home</a>
    """, 404

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

Conclusion

We finally have our Rest API Flask Application ready🔥. Its time to deploy the restful API Python Flask app on Heroku. Check out part 2 of this article to deploy the app on Heroku: Article Link To Deploy🚀

In this article we performed Create and Read i.e., GET and POST method, in the next article we shall implement Update and Delete request methods. To stay tuned to our content: Subscribe to our newsletter to get updates.

Newsletter: https://animevyuh.org/newsletter/

If you like our content support us: Buy Me A CoffeeKo-Fi

1 thought on “REST API With Flask”

  1. Pingback: Deploy A Flask App On Heroku

Comments are closed.