Python REST API tutorial: Getting started with FastAPI (https://www.educative.io/blog)
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.
Let’s get started!
We’ll cover:
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
What is FastAPI?
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 features
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.
Flask vs FastAPI
In this section, we’ll explore Flask and FastAPI. We’ll discuss their pros, cons, and use cases.
Flask
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
- Flexible: You can manipulate most aspects of Flask.
- Intuitive: Flask is great for beginners because of its simplicity.
- Built-in development server: This built-in functionality, along with its integrated support, allows for seamless unit testing.
Cons
- No data validation: With Flask, you can pass any data type. This can cause programs to crash often.
- Time: It has a single source that handles requests in turns, meaning that it can take some time for requests to be addressed.
Use cases
Flask is commonly used for projects such as:
- E-commerce systems
- Social media bots
- Social networks
- Static websites
FastAPI
FastAPI is a modern, high-performance web framework. It’s used to build web APIs.
Pros
- 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.
Cons
- 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
To start the server, we need to run the following command:
Let’s break this down:
main
: refers to the file nameapp
: refers to the object ofFastAPI
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 itapp
. This is theapp
referred to byuvicorn
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.
Keep the learning going.
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
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 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:
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:
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:
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.
What to learn next
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:
- Parallel processing
- Deploying your API to the cloud using GitHub
- Default and optional parameters
- Etc.
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!
Comments