Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Building Python Web APIs with FastAPI
Building Python Web APIs with FastAPI

Building Python Web APIs with FastAPI: A fast-paced guide to building high-performance, robust web APIs with very little boilerplate code

Arrow left icon
Profile Icon Abdulazeez Profile Icon Abdulazeez Abdulazeez Adeshina
Arrow right icon
$22.99 $33.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7 (9 Ratings)
eBook Jul 2022 216 pages 1st Edition
eBook
$22.99 $33.99
Paperback
$41.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Abdulazeez Profile Icon Abdulazeez Abdulazeez Adeshina
Arrow right icon
$22.99 $33.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7 (9 Ratings)
eBook Jul 2022 216 pages 1st Edition
eBook
$22.99 $33.99
Paperback
$41.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$22.99 $33.99
Paperback
$41.99
Subscription
Free Trial
Renews at $19.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
Table of content icon View table of contents Preview book icon Preview Book

Building Python Web APIs with FastAPI

Chapter 1: Getting Started with FastAPI

FastAPI is the Python web framework that we are going to use in this book. It is a fast, lightweight modern API and has an easier learning curve when compared to other Python-based web frameworks, such as Flask and Django. FastAPI is relatively new, but it has a growing community. It is used extensively in building web APIs and in deploying machine learning models.

In the first chapter, you will learn how to set up your development environment and build your first FastAPI application. You will begin by learning the basics of Git – a version control system – to equip you with the knowledge of storing, tracking, and retrieving file changes as you build your application. You will also learn how to handle packages in Python using pip, how to create isolated development environments with Virtualenv, and the basics of Docker. Lastly, you will be introduced to the basics of FastAPI by building a simple Hello World application.

An understanding of the technologies previously mentioned is required to build a full-blown FastAPI application. It also serves as an addition to your current skillset.

At the completion of this chapter, you will be able to set up and use Git, install and manage packages using pip, create an isolated development environment with Virtualenv, use Docker, and most importantly, scaffold a FastAPI application.

This chapter covers the following topics:

  • Git basics
  • Creating isolated development environments with Virtualenv
  • Package management with pip
  • Setting up and learning the basics of Docker
  • Building a simple FastAPI application

Technical Requirement

You can find the code files for this chapter on GitHub at https://github.com/PacktPublishing/Building-Python-Web-APIs-with-FastAPI/tree/main/ch01

Git basics

Git is a version control system that enables developers to record, keep track, and revert to earlier versions of files. It is a decentralized and lightweight tool that can be installed on any operating system.

You will be learning how to use Git for record-keeping purposes. As each layer of the application is being built, changes will be made, and it’s important that these changes are kept note of.

Installing Git

To install Git, visit the downloads page at https://git-scm.com/downloads and select a download option for your current operating system. You’ll be redirected to an instructional page on how to install Git on your machine.

It is also worth noting that Git comes as a CLI and a GUI application. Therefore, you can download the one that works best for you.

Git operations

As mentioned earlier, Git can be used to record, track, and revert to earlier versions of a file. However, only the basic operations of Git will be used in this book and will be introduced in this section.

In order for Git to run properly, folders housing files must be initialized. Initializing folders enables Git to keep track of the content except otherwise exempted.

To initialize a new Git repository in your project, you need to run the following command in your terminal:

$ git init

To enable tracking of files, a file must first be added and committed. A Git commit enables you to track file changes between timeframes; for example, a commit made an hour ago and the current file version.

What Is a Commit?

A commit is a unique capture of a file or folder status at a particular time, and it is identified by a unique code.

Now that we know what a commit is, we can go ahead and commit a file as follows:

$ git add hello.txt
$ git commit -m "Initial commit"

You can track the status of your files after making changes by running the following command:

$ git status

Your terminal should look similar to the following:

Figure 1.1 – Git commands

Figure 1.1 – Git commands

To view the changes made to the file, which can be additions or subtractions from the file contents, run the following command:

$ git diff

Your terminal should look similar to the following:

Figure 1.2 – Output from the git diff command

Figure 1.2 – Output from the git diff command

It is good practice to include a .gitignore file in every folder. The .gitignore file contains the names of files and folders to be ignored by Git. This way, you can add and commit all the files in your folder without the fear of committing files like .env.

To include a .gitignore file, run the following command in your terminal:

$ touch .gitignore

To exempt a file from being tracked by Git, add it to the .gitignore file as follows:

$ echo ".env" >> .gitignore

Common files contained in a .gitignore file include the following:

  • Environment files (*.env)
  • Virtualenv folder (env, venv)
  • IDE metadata folders (such as .vscode and .idea)

Git branches

Branches are an important feature that enables developers to easily work on different application features, bugs, and so on, separately before merging into the main branch. The system of branching is employed in both small-scale and large-scale applications and promotes the culture of previewing and collaborations via pull requests. The primary branch is called the main branch and it is the branch from which other branches are created.

To create a new branch from an existing branch, we run the git checkout -b newbranch command. Let’s create a new branch by running the following command:

$ git checkout -b hello-python-branch

The preceding command creates a new branch from the existing one, and then sets the active branch to the newly created branch. To switch back to the original main branch, we run git checkout main as follows:

$ git checkout main

Important Note

Running git checkout main makes main the active working branch, whereas git checkout -b newbranch creates a new branch from the current working branch and sets the newly created branch as the active one.

To learn more, refer to the Git documentation: http://www.git-scm.com/doc.

Now that we have learned the basics of Git, we can now proceed to learn about how to create isolated environments with virtualenv.

Creating isolated development environments with Virtualenv

The traditional approach to developing applications in Python is to isolate these applications in a virtual environment. This is done to avoid installing packages globally and reduce conflicts during application development.

A virtual environment is an isolated environment where application dependencies installed can only be accessed within it. As a result, the application can only access packages and interact only within this environment.

Creating a virtual environment

By default, the venv module from the standard library is installed in Python3. The venv module is responsible for creating a virtual environment. Let’s create a todos folder and create a virtual environment in it by running the following commands:

$ mkdir todos && cd todos
$ python3 -m venv venv

The venv module takes an argument, which is the name of the folder where the virtual environment should be installed into. In our newly created virtual environment, a copy of the Python interpreter is installed in the lib folder, and the files enabling interactions within the virtual environment are stored in the bin folder.

Activating and deactivating the virtual environment

To activate a virtual environment, we run the following command:

$ source venv/bin/activate

The preceding command instructs your shell to use the virtual environment’s interpreter and packages by default. Upon activating the virtual environment, a prefix of the venv virtual environment folder is added before the prompt as follows:

Figure 1.3 – Prefixed prompt

Figure 1.3 – Prefixed prompt

To deactivate a virtual environment, the deactivate command is run in the prompt. Running the command immediately exits the isolated environment and the prefix is removed as follows:

Figure 1.4 – Deactivating a virtual environment

Figure 1.4 – Deactivating a virtual environment

Important Note

You can also create a virtual environment and manage application dependencies using Pipenv and Poetry.

Now that we have created the virtual environment, we can now proceed to understand how package management with pip works.

Package management with pip

A FastAPI application constitutes packages, therefore you will be introduced to package management practices, such as installing packages, removing packages, and updating packages for your application.

Installing packages from the source can turn out to be a cumbersome task as, most of the time, it involves downloading and unzipping .tar.gz files before manual installation. In a scenario where a hundred packages are to be installed, this method becomes inefficient. Then, how do you automate this process?

Pip is a Python package manager like JavaScript’s yarn; it enables you to automate the process of installing Python packages – both globally and locally.

Installing pip

Pip is automatically installed during a Python installation. You can verify whether pip is installed by running the following command in your terminal:

$ python3 -m pip list

The preceding command should return a list of packages installed. The output should be similar to the following figure:

Figure 1.5 – List of installed Python packages

Figure 1.5 – List of installed Python packages

If the command returns an error, follow the instructions at https://pip.pypa.io/en/stable/installation/ to install pip.

Basic commands

With pip installed, let’s learn its basic commands. To install the FastAPI package with pip, we run the following command:

$ pip install fastapi

On a Unix operating system, such as Mac or Linux, in some cases, the sudo keyword is prepended to install global packages.

To uninstall a package, the following command is used:

$ pip uninstall fastapi

To collate the current packages installed in a project into a file, we use the following freeze command:

$ pip freeze > requirements.txt

The > operator tells bash to save the output from the command into the requirements.txt file. This means that running pip freeze returns an output of all the currently installed packages.

To install packages from a file such as the requirements.txt file, the following command is used:

$ pip install -r requirements.txt

