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! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
FastAPI Cookbook
FastAPI Cookbook

FastAPI Cookbook: Develop high-performance APIs and web applications with Python

eBook
£23.99 £26.99
Paperback
£33.99
Subscription
Free Trial
Renews at £16.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

FastAPI Cookbook

First Steps with FastAPI

Welcome to the exciting world of FastAPI, a modern, high-performance framework for building APIs and web applications in Python. This first chapter is your gateway to understanding and harnessing the power of FastAPI. Here, you’ll take your initial steps into setting up your development environment, creating your very first FastAPI project, and exploring its fundamental concepts.

FastAPI stands out for its speed, ease of use, and comprehensive documentation, making it a preferred choice for developers looking to build scalable and efficient web applications. In this chapter, you’ll practically engage in setting up FastAPI, learning how to navigate its architecture, and understanding its core components. You’ll gain hands-on experience by defining simple API endpoints, handling HTTP methods, and learning about request and response handling. These foundational skills are crucial for any developer stepping into the world of modern web development with FastAPI.

By the end of this chapter, you will have a solid understanding of FastAPI’s basic structure and capabilities. You’ll be able to set up a new project, define API endpoints, and have a grasp on handling data with FastAPI. This knowledge sets the stage for more advanced topics and complex applications you’ll encounter as you progress through the book.

In this chapter, we’re going to cover the following recipes:

  • Setting up your development environment
  • Creating a new FastAPI project
  • Understanding FastAPI basics
  • Defining your first API endpoint
  • Working with path and query parameters
  • Defining and using request and response models
  • Handling errors and exceptions

Each recipe is designed to provide you with practical knowledge and direct experience, ensuring that by the end of this chapter, you’ll be well equipped to start building your own FastAPI applications.

Technical requirements

To embark on your journey with FastAPI, you’ll need to set up an environment that supports Python development and FastAPI’s functionalities. Here’s a list of the technical requirements and installations needed for this chapter:

  • Python: FastAPI is built on Python, so you’ll need a Python version compatible with your FastAPI version. You can download the latest version of it from python.org.
  • FastAPI: Install FastAPI using pip, Python’s package manager. You can do it by running pip install fastapi from the command terminal.
  • Uvicorn: FastAPI requires an Asynchronous Server Gateway Interface (ASGI) server, and Uvicorn is a lightning-fast ASGI server implementation. Install it using pip install uvicorn.
  • Integrated development environment (IDE): An IDE such as Visual Studio Code (VS Code), PyCharm, or any other IDE that supports Python development will be necessary for writing and testing your code.
  • Postman or Swagger UI: For testing API endpoints. FastAPI automatically generates and hosts Swagger UI, so you can use it right out of the box.
  • Git: Version control is essential, and Git is a widely used system. If not already installed, you can get it from git-scm.com.
  • GitHub account: A GitHub account is required to access the code repositories. Sign up at github.com if you haven’t already.

The code used in the chapter is available on GitHub at the following address: https://github.com/PacktPublishing/FastAPI-Cookbook/tree/main/Chapter01. You can clone or download the repository at https://github.com/PacktPublishing/FastAPI-Cookbook to follow along on your local machine.

Setting up your development environment

This recipe, dedicated to setting up your development environment, is a critical foundation for any successful project in web development. Here, you’ll learn how to install and configure all the essential tools needed to start building with FastAPI.

We begin by guiding you through the installation of Python, the core language behind FastAPI. Next, we’ll move on to installing FastAPI itself, along with Uvicorn, a lightning-fast ASGI server, which serves as the bedrock for running your FastAPI applications.

Setting up an IDE is our next stop. Whether you prefer VS Code, PyCharm, or any other Python-friendly IDE, we’ll provide tips to make your development process smoother and more efficient.

Lastly, we’ll introduce you to Git and GitHub – indispensable tools for version control and collaboration in modern software development. Understanding how to use these tools will not only help you manage your code effectively but also open doors to the vast world of community-driven development and resources.

Getting ready

FastAPI works with Python, so you need to check your Python version before using it. This is an important step for setting up FastAPI. We will guide you through how to install it.

Windows installation

If you work on Windows, follow these steps to install Python:

  1. Visit the official Python website: python.org.
  2. Download the latest version of Python or any other version higher than 3.9.
  3. Run the installer. Ensure to check the box that says Add Python to PATH before clicking Install Now.
  4. After the installation, open Command Prompt and type python --version to confirm the installation.

macOS/Linux installation

macOS usually comes with Python pre-installed; however, it might not be the latest version.

You can use Homebrew (a package manager for macOS). To install it, open the terminal and run it:

$ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/\Homebrew/install/HEAD/install.sh)"

Then, you can install Python – still from the terminal – with the following command:

$ brew install python

On Linux, you can install Python using the package manager by running the following command:

$ sudo apt-get install python3

That’s all you need to install Python on macOS and Linux systems.

Checking the installation

You can then check that Python is correctly installed by running the following command in the terminal:

$ python --version

If you installed it on Linux, the binary command is python3, so you can check that Python is correctly installed by running the following command:

$ python3 --version

Once Python is installed, we want to make sure that the Python’s package manager is correctly installed. It comes with Python’s installation, and it’s called pip.

From a terminal window, run the following command:

$ pip --version

On Linux, run the following command:

$ pip3 --version

Once Python is installed on your computer, you can now consider installing FastAPI.

How to do it...

When you have Python and pip ready, we can continue with installing FastAPI, the IDE. Then, we will configure Git.

We will do it by following these steps:

  1. Installing FastAPI and Uvicorn
  2. Setting up your IDE (VS Code or PyCharm)
  3. Setting up Git and GitHub to track your project

Installing FastAPI and Uvicorn

With Python set up, the next step is installing FastAPI and Uvicorn. FastAPI is the framework we’ll use to build our applications, and Uvicorn is an ASGI server that runs and serves our FastAPI applications.

Open your command-line interface and install FastAPI and Uvicorn together by running the following command:

$ pip install fastapi[all]

This command installs FastAPI along with its recommended dependencies, including Uvicorn.

To verify the installation, you can simply run uvicorn --version from the terminal.

Setting up your IDE

Choosing the right IDE is a crucial step in your FastAPI journey. An IDE is more than just a text editor; it’s a space where you write, debug, and test your code.

A good IDE can significantly enhance your coding experience and productivity. For FastAPI development and Python in general, two popular choices are VS Code and PyCharm.

VS Code

VS Code is a free, open source, lightweight IDE with powerful features. It offers excellent Python support and is highly customizable.

You can download and install VS Code from the official website (code.visualstudio.com). The installation is quite straightforward. Once installed, open VS Code, go to Extensions (a square icon on the left bar), and search for python. Install the Microsoft version, and that is it.

PyCharm

PyCharm, created by JetBrains, is specifically tailored for Python development. It offers a broad range of tools for professional developers, including excellent support for web development frameworks such as FastAPI.

You can choose between a Community free edition and a Professional paid version. For the scope of the book, the Community Edition is largely sufficient, and it can be downloaded on the JetBrains website: https://www.jetbrains.com/pycharm/download/.

For PyCharm as well, the installation is straightforward.

Enhancing your development experience

For both IDEs – and if you use another of your choice – make sure to leverage basic perks to improve your experience as a developer and be more efficient. Here is a short checklist that I use when I approach a new IDE environment:

  • Code completion and analysis: Good IDEs provide intelligent code completion, error highlighting, and fixes, which are invaluable for efficient development
  • Debugging tools: Utilize debugging features provided by the IDE to diagnose and resolve issues in your code
  • Version control integration: A good IDE offers support for Git, simplifying code change tracking and repository management
  • Customization: Customize your IDE by adjusting themes, key binding, and settings to match your workflow, making your development experience as comfortable and productive as possible

Setting up Git and GitHub

Version control is an essential aspect of software development. Git, coupled with GitHub, forms a powerful toolset for tracking changes, collaborating, and maintaining the history of your projects. You can download the Git installer from the official website git-scm.com and install it.

After installation, configure Git with your username and email using the following commands in the command line:

$ git config --global user.name "Your Name"
$ git config --global user.email "your.email@example.com"

GitHub is the platform chosen to store code examples used in the book. Sign up for a GitHub account at github.com if you don’t already have one.

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:

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Explore FastAPI in depth, from basic setup to advanced features such as custom middleware and WebSockets
  • Discover practical strategies to optimize app performance and handle high traffic
  • Implement SQL and NoSQL integration techniques for versatile data management in FastAPI applications
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

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.

Who is this book for?

This book is for Python developers looking to enhance their skills to build scalable, high-performance web apps using FastAPI. Professionals seeking practical guidance to create APIs and web apps that can handle significant traffic and scale as needed will also find this book helpful by learning from both foundational insights and advanced techniques. The book is also designed for anyone familiar with RESTful APIs, HTTP protocols, and database systems, as well as developers looking to migrate existing applications to FastAPI or explore its advanced features.

What you will learn

  • Explore advanced FastAPI functionalities such as dependency injection, custom middleware, and WebSockets
  • Discover various types of data storage for powerful app functionality with SQL and NoSQL
  • Implement testing and debugging practices for clean, robust code
  • Integrate authentication and authorization mechanisms to secure web apps
  • Acquire skills to seamlessly migrate existing applications to FastAPI
  • Write unit and integration tests, ensuring reliability and security for your apps
  • Deploy your FastAPI apps to production environments for real-world use

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 02, 2024
Length: 358 pages
Edition : 1st
Language : English
ISBN-13 : 9781805129776
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Aug 02, 2024
Length: 358 pages
Edition : 1st
Language : English
ISBN-13 : 9781805129776
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
£16.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
£169.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts
£234.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total £ 97.97
Mastering Flask Web and API Development
£29.99
FastAPI Cookbook
£33.99
Python Data Cleaning and Preparation Best Practices
£33.99
Total £ 97.97 Stars icon

Table of Contents

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

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7
(3 Ratings)
5 star 66.7%
4 star 33.3%
3 star 0%
2 star 0%
1 star 0%
Cliente Amazon Aug 09, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Look no further if you want to learn FastAPI. The book lets you learn exhaustively yet quickly and is very well organized with a lot of use cases. And it covers everything about it, from the first steps, to the most complex scenarios, while also focusing on PyTest integration.I personally keep it with me so that I can go back to the things I need, as the book is also very easy to search.I love how also examples on ML and LLM applications are given!
Amazon Verified review Amazon
M. Aug 17, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
As someone from a JavaScript background who wanted to become more skilled with Python, I find this book an excellent opportunity to learn about FastAPI and use it to create web apps in a different programming language. The author does a great job of making the material easy to understand and giving detailed and practical recipes for success.
Amazon Verified review Amazon
Salman Farsi Sep 02, 2024
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
The FastAPI Cookbook covers everything from setting up your development environment to advanced features like WebSockets and integrating FastAPI with other Python libraries. Each chapter includes hands-on recipes that guide you through real-world scenarios, making it easy to apply what you learn. Emphasizes security, testing, and performance optimization, ensuring you build robust and efficient APIs.Clear explanations and structured content make it accessible for intermediate and advanced Python developers. Highly recommended for FastAPI engineers who want to advance their skills.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.