top of page

An Introduction to FastAPI - FastAPI Tutorial

Updated: Feb 5

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to be easy to use and to produce fast, highly efficient code. FastAPI is built on top of Starlette for the web parts and Pydantic for the data parts.




Exploring the key features highlighted in the original documentation:


  • Performance: FastAPI boasts high performance, comparable to NodeJS and the Go language. This ensures that applications built with FastAPI deliver efficient and responsive performance.

  • Speed: The framework accelerates development speed, boasting a 2-3 times improvement over traditional approaches. This is attributed to its simplicity, clear syntax, and adoption of modern asynchronous programming techniques.

  • Easy: FastAPI provides robust support within code editors, offering features like auto-completion throughout the development process. Its user-friendly design makes it accessible for developers, promoting a straightforward learning curve.

  • Robust: FastAPI supports the creation of production-ready code, ensuring applications are dependable and seamlessly transition into live environments. The framework also automatically generates interactive documentation, enhancing code understanding.

  • OpenAPI based: The framework fully aligns with OpenAPI and JSON Schema standards, ensuring compatibility with industry best practices for API design, development, and documentation. This compatibility promotes consistent and interoperable API development.




Setting Up a FastAPI Application: A Quick Start Guide

To get started with FastAPI, you can follow these steps for a quick setup:

Installing FastAPI

The commands pip install fastapi and pip install uvicorn are used to install the necessary Python packages—FastAPI and Uvicorn—required for developing and running FastAPI applications.


Open your terminal and run the following commands to install FastAPI and Uvicorn using pip:


# This command installs the FastAPI framework
pip install fastapi 

'''
pip install uvicorn: This command installs Uvicorn, which is an ASGI (Asynchronous Server Gateway Interface) server. Uvicorn is used to run FastAPI applications. It provides a lightweight and efficient server for handling asynchronous requests, making it well-suited for FastAPI's asynchronous capabilities.

'''
pip install uvicorn


These above commands ensure that the required dependencies (FastAPI and Uvicorn) are installed in your Python environment. Once installed, you can start building and running FastAPI applications using Uvicorn as the server.



Screenshot: fastapi installation successfully

In Python 3, the pip command is often associated with the Python 2 version. To avoid confusion and ensure that you are working with Python 3, it's recommended to use pip3 when working with Python 3.x installations


Screenshot: fastapi installation successfully
Screenshot: fastapi installation successfully

Create a FastAPI App:

Create a new Python file (e.g., main.py) and define a basic FastAPI application. For this example, let's create a simple app that returns "Hello, FastAPI!" when accessed.


# main.py

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello, FastAPI!"}



  1. from fastapi import FastAPI:

  • This line imports the FastAPI class from the fastapi module. FastAPI is the main class provided by the FastAPI framework that you use to create your web application.

  1. app = FastAPI():

  • This line creates an instance of the FastAPI class and assigns it to the variable app. This instance represents your FastAPI application and is used to define the routes and other configurations.

  1. @app.get("/"):

  • This is a decorator that defines a route for the HTTP GET method at the root ("/") of your application. In this case, it corresponds to the base URL of your app. The function immediately following this decorator will be executed when a request is made to this route.

  1. def read_root()::

  • This is a Python function named read_root, which is the function associated with the route defined above. It is a simple example of a FastAPI route handler.

  1. return {"message": "Hello, FastAPI!"}:

  • Inside the read_root function, this line returns a dictionary as a JSON response. In this example, it returns a simple JSON object with a key "message" and the value "Hello, FastAPI!". This JSON response will be sent to the client when the root URL is accessed.


In summary, this code sets up a basic FastAPI application with a single route ("/") that responds to HTTP GET requests with a JSON message. When you run this application using Uvicorn, you can access it in your browser or through tools like curl or HTTPie, and it will respond with the specified message. The application also automatically generates interactive API documentation that you can explore at the /docs endpoint when the app is running.

 

Run the FastAPI App:

In the terminal, run the following command to start the FastAPI application using Uvicorn:

uvicorn main:app --reload


The --reload option enables automatic code reloading during development.


Screenshot of a running FastAPI app in the browser
Screenshot of a running FastAPI app in the browser


  1. Access the API: Open your web browser and navigate to http://127.0.0.1:8000 or http://localhost:8000. You should see the default FastAPI documentation provided by Swagger UI.

  2. Explore the API Documentation: FastAPI generates interactive API documentation. Access the Swagger documentation at http://127.0.0.1:8000/docs or the ReDoc documentation at http://127.0.0.1:8000/redoc to explore and test your API endpoints interactively.


Screenshot of FastAPI documentation, particularly the docs route, and it was taken in a browser.
Screenshot of FastAPI documentation, particularly the docs route, and it was taken in a browser.


Now, you've successfully created and run your first FastAPI app. You can extend this app by adding more endpoints, handling query parameters, connecting to databases, and leveraging other features provided by FastAPI. Refer to the official FastAPI documentation for more advanced features and examples.

bottom of page