Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying FastAPI Cookbook
  • Table Of Contents Toc
  • Feedback & Rating feedback
FastAPI Cookbook

FastAPI Cookbook

By : Giunio De Luca
4.3 (4)
close
close
FastAPI Cookbook

FastAPI Cookbook

4.3 (4)
By: Giunio De Luca

Overview of this book

FastAPI is a cutting-edge Python framework that is revolutionizing the way web apps and APIs are built. Known for its speed, simplicity, and scalability, FastAPI empowers developers to create high-performing applications with ease. This book will help you leverage FastAPI’s immense potential to handle high-traffic scenarios and integrate seamlessly with modern Python tools. The book begins by familiarizing you with the basics of setting up and configuring your FastAPI environment before moving to the intricacies of building RESTful APIs, managing data with SQL and NoSQL databases, and handling authentication and authorization. Next, you'll focus on advanced topics such as custom middleware, WebSocket communication, and integration with various Python libraries. Each chapter is meticulously crafted with practical recipes, progressing from foundational concepts to advanced features and best practices. The concluding chapters show you how to optimize performance, implement rate limiting, and execute background tasks, empowering you to become a proficient FastAPI developer. By the end of this book, you'll have gained the skills you need to migrate existing apps to FastAPI, and be equipped to tackle any challenge in the modern web development landscape, ensuring your apps are not only functional, but also efficient, secure, and scalable.
Table of Contents (15 chapters)
close
close

Creating a new FastAPI project

Setting up a well-organized project structure is crucial for maintaining a clean code base, especially as your application grows and evolves. This recipe will guide you on how to create your first basic FastAPI project. A structured project simplifies navigation, debugging, and collaboration. For FastAPI, following best practices in structuring can significantly enhance scalability and maintainability.

Getting ready

All you need to do to follow the recipe is make sure that you have your development environment set up.

How to do it...

We begin by making a project folder named fastapi_start that we’ll use as the root project folder.

  1. From the terminal at the root project folder level, we’ll set up our virtual environment by running the following command:
    $ python -m venv .venv

    This will create a .venv folder that will contain all packages required for the project within our project's root folder.

  2. Now, you need to activate the environment. If you are on Mac or Linux, run the following command:
    $ source .venv/bin/activate

    From Windows, run the following command:

    $ .venv\Scripts\activate

    When the environment is active, you should see in your terminal a prefix string such as (.venv) $. Alternatively, if you check the location of the python binary command, it should be located within the .venv folder. From now on, each time you install a module with pip, it will be installed in the .venv folder, and it will be activated only if the environment is active.

  3. Now, you can install the fastapi package with uvicorn in your environment by running the following command:
    $ pip install fastapi uvicorn

    Once FastAPI is installed in your environment, open your project folder with your favorite IDE and create a file called main.py.

  4. This file is where your FastAPI application begins. Start by writing the import of the FastAPI module. Then, create an instance of the FastAPI class:
    from fastapi import FastAPI
    app = FastAPI()

    This instance houses the code of your application.

  5. Next, define your first route. Routes in FastAPI are like signposts that direct requests to the appropriate function. Start with a simple route that returns a greeting to the world:
    @app.get("/")
    def read_root():
        return {"Hello": "World"}

    You’ve just created the code for your first FastAPI application.

If you want to track the project, you can set up Git as follows:

  1. In your project’s root directory, open a terminal or Command Prompt and run the following command:
    $ git init

    This simple command prepares your project for version control under Git.

    Before committing, create a .gitignore file to specify untracked files to ignore (such as __pychache__, .venv, or IDE-specific folders). You can also have a look at the one on the GitHub repository of the project at the link: https://github.com/PacktPublishing/FastAPI-Cookbook/blob/main/.gitignore.

  2. Then, add your files with the following command:
    $ git add .
  3. Then, commit them using the following command:
    $ git commit -m "Initial commit"

And that's it. You are now tracking your project with Git.

There’s more...

A well-structured project is not just about neatness; it’s about creating a sustainable and scalable environment where your application can grow and evolve. In FastAPI, this means organizing your project in a way that separates different aspects of your application logically and efficiently.

There is no unique and perfect structure for a FastAPI project; however, a common approach is to divide your project into several key directories:

  • /src: This is where your primary application code lives. Inside /src, you might have subdirectories for different modules of your application. For instance, you could have a models directory for your database models, a routes directory for your FastAPI routes, and a services directory for business logic.
  • /tests: Keeping your tests separate from your application code is a good practice. It makes it easier to manage them and ensures that your production builds don’t include test code.
  • /docs: Documentation is crucial for any project. Whether it’s API documentation, installation guides, or usage instructions, having a dedicated directory for documentation helps maintain clarity.

See also

You can find detailed information on how to manage virtual environments with venv at the following link:

To brush up your knowledge with Git and get familiar with adding, staging and commiting operations, have a look at this guide:

Create a Note

Modal Close icon
You need to login to use this feature.
notes
bookmark search playlist download font-size

Change the font size

margin-width

Change margin width

day-mode

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Delete Note

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Edit Note

Modal Close icon
Write a note (max 255 characters)
Cancel
Update Note

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY