Web Development with FastAPI and Python

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setup
  4. Creating a FastAPI Project
  5. Defining Routes and Models
  6. Handling HTTP Requests and Responses
  7. Adding Database Support
  8. Testing the API
  9. Deployment
  10. Conclusion

Introduction

In this tutorial, we will explore how to build a web application using FastAPI, a modern, fast (high-performance), web framework for building APIs with Python. By the end of this tutorial, you will have a good understanding of FastAPI and be able to develop and deploy your own web applications.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of Python programming language fundamentals and web development concepts. Familiarity with HTTP and RESTful APIs is also beneficial but not required.

Setup

Before we start, make sure you have Python installed on your machine. You can download the latest version of Python from the official website and follow the installation instructions specific to your operating system.

Besides Python, we also need to install a few additional dependencies. Open your terminal or command prompt and execute the following command to install FastAPI and its dependencies: python pip install fastapi uvicorn FastAPI relies on Uvicorn to run the web server, so we install it as well.

Creating a FastAPI Project

Let’s begin by creating a new directory for our FastAPI project. Open your terminal or command prompt, navigate to the desired location, and use the following command to create a new directory: bash mkdir fastapi-project Enter the newly created directory: bash cd fastapi-project Inside the fastapi-project directory, create a new Python file called main.py using a text editor of your choice. bash touch main.py Open main.py in your text editor and import the necessary modules: python from fastapi import FastAPI Next, create an instance of the FastAPI class: python app = FastAPI() Congratulations! You have just created a basic FastAPI application.

Defining Routes and Models

In FastAPI, routes are used to define HTTP endpoints and the actions associated with them. Let’s define a simple API route that returns a welcome message.

Add the following code to main.py: python @app.get("/") async def root(): return {"message": "Welcome to the FastAPI tutorial"} The @app.get("/") decorator specifies that this route will be triggered when a GET request is made to the root URL (“/”). The root() function is an asynchronous function that will handle the request. In this case, it returns a dictionary with a message.

Now, let’s define a route that accepts a parameter. Add the following code to main.py: python @app.get("/user/{username}") async def get_user(username: str): return {"message": f"Welcome, {username}!"} In this example, we use the @app.get("/user/{username}") decorator to define a route that accepts a username parameter. The get_user() function retrieves the value of the username parameter and includes it in the response message.

Handling HTTP Requests and Responses

FastAPI provides several decorators to handle different types of HTTP requests, such as @app.post(), @app.put(), @app.delete(), etc.

To demonstrate, let’s create a route that handles POST requests to create a new user. Add the following code to main.py: python @app.post("/user") async def create_user(user: dict): # Save the user in the database or perform other actions return {"message": "User created successfully"} In this example, the @app.post("/user") decorator specifies that this route will handle POST requests to the “/user” URL. The create_user() function accepts a user parameter, which is expected to be a dictionary representing the user data.

Adding Database Support

To interact with a database in FastAPI, we can use an ORM (Object-Relational Mapping) library such as SQLAlchemy. SQLAlchemy provides a powerful and flexible interface for working with databases from Python.

Let’s add support for a SQLite database using SQLAlchemy. Install SQLAlchemy by executing the following command: bash pip install sqlalchemy databases Next, import the necessary modules in main.py: ```python from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import declarative_base, sessionmaker

DATABASE_URL = "sqlite:///./fastapi.db"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String, unique=True, index=True)

Base.metadata.create_all(bind=engine)
``` The above code sets up the database connection and defines a `User` model using SQLAlchemy. The `User` model represents a table named "users" with an `id` and `username` column.

Next, modify the create_user() route to save the user in the database. Replace the existing create_user() route with the following code: python @app.post("/user") async def create_user(user: dict): db = SessionLocal() new_user = User(username=user["username"]) db.add(new_user) db.commit() db.refresh(new_user) return {"message": "User created successfully"} This code creates a new instance of the User model, saves it to the database, and returns a success message.

Testing the API

To test our API endpoints, we can use tools like curl or Postman. However, FastAPI also provides a built-in user interface called “Swagger UI” that allows us to interact with our API using a web browser.

To access the Swagger UI, we need to run our FastAPI application using Uvicorn. Open your terminal or command prompt, navigate to the project directory, and execute the following command: bash uvicorn main:app --reload Now, open your web browser and go to http://localhost:8000/docs. You will see the Swagger UI interface with a list of available routes, parameters, and the ability to test them.

Deployment

When it comes to deploying a FastAPI application, there are several options available. Some popular deployment choices include Docker, Kubernetes, or using a Platform-as-a-Service (PaaS) provider like Heroku or AWS Elastic Beanstalk.

Please refer to the FastAPI documentation to learn about different deployment strategies and choose the one that best fits your needs.

Conclusion

In this tutorial, we covered the basics of building a web application with FastAPI and Python. We learned how to define routes, handle HTTP requests and responses, add database support using SQLAlchemy, and test our API using Swagger UI. With this knowledge, you can now start developing your own FastAPI applications and explore its extensive features.

Remember, practice makes perfect, so don’t hesitate to experiment and build more complex projects using FastAPI. Happy coding!