An Introduction to FastAPI, a Powerful Python Framework

What is FastAPI ?

FastAPI is another Python framework is modern, and fast which means high-performance web framework for building an API in python.

Features

  • High Performance
  • Increase the speed to develop features
  • Editor support
  • Provide multiple parameter declarations for minimum code duplication
  • Production interactive documentation
  • Compatible with open standard API like Swagger, JSON etc
  • Compatible with fully Starlette
  • Pydantic Feature

How to Install FastAPI?

Let’s start (Hope you know basics of python project setup)

1. Basic Prerequisite for Project

  • Create a Repository on github/bitbucket/gitlab as per your choice and Clone repository.
  • Install virtual environment and activate

2. Installation

  • Pip install fastapi
    As fastapi supports asgi server for production such as Uvicorn or Hypercorn
  • Pip install “uvicorn[standard]”
    You can install like this also $ pip3 install fastapi uvicron

    Installation of fast API
    Installation of Fast API

Now we are moving towards to create basic functions/ classes in FastAPI so let’s start, considering we have basic knowledge of how to write function/classes in python etc

Create First API

Create a file called main.py , add basic code and run it
main.py

from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello World"}

Lets’ understand the code firstly import the FastAPI then create an object of FastAPI, this is the main point of interaction to API then for run application

$ uvicorn main:app –reload

Creation of First API

  • Main.py is python file
  • app is object which created of FastAPI in code
  • –reload : load server after changes , this only for development
  • In output shows running server url
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
  • Output with interactive documentation
  • FastAPI Swagger UI : http://127.0.0.1:8000/doc

example of FastAPI Swagger UI

  • Alternatively UI Doc : http://127.0.0.1:8000/redoc

Alternate Example of FastAPI Swagger UI

Another important point is communication with API using HTTP methods like GET, POST, PUT, PATCH, DELETE , HEAD, TRACE, OPTIONS.
The above example tells FastAPI to do a GET operation with the path using @app.get(‘/’) likewise other operations also can be done @app.post(), @app.put(), @app.delete() etc.
You can define function as async function instead of normal function.

PATH Parameter : Get ID of Item

You can declare parameter as you declared formatted string

@app.get("item/{item_id}")
def read_item_by_id(item_id):
return { "item_id": item_id}

The value of the path parameter item_id will be passed to your function as the argument item_id.
So, if you run this example and go to http://127.0.0.1:8000/items/arti, you will see this response:

Example of response

1. Path Parameter with Types

You can declare the type of parameter in function using python standard types

Type of Parameter

2. Data Validation

If we pass wrong data it will display errors. FastAPI do data parsing and data Validation both

Example of data validation

Interactive documentation

Interactive documentation of data validation

3. Data Handling with Pydantic

All data validation is done by Pydantic in FastAPI. Usage of Pydantic in defining model , Field types, Validators, allows to create schema for JSON type data , Decorators , setting management , data class integration , data type declaration and so on.
Mainly the Pydantic is use of Data validation in FastAPI.

Request Body (JSON): Pydantic

When we send data to API is send as request body to API to perform operation and with the we are configuring which HTTP methods used for perform operation like GET,POST,PUT etc

1. Model

For model we are going to use Pydantic so we need to import these Pydantic as BaseModel from it and create subclasses by define schema or data shapes as you want.
After that inherit BaseModel to create class.
If we made any mistake while defining a model then it will show error.

MODEL OF REQUEST BODY

If we define default values of model attributes then no else is required to send. We can skip optional value to send suppose we send following object

{
"first_name": "arti",
“last_name”: “khot”
"description": "An optional description",
"email":”arti@yopmail.com”,
}

2. Use Pydantic to Declare JSON Data Models

Now we add this model where we need to perform operations like we defined path parameter you can declare in same as path parameter

@app.post("/items")
def create_item(item:Item):
return item

The parameter item has type of Item, which means that item is declared as an instance of the class Item.
With that Python type declaration, FastAPI will:

  • JSON as request Body
  • Convert the corresponding types if needed as per conversion
  • Validate the data and return a clear error if it is not valid data defines
  • Generate JSON Schema definitions for your model that you can also use anywhere else that makes sense for your project
  • Inside function you can directly access all parameter as you need and perform operations

By using standard type hints with Pydantic, FastAPI helps you build APIs that have all these practices by default with the help of editor, with little work or effort.

Example of Use of Pydantic to Declare JSON Data Models

3. Use Pydantic Model

We can do operation as we want

@app.post("/items/")
def create_item_param(item: Item):
item_dict = item.dict()
if item.first_name and item.last_name:
detail = item.first_name + item.last_name + " tetsing data"
item_dict.update({"description": detail})
return item_dict

Use of Pydantic Model

 

coma

Conclusion

In this way we learned the basics of FastAPI where now we know how we can pass parameters to get a unique URL path per item .
It combines async programming, automatic validation, and interactive documentation to streamline development. With strong typing and extensive ecosystem integration, FastAPI offers a modern and efficient solution for creating reliable APIs. Also we know how to use JSON data on request with Pydantic.
In the next tutorial we will see about classes with basic operations like login , Authentication, logout etc.

Keep Reading

Keep Reading

Leave your competitors behind! Become an EPIC integration pro, and boost your team's efficiency.

Register Here
  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?