Skip to main content
Create RestAPI Using Python fastapi

Create Rest API Using Python Fastapi

This tutorial help to create rest API with fastapi and CRUDRouter.The fastapi is the fastest python API framework. We will create a CRUD API Using the python fastapi framework.

Whats’s Fastapi Framework

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.

The main features of fastapi:

  • Very high performance
  • Easy to use and learn
  • Get code that’s ready for production. With interactive documentation that is generated automatically.
  • Generating dynamically open API standards docs.

You can also checkout other python API tutorials:

How To Create RestAPI Using Fastapi

Let’s create CRUD operation using rest API through fastapi framework. I am creating CRUD api for the employee module. We’ll generate a listing of employees, add a new record, update a record and delete an employee.

The default routes for CRUD Operation:

RouteMethodDescription
/GETGet all the resources
/POSTCreate a new resource
/DELETEDelete all the resources
/{id}GETGet an existing resource matching the given id
/{id}PUTUpdate an existing resource matching the given id
/{id}DELETEDelete an existing resource matching the given id

Dynamic Generating CRUD routes Using CRUDRouter

The FastAPI-CRUDRouter is lighting fast, well tested, and production-ready libs to generate routes. The FastAPI CRUDRouter will automatically generate and document your CRUD routes for you. You can pass your model and maybe your database connection..

Install Dependencies

We’ll install the following dependencies into this tutorial:

Install fastapi:

$ pip install fastapi

installing crudrouter:

$ pip install fastapi_crudrouter

You will also need an ASGI server, for production such as uvicorn.

$ pip install uvicorn

Now You can create a main.py file and added below code into this file:

from fastapi import FastAPI
from pydantic import BaseModel
from fastapi_crudrouter import MemoryCRUDRouter

app = FastAPI()

class Emp(BaseModel):
    id: int
    name: str
    age: int
    salary: float

router = MemoryCRUDRouter(schema=Emp)
app.include_router(router)

@app.get("/")
def read_root():
    return {"Hello": "World"}

The above code has the following steps:

  • Import all dependencies packages.
  • Created FastAPI instance.
  • Defined employee Model class
  • I am using MemoryCRUDRouterfor store temporary data into the memory.
  • included routed with fastapp.

The above code is generating all crud operations and you can access using the below URL in the browser:

https://127.0.0.1:8000/emp/

Interactive API docs

Now go to https://127.0.0.1:8000/docs.

You will see the automatic interactive API documentation (provided by Swagger UI):

fastapi-swagger-docs

Leave a Reply

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