The preceding command is mostly used in deployment.

Now that you have learned the basics of pip and have gone over some basic commands, let’s learn the basics of Docker.

Setting up Docker

As our application grows into having multiple layers, such as a database, coupling the application into a single piece enables us to deploy our application. We’ll be using Docker to containerize our application layers into a single image, which can then be easily deployed locally or in the cloud.

Additionally, using a Dockerfile and a docker-compose file eliminates the need to upload and share images of our applications. New versions of our applications can be built from the Dockerfile and deployed using the docker-compose file. Application images can also be stored and retrieved from Docker Hub. This is known as a push and pull operation.

To begin setting up, download and install Docker from https://docs.docker.com/install.

Dockerfile

A Dockerfile contains instructions on how our application image is to be built. The following is an example Dockerfile:

FROM PYTHON:3.8
# Set working directory to /usr/src/app
WORKDIR /usr/src/app
# Copy the contents of the current local directory into the container's working directory
ADD . /usr/src/app
# Run a command
CMD ["python", "hello.py"]

Next, we’ll build the application container image and tag it getting_started as follows:

$ docker build -t getting_started .

If the Dockerfile isn’t present in the directory where the command is being run, the path to the Dockerfile should be properly appended as follows:

$ docker build -t api api/Dockerfile

The container image can be run using the following command:

$ docker run getting-started

Docker is an efficient tool for containerization. We have only looked at the basic operations and we’ll learn more operations practically in Chapter 9, Deploying FastAPI Applications.

Building a simple FastAPI application

Finally, we can now get to our first FastAPI project. Our aim in this section is to introduce FastAPI by building a simple application. We shall cover in-depth operations in subsequent chapters.

We’ll begin by installing the dependencies required for our application in the todos folder we created earlier. The dependencies are the following:

  • fastapi: The framework on which we’ll build our application.
  • uvicorn: An Asynchronous Server Gateway Interface module to run our application.

First, activate your development environment by running the following command in your project directory:

$ source venv/bin/activate

Then, install the dependencies as follows:

(venv)$ pip install fastapi uvicorn

For now, we’ll create a new api.py file and create a new instance of FastAPI as follows:

from fastapi import FastAPI
app = FastAPI()

By instantiating FastAPI in the app variable, we can proceed to create routes. Let’s create a welcome route.

A route is created by first defining a decorator to indicate the type of operation, followed by a function containing the operation to be carried out when this route is invoked. In the following example, we’ll create a "/" route that only accepts GET requests and returns a welcome message when visited:

@app.get("/")
async def welcome() -> dict:
    return { "message": "Hello World"}

The next step is to start our application using uvicorn. In your terminal, run the following command:

(venv)$ uvicorn api:app --port 8000 --reload

In the preceding command, uvicorn takes the following arguments:

  • file:instance: The file containing the instance of FastAPI and the name variable holding the FastAPI instance.
  • --port PORT: The port the application will be served on.
  • --reload: An optional argument included to restart the application on every file change.

The command returns the following output:

(venv) ➜  todos uvicorn api:app --port 8080 --reload
INFO:     Will watch for changes in these directories: ['/Users/youngestdev/Documents/todos']
INFO:     Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit)
INFO:     Started reloader process [3982] using statreload
INFO:     Started server process [3984]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

The next step is to test the application by sending a GET request to the API. In a new terminal, send a GET request using curl as follows:

$ curl http://0.0.0.0:8080/

The response from the application logged in your console will be the following:

{"message":"Hello World"}

Summary

In this chapter, we have learned how to install the tools required to set up our development environment. We have also built a simple API as an introduction to FastAPI and learned how to create a route in the process.

In the next chapter, you will be introduced to routing in FastAPI. First, you will be introduced to the process of building models to validate request payloads and responses using Pydantic. You will then learn about Path and Query parameters as well as request body, and finally, you will learn how to build a CRUD todo application.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • A practical guide to developing production-ready web APIs rapidly in Python
  • Learn how to put FastAPI into practice by implementing it in real-world scenarios
  • Explore FastAPI, its syntax, and configurations for deploying applications

Description

RESTful web services are commonly used to create APIs for web-based applications owing to their light weight and high scalability. This book will show you how FastAPI, a high-performance web framework for building RESTful APIs in Python, allows you to build robust web APIs that are simple and intuitive and makes it easy to build quickly with very little boilerplate code. This book will help you set up a FastAPI application in no time and show you how to use FastAPI to build a REST API that receives and responds to user requests. You’ll go on to learn how to handle routing and authentication while working with databases in a FastAPI application. The book walks you through the four key areas: building and using routes for create, read, update, and delete (CRUD) operations; connecting the application to SQL and NoSQL databases; securing the application built; and deploying your application locally or to a cloud environment. By the end of this book, you’ll have developed a solid understanding of the FastAPI framework and be able to build and deploy robust REST APIs.

Who is this book for?

This book is for Python developers who want to learn FastAPI in a pragmatic way to create robust web APIs with ease. If you are a Django or Flask developer looking to try something new that's faster, more efficient, and produces fewer bugs, this FastAPI Python book is for you. The book assumes intermediate-level knowledge of Python programming.

What you will learn

  • Set up a FastAPI application that is fully functional and secure
  • Understand how to handle errors from requests and send proper responses in FastAPI
  • Integrate and connect your application to a SQL and NoSQL (MongoDB) database
  • Perform CRUD operations using SQL and FastAPI
  • Manage concurrency in FastAPI applications
  • Implement authentication in a FastAPI application
  • Deploy a FastAPI application to any platform

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 29, 2022
Length: 216 pages
Edition : 1st
Language : English
ISBN-13 : 9781801074513
Languages :
Concepts :
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

Product Details

Publication date : Jul 29, 2022
Length: 216 pages
Edition : 1st
Language : English
ISBN-13 : 9781801074513
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 130.97
Building Python Microservices with FastAPI
$46.99
Building Python Web APIs with FastAPI
$41.99
Full Stack FastAPI, React, and MongoDB
$41.99
Total $ 130.97 Stars icon

Table of Contents

13 Chapters
Part 1: An Introduction to FastAPI Chevron down icon Chevron up icon
Chapter 1: Getting Started with FastAPI Chevron down icon Chevron up icon
Chapter 2: Routing in FastAPI Chevron down icon Chevron up icon
Chapter 3: Response Models and Error Handling Chevron down icon Chevron up icon
Chapter 4: Templating in FastAPI Chevron down icon Chevron up icon
Part 2: Building and Securing FastAPI Applications Chevron down icon Chevron up icon
Chapter 5: Structuring FastAPI Applications Chevron down icon Chevron up icon
Chapter 6: Connecting to a Database Chevron down icon Chevron up icon
Chapter 7: Securing FastAPI Applications Chevron down icon Chevron up icon
Part 3: Testing And Deploying FastAPI Applications Chevron down icon Chevron up icon
Chapter 8: Testing FastAPI Applications Chevron down icon Chevron up icon
Chapter 9: Deploying FastAPI Applications Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7
(9 Ratings)
5 star 77.8%
4 star 11.1%
3 star 11.1%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Aaaaaooooobree Aug 31, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I loved how easy it was to read and how the code is written and explained throughout the book. I can't wait to apply more of it in a practical application and see where it goes from there. Definitively worth checking out.It even goes over git and how to do pip installs. So, there is information here that's useful all the way from new user to an experienced user.
Amazon Verified review Amazon
gokul Sep 26, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I like the parts where the apps are integrated with databases. Firstly with sqlclient and then with mongodb.At the end, deployment with docker is covered all. Overall, i have gained confidence with fastapi fastly.Appreciate the author.
Amazon Verified review Amazon
Luiz Eduardo Fonseca Aug 22, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book is very well-structured. It takes the reader from the basic aspects of building an API like routing, connecting to Databases, authenticating etc. But then it also takes to more advanced topics, like testing, advanced error handling, and container deployment. All in all, it achieves what it sets out to do with great mastery, and then some.
Amazon Verified review Amazon
K Oct 06, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Kurz und knackig.Inhaltlich viel besser als das andere Buch zu FastAPI von Packt.Es werden auch einige best practices erwähnt.
Amazon Verified review Amazon
Pablo Moreno Aug 05, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I got this book just couple of weeks ago, and it is very well written. It has many practical examples and written in simple language.To get the most of the content, it is important that you have some experience working with Python (some, but no need to be a Python expert).The concepts around API are focused on how to put products in production quickly with FastAPI, regardless of your knowledge and experience working with APIs.If you want to start understanding how API works, this book is definitely for you.
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.