FAST API - CRUD APPLICATION (Tutorial)

 

In this article I am giving a tutorial about how to create a simple CRUD application using python fast-API framework. In this tutorial I’m going to create a simple blog application, users will be able to


Write their blogs,

Read blogs

Update blogs

Delete blogs


Requirements:

1.CREATING THE VIRTUAL ENVIRONMENT:

Before you create a project you need a virtual Environment to isolate the code from the other projects and for the security.

You can create a virtual environment by using the following syntax,

            Python –m  venv environment_name

This will create a folder/directory with the environment name.

 

You can activate the virtual environment .

              Environment name/scripts/actiavte

You can see the result once it is activated.

Output:

PS C:\Users\sugum\OneDrive\Desktop\myfastapi> myfastapi/Scripts/activate

(myfastapi) PS C:\Users\sugum\OneDrive\Desktop\myfastapi>  

 

2.Installing FAST API:

We can  install fastapi package using the below syntax,


                       pip install fastapi

We will need an ASGI (Asynchronous Server Gateway Interface) server, in this case we will use unicorn.
                        pip install uvicorn

After installing the fast API let us head over the development.

3.Creating a basic API:

Create a python folder called main.py inside the project folder then write the code below to create a basic api.

from fastapi import FastAPI

#initailize FastApi instance

app = FastAPI()

#define endpoint

@app.get("/")

def home():

    return {"blog:demo"}

To run this, execute this from your command line/terminal:
              uvicorn main:app reload


main: refers to the name of our entry point
app: refers to the fastAPI instance that we initialized from main.py
--reload: is a flag that allows the server to reload itself when we make changes to the project.

Open your browser at link
For automatic Interactive API Docs:

  • http://127.0.0.1.8000/docs-> provided by SwaggerUI
  • http://127.0.0.1.8000/redoc -> provided by Redoc

 

4.Designing The App:

As a user I want to be able to create, read, update, and delete blogs. So, we should probably have five endpoints like

functionality

create a blog

read a blog

update a blog

delete a blog

read all blog

The type of operation we’re performing dictates which HTTP method should use. For example, our endpoint for reading a blog should use an HTTP GET method. Our endpoint for deleting a blog item should use an HTTP DELETE method.

functionality

method

create a blog

POST

read a blog

GET

update a blog

PUT

delete a blog

DELETE

read all blog

GET

POST is used to a create a new database record and PUT is used to update an existing database record.  

We should define the path for each operations like follow,

functionality

method

path

create a blog

POST

/blog

read a blog

GET

/blog/{id}

update a blog

PUT

/blog/{id}

delete a blog

DELETE

/blog/{id}

read all blog

GET

/blog

We can actually implement different logic for the same URL path, depending on the HTTP method used. Like a PUT call to /blog/{id} will update the data inside the specific blog while DELETE call to /blog/{id} will delete the blog.

Let us write a code for a demo application to check the operations,




Creating Database:

We use sqlite database to store the data ,to speak with the database we use a ORM -object relational mapper called SQLalchemy

First, let’s install sqlalchemy with

                 pip install sqlalchemy.

Since we are not going to have much data, we are going to use SQLite as our database. SQLite is an inbuilt python library, so we do not need to install it.
Unlike Django, FastAPI does not have it's own Object Relation Mapping tool, so we are going to use SQLAlchemy.

SqlAlchemy Engine

Then we’ll need to create an Engine instance. An Engine tells sqlalchemy

  1. what type of database you’re connecting to
  2. where that database is located
  3. what your credentials are for connecting to the database
  4. lots of other stuff,

so create a file called db.py and write the code below to create a database,



It will create file named blog.db inside the project folder. , we imported three items from SqlAlchemy then we connected the database using the url, if we used different database we connect that using port ,ip address, user id, password .Base is used for performing the operation ,you can set set auto commit in true also.

Creating the models:

For creating the models create a python file called models.py and write the code below,

I just imported the Base from the db.py and imported the required data fields to create the models from the sqlalchemy then created a class called blog and a table called blogs.

 


then make some additions to the main.py file,


CRUD Operations:

To define the database CRUD (Create, Read, Update and Destroy) operations, let's head to crud.py and write the following,


Define Endpoints:

We are almost done. Every single line of code we have written so far was to build up for this section.

Let's head back over to main.py:
add the following after where you initialized your FastAPI instance

from app.db import SessionLocal
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


SessionLocal is the connection to our db.
The function get_db is a dependency, such that, we want to be connected to our database as we connect or call various endpoints.

Let us see this in use with our first endpoint. Add this to main.py

 


after running the server go to the auto docs and create a blog Fill in the fields and click on the blue Execute button.



Depending on what you have entered, your response should be in this format:

                  


We can see that response  Let us now add other endpoints for each of our remaining CRUD operations.

Get a blog object:


list all blogs:



update a blog:


delete a blog:




 

Comments

Popular posts from this blog

Oracle Database Server Architecture: Overview

Oracle E-Business Suite (EBS) - Introduction

Why enterprises must not ignore Azure DevOps Server