Running Your First FastAPI Application

Running Your First FastAPI Application

Welcome to the first lesson of our FastAPI for Beginners course! We're thrilled to have you here. By the end of this lesson, you will be able to set up a FastAPI application and run it on your local server — a crucial first step in creating web APIs. So, whether you're a seasoned developer exploring new frameworks or a complete beginner embarking on your programming journey, we've got you covered. Let's dive in and start building with FastAPI! ⚡

What is FastAPI?

FastAPI is a Python web framework that allows you to build APIs quickly and efficiently. It's built on top of other robust libraries like Starlette for the web parts and Pydantic for the data handling. One major advantage of FastAPI is that it uses Python type hints. These type hints not only allow for better editor support but also provide data validation, serialization, and documentation.

Comparatively, though Flask and Django also allow for API building, FastAPI often outstrips them in terms of speed and ease of use. That's why many people, specially beginners to back-end engineering, chose to learn FastAPI to turn their project into reality.

Required Libraries

Before we dive into building your FastAPI application, let's explore the libraries we'll be using: fastapi and uvicorn.

  1. fastapi: This is the core library that provides all the functionalities for building APIs.

  2. uvicorn: This is an ASGI (Asynchronous Server Gateway Interface) server used to run your FastAPI applications. It serves as the bridge between your FastAPI app and the web.

To install these libraries, if you are working on your local machine, you can use the following pip commands:

pip install fastapi
pip install uvicorn

If you are using the CodeSignal environment provided for this course, there's no need to install any libraries as they are already pre-installed. You can jump straight into coding!

Setting up Your First FastAPI Application

Building a FastAPI application starts with a simple script. At its most basic, a FastAPI app involves importing the FastAPI class and creating an instance of this class. Observe the following code:

# Import FastAPI class
from fastapi import FastAPI

# Initialize a FastAPI app instance
app = FastAPI()

In this simple script, we first import the FastAPI class from the fastapi module. Then, we create an instance of this class and assign it to a variable. While you can name this variable whatever you want, it's generally accepted to use app. That's it! You've just created your first FastAPI application.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal