Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
FastAPI Cookbook

You're reading from   FastAPI Cookbook Develop high-performance APIs and web applications with Python

Arrow left icon
Product type Book
Published in Aug 2024
Publisher Packt
ISBN-13 9781805127857
Pages 358 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Giunio De Luca Giunio De Luca
Author Profile Icon Giunio De Luca
Giunio De Luca
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Chapter 1: First Steps with FastAPI FREE CHAPTER 2. Chapter 2: Working with Data 3. Chapter 3: Building RESTful APIs with FastAPI 4. Chapter 4: Authentication and Authorization 5. Chapter 5: Testing and Debugging FastAPI Applications 6. Chapter 6: Integrating FastAPI with SQL Databases 7. Chapter 7: Integrating FastAPI with NoSQL Databases 8. Chapter 8: Advanced Features and Best Practices 9. Chapter 9: Working with WebSocket 10. Chapter 10: Integrating FastAPI with other Python Libraries 11. Chapter 11: Middleware and Webhooks 12. Chapter 12: Deploying and Managing FastAPI Applications 13. Index 14. Other Books You May Enjoy

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:

  • Creation of virtual environments: https://docs.python.org/3/library/venv.html

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

  • Git simple guide: https://rogerdudler.github.io/git-guide/
You have been reading a chapter from
FastAPI Cookbook
Published in: Aug 2024
Publisher: Packt
ISBN-13: 9781805127857
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime