29,99 €
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.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 149
Veröffentlichungsjahr: 2022
A fast-paced guide to building high-performance, robust web APIs with very little boilerplate code
Abdulazeez Abdulazeez Adeshina
BIRMINGHAM—MUMBAI
Copyright © 2022 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Associate Group Product Manager: Pavan Ramchandani
Publishing Product Manager: Aaron Tanna
Senior Editor: Mark Dsouza
Content Development Editor: Divya Vijayan
Technical Editor: Shubham Sharma
Copy Editor: Safis Editing
Project Coordinator: Rashika Ba
Proofreader: Safis Editing
Indexer: Pratik Shirodkar
Production Designer: Vijay Kamble
Marketing Coordinators: Anamika Singh and Marylou De Mello
First published: July 2022
Production reference: 1150722
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80107-663-0
www.packt.com
To my mother, and to the memory of my father, for their sacrifices, belief, and constant support throughout the years. To my amazing sisters, Ameedat and Aminat, for being a continuous source of joy and happiness. To my uncle, Bako, for his continuous support over the years. To my best friends, Abdulrahman and Amina, for always being there.
– Abdulazeez Abdulazeez Adeshina
Abdulazeez Abdulazeez Adeshina is a skilled Python developer, backend software engineer, and technical writer, with a wide range of technical skill sets in his arsenal. His background has led him to build command-line applications, backend applications in FastAPI, and algorithm-based treasure-hunting tools. He also enjoys teaching Python and solving mathematical-oriented problems through his blog. Abdulazeez is currently in his penultimate year of a water resources and environmental engineering program. His work experience as a guest technical author includes the likes of Auth0, LogRocket, Okteto, and TestDriven.
I want to thank Allah (SWT) for his unending grace, and Sebastián Ramírez for creating FastAPI. I want to thank Precious Ndubueze for introducing me to FastAPI and insisting I get acquainted with the framework, and Bolaji Olajide for helping me by reviewing the first chapters. Lastly, I also want to thank every one of my close associates, especially my uncle, Tosin Olayanju, for their support throughout the development of this book – I am incredibly grateful and honored.
Akash Ranjan is a Python professional, with 6+ years of industry experience. He has developed, deployed, and managed large-scale enterprise applications. He has extensive experience in building APIs and designing microservice-based application architecture.
FastAPI is a fast and efficient web framework for building APIs with Python. This book is a thorough guide on how to build an application with the FastAPI framework.
It starts with the basics of the FastAPI framework and the other technologies used throughout this book. You’ll then learn about the different aspects of the framework: the routing system, response modeling, error handling, and templating.
In this book, you will learn how to build fast, efficient, and scalable applications in Python with FastAPI. You will begin from a Hello World application to a complete API that uses a database, authentication, and templates. You will learn how to structure your application to enhance efficiency, readability, and scalability. By integrating with other libraries in your application, you will learn how to connect your application to both a SQL database and a NoSQL database, integrate templates, and build authentication. Toward the end of this book, you will learn how to write tests, containerize your application, build a continuous integration and delivery pipeline using GitHub actions, and deploy your application to multiple cloud services. All of these will be taught via a theoretical and practical approach.
By the end of this book, you’ll be equipped with the necessary knowledge to build and deploy a robust web API using the FastAPI framework.
The primary audience for this book is any Python developer interested in building web APIs. The ideal reader is familiar with the basics of the Python programming language.
Chapter 1, Getting Started with FastAPI, introduces the basics of FastAPI and other technologies used in the book. The chapter also details the steps involved in setting up your development environment for your FastAPI application.
Chapter 2, Routing in FastAPI, talks in detail about the process of creating endpoints using the routing system in FastAPI. The components of a routing system, including the request body and path parameters, are also discussed alongside validating them with pydantic classes.
Chapter 3, Response Models and Error Handling, introduces responses in FastAPI, response modeling, error handling, and status codes.
Chapter 4, Templating in FastAPI, discusses how templates can be used to create views and render responses from the API.
Chapter 5, Structuring FastAPI Applications, introduces structuring applications and also briefly introduces the application to be built in the next chapters.
Chapter 6, Connecting to a Database, discusses two classes of databases (SQL and NoSQL) and demonstrates how you can connect your FastAPI application to either of them. We’ll cover how to connect to and use a SQL database using SQLModel, and how to work with MongoDB using an object-document mapper, Beanie.
Chapter 7, Securing FastAPI Applications, talks about what securing your application entails – authorization and authentication, implementing authentication, and restricting access to application endpoints.
Chapter 8, Testing FastAPI Applications, explains what testing is and how to test our API endpoints.
Chapter 9, Deploying FastAPI Applications, discusses the steps involved in deploying your FastAPI application.
You will need the latest version of Python installed on your computer. You also need to be familiar with the Python programming language to get the most out of this book.
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Building-Python-Web-APIs-with-FastAPI. If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/qqhpc.
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “To switch back to the original main branch, we run git checkout main.”
A block of code is set as follows:
from fastapi import FastAPI from routes.user import user_router import uvicornWhen we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
from pydantic import BaseModel from typing import List class Event(BaseModel): id: int title: str image: str description: str tags: List[str] location: strAny command-line input or output is written as follows:
$ git add hello.txt
$ git commit -m "Initial commit"
Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “As shown in the previous model diagram, each user will have an Events field, which is a list of the events they have ownership of.”
Tips or Important Notes
Appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Once you’ve read Building Python Web APIs with FastAPI, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Upon completion of this part, you will have a substantial understanding of FastAPI, including routing, file handling, error handling, building response models, and templating. This part starts by introducing the technologies that will be used throughout the book before proceeding to the basics of the FastAPI framework.
This part comprises the following chapters:
Chapter 1, Getting Started with FastAPIChapter 2, Routing in FastAPIChapter 3, Response Models and Error HandlingChapter 4, Templating in FastAPIFastAPI 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 basicsCreating isolated development environments with VirtualenvPackage management with pipSetting up and learning the basics of DockerBuilding a simple FastAPI applicationYou 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 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.
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.
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
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
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)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
