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
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7 (9 Ratings)
Paperback 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
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7 (9 Ratings)
Paperback 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 a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781801076630
Languages :
Concepts :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.