A REST API is an architectural pattern for creating web services. REST is a set of rules that outlines the best practices for sharing data between clients and servers. They use HTTP requests to manipulate data and communicate with web services. REST APIs are stateless, cacheable, and consistent. They’re great for building general-purpose and scalable web applications. The three major Python frameworks are Django, Flask, and FastAPI.
Today, we’re going to explore FastAPI, an open-source web framework used to build APIs with Python.
Get hands-on with FastAPI
Learn the basics of FastAPI applications with interactive exercises.
Build a REST API Using Python and Deploy it to Microsoft Azure
The official FastAPI website describes FastAPI as a modern and 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+.
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 has many great features. Let’s take a look at them:
High-performance: As the name suggests, FastAPI is fast. It’s considered to be one of the fastest Python frameworks currently available.
Robust: You 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%.
Fewer bugs: It reduces around 40% of induced bugs.
Compatible: It works well 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.
In this section, we’ll explore Flask and FastAPI. We’ll discuss their pros, cons, and use cases.
Flask is a Python microframework. It comes with ORM, caching, and authentication. It was designed to build web applications using Python. It’s considered to be easy, fast, and scalable.
Pros
Cons
Use cases
Flask is commonly used for projects such as:
FastAPI is a modern, high-performance web framework. It’s used to build web APIs.
Pros
async/await
Python keywords.Cons
Use cases
FastAPI is commonly used for projects such as:
Let’s get some practice with FastAPI! We’ll take a look at a simple Hello World!
and break down the pieces.
from fastapi import FastAPIapp = FastAPI()@app.get("/")def root ():return {"message": "Hello World!"}
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 nameapp
: refers to the object of FastAPI
created inside the hello.py file--reload
: parameter that makes the server restart after the code changesLet’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.
Get started with Python FastAPI without scrubbing through videos or documentation. Educative’s text-based courses are easy to skim and feature live coding environments, making learning quick and efficient.
Build a REST API Using Python and Deploy it to Microsoft Azure
Let’s explore some of the building blocks of FastAPI, including path parameters, query parameters, and request bodies.
Path parameters help scope the API call down to a single resource, which means you 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 you 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:
from fastapi import FastAPIapp = FastAPI()@app.get("/courses/{course_name}")def read_course(course_name):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 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:
from fastapi import FastAPIapp = FastAPI()course_items = [{"course_name": "Python"}, {"course_name": "SQLAlchemy"}, {"course_name": "NodeJS"}]@app.get("/courses/")def read_courses(start: int, end: int):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.
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:
from typing import Optionalfrom fastapi import FastAPIfrom pydantic import BaseModelclass Course(BaseModel):name: strdescription: Optional[str] = Noneprice: intauthor: Optional[str] = Noneapp = FastAPI()@app.post(“/courses/”)def create_course(course: Course):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.
Congrats on taking your first steps with FastAPI! FastAPI is a lighter web framework for Python. 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. To get comfortable with the framework, we suggest you dive deeper into the framework and work on some projects.
Some recommended topics to cover next are:
To get started learning these concepts and more, check out Educative’s course Build a REST API Using Python and Deploy it to Microsoft Azure. In this course, you’ll learn how to build a REST API in Python using FastAPI and deploy you API on Microsoft Azure. By the end, you’ll be able to implement FastAPI into your own projects.
Happy learning!
Free Resources