Home/Blog/Web Development/Python REST API tutorial: Getting started with FastAPI
Home/Blog/Web Development/Python REST API tutorial: Getting started with FastAPI

Python REST API tutorial: Getting started with FastAPI

7 min read
Jul 02, 2021

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

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

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

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.

from fastapi import FastAPI
app = 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 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.

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:

from fastapi import FastAPI
app = 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#

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 FastAPI
app = 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.

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:

from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
class Course(BaseModel):
name: str
description: Optional[str] = None
price: int
author: Optional[str] = None
app = 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.


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!

Continue reading about Python and APIs#


Written By:
Erin Schaffer
 
Join 2.5 million developers at
Explore the catalog

Free Resources