Skip to main content

FastAPI

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. FastAPI is very fast due to its out-of-the-box support of the async feature of Python 3.6+.

Image Source:- FastAPI

FastAPI was released in 2018, and it was created by Sebastián Ramírez. Ramírez was unhappy with existing frameworks like Flask and DRF, so he created his own framework using tools like Starlette and Pydantic. Now, many big tech companies like Uber, Netflix, and Microsoft are using FastAPI to build their apps.

FastAPI Features

  • High-performance:- As the name suggests, FastAPI is fast. It’s considered to be one of the fastest Python frameworks currently available.
  • Robust::- We can create production-ready code using automatic interactive documentation.
  • Intuitive:- FastAPI was designed to be easy to use and learn. It offers great editor support and documentation.
  • Quick to code:- FastAPI increases your developing speed by 200%-300%.
  • Less bugs:- Reduce about 40% of human (developer) induced errors.
  • Easy:- Designed to be easy to use and learn. Less time reading docs.
  • Short:- Minimize code duplication. Multiple features from each parameter declaration. Less bugs.
  • Standards-based:- Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.
  • Plugins:- You can easily create plugins using dependency injection.
  • Type hints:- You can use type hinting for data validation and conversion.

Advantages of FastAPI

  • Data validation:- It validates your data type even in nested JSON requests.
  • Exception handling:- With FastAPI, it’s easy to do exception handling.
  • Asynchronous code support:- It supports async code using the async/await Python keywords.
  • GraphQL support:- FastAPI makes it easy to build a GraphQL API with a Python library called graphene-python.
  • Great documentation:- Of course, a great framework cannot truly shine without an equally great documentation. Django, Flask and all the others excel in this aspect, but FastAPI is on par with them.

Disadvantages of FastAPI

  • Request validation:- FastAPI uses Pydantic for request validation. This process isn’t always very intuitive, and it sometimes requires you to write your own custom validator.
  • Smaller community:- Since the framework is still pretty new, the community is smaller in comparison to other frameworks.

Use Cases

FastAPI is commonly used for projects such as:

  • Internal crisis management.
  • Deploying machine learning models.
  • Create accounts, logins, and authentication for web applications.

Installation

$ pip install fastapi

FastAPI Hello World

Let’s get some practice with FastAPI! We’ll take a look at a simple Hello World! and break down the pieces.

1. from fastapi import FastAPI
2.
3. app = FastAPI()
4.
5. @app.get("/")
6. def root ():
7. return {"message": "Hello World!"}

We'll also need an ASGI server, for production such as uvicorn.

$ pip install uvicorn

To start the server, we need to run the following command:

uvicorn main:app --reload

Let’s break this down:

  • main:- refers to the file name
  • app:- refers to the object of FastAPI created inside the hello.py file
  • --reload:- parameter that makes the server restart after the code changes

Let’s break down our Hello World! code:

  • Line 1:- We import FastAPI, which is a Python class that provides all the functionality for the API.
  • Line 3:- We create an instance of the class FastAPI and name it app. This is the app referred to by uvicorn in the above command.
  • Line 5:- We create a GET path.
  • Line 6:- We define the function that will execute whenever someone visits the above path.
  • Line 7:- We return a response to the client whenever the route is accessed.

Basic FastAPI building blocks

Let’s explore some of the building blocks of FastAPI, including path parameters, query parameters, and request bodies.

Path parameters

Path parameters help scope the API call down to a single resource, which means we don’t have to build a body for something as simple as a resource finder.

These parameters are enclosed in curly brackets {}, and they offer a way for us to control the representation of specific resources. They’re placed before the query string and within the path of an endpoint.

Let’s take a look at how to use them:

1. from fastapi import FastAPI
2.
3. app = FastAPI()
4.
5. @app.get("/courses/{course_name}")
6. def read_course(course_name):
7. return {"course_name": course_name}

The value of the path parameter course_name will be passed to the function read_couse() as the argument course_name.

Query parameters

Query parameters are optional. In FastAPI, function parameters that aren’t declared as part of the path parameters are automatically interpreted as query parameters.

Let’s look at some sample code:

1. from fastapi import FastAPI
2.
3. app = FastAPI()
4.
5. course_items = [{"course_name": "Python"}, {"course_name": "SQLAlchemy"}, {"course_name": "NodeJS"}]
6.
7. @app.get("/courses/")
8. def read_courses(start: int, end: int):
9. return course_items[start : start + end]

The query is the set of key-value pairs that comes after the question mark ? in a URL, separated by an ampersand &.

Take a look at the following URL:-

http://localhost:8000/courses/?start=0&end=10

Its query parameters are:

start with a value of 0 and end with a value of 10.

In line 8 of the code, we pass the two query parameters that our API would expect.

Request body

A request body is data sent by the client to your API. To declare one in FastAPI, we can use Pydantic models.

Let’s see an example of how we can do this:

1.  from typing import Optional
2. from fastapi import FastAPI
3. from pydantic import BaseModel
4.
5. class Course(BaseModel):
6. name: str
7. description: Optional[str] = None
8. price: int
9. author: Optional[str] = None
10.
11. app = FastAPI()
12.
13. @app.post(“/courses/”)
14. def create_course(course: Course):
15. return course

Let’s break this down:

  • Lines 1-3:- We import the required packages.
  • Line 5:- We declare the request data model.
  • Line 11:- We create an instance of the FastAPI class.
  • Line 13:- We create a POST path.
  • Line 14:- We add the request data model to the path.

FastAPI is a lighter web framework for Python. FastAPI is perfect if you’re looking for speed or scalability. It allows you to build APIs easily, quickly, and efficiently. If you’re interested in web application development, learning FastAPI will put you ahead of the curve.

REFERENCES:-