How to create a Flask Rest API (CRUD)
Rest API is an acronym that represents representational state transfer, its used for communication to the frontend of both websites, web applications,s or an app both mobile or desktop building a rest API application you can use other stacks like nodejs (Javascript), Laravel(PHP), Django(Python), Flask(Python), C#(.Net), Springboot(Java). Building an API there basic thing we need to consider while building an API which is the choice of the database there is a basic database structure we need to understand which is NoSQL and SQL ie. don’t worry I will write on that one later for this application we will leverage the power CRUD which is created, read, update and delete which is Get, Put, Update and Delete. Working with a rest API you will need a certain software or extension like postman, insomnia and many others as an application and thunder client as a vs code extension
This tutorial will talk about how to work on a crud application we are building a drink API first thing you need to do while working on a flask rest API application we need to create a basic flask server by importing flask
from flask import Flask
app = Flask(__name__)
@app.route(“/”)
def index():
return “Welcome”
if __name__ == “__main__”:
app.run(debug=True)
The second part now is to create and initialize our database by importing sqlalchemy
from flask_sqlalchemy import SQLAlchemy
app.config[“SQLALCHEMY_DATABASE_URI”] = “sqlite:///data.db”
db = SQLAlchemy(app)
now lets create our model a model is a sequence of how our data is been stored in the database
class Drink(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
description = db.Column(db.String(120))
def __repr__(self):
return f”{self.name} — {self.description}”
after this step, we are about to generate our database in our project by opening our terminal to the exact path with the project we are working on now in the terminal now type in
from app import db
the app is the name of my application which is app.py if u use another name like main.py you will use
from main import db
and now type in this command
db.create_all()
And let's enter the first route which will display the home page
@app.route(“/”)
def index():
return “Welcome”
and the next one is the route that will list all the drinks
@app.route(“/drinks”)
def get_drinks():
drinks = Drink.query.all()
output = []
for drink-in drinks:
drink_data ={“name”: drink. name,” description”: drink. description }
output.append(drink_data)
return {“drinks”: output}
ok let me explain this code from the route statement
we create a route that takes us to the drink page,create a function called get_drinks() ie let it not be similar to the first route because if they have the same function the code will break. ok the next statement which is drinks = Drink.query.all() we create a variable drink and now query the database or to search what is inside the database now use the name we named our Model which is Drink and use the keyword Query.all() this function will search what is been stored in the database and now create a variable output with an empty array lets loop through the drinks to get data from the db and append it with the output which is the drink_data and output variable and lets now return our drinks with the output variable
out next route is to create a route that will get only one drink
@app.route(“/drinks/<id>”)
def get_drink(id):
drink = Drink.query.get_or_404(id)
return {“name”: drink.name, “description”: drink.description}
ok let me explain create a route with drinks with an id which is the number or a dynamic variable and create a function get_drink with id and we will now find only one object using this function drink = Drink.query.get_or_404(id) and we will now return the details which are being embedded with the id.
and the next one is to post or add new information to the database
@app.route(“/drinks”, methods=[“POST”])
def add_drink():
drink = Drink(name= request.json[“name”], description=request.json[“description”])
db.session.add(drink)
db.session.commit()
return {“id”: drink.id}
ok let me explain first create a route leading to drinks with a method post create a function get_drink() and create a variable drink with the name of our model and we will now call out the details we gave to the model and will use request which is imported from the flask module from flask import Flask, request we will now add and save our information using session, add and commit
and our last one is the delete route which is
@app.route(“/drinks/<id>”, methods=[“DELETE”])
def delete_drink(id):
drink = Drink.query.get(id)
if drink is None:
return {“error”: “Not found”}
db.session.delete(drink)
db.session.commit()
return {“Message”: “deleted”}
let me explain the code
create a route with drinks and is and a method delete
query the information with the query keyword to get the id
now iterate the drink to check if the information is deleted or it is not found now use session. delete to delete the information from the table and lastly save the action
check the code here https://github.com/rodeok/flask_api12