www.packtpub.com
Open in
urlscan Pro
2606:4700:10::ac43:15a2
Public Scan
Submitted URL: https://packt.omeclk.com/portal/wts/ug^cnN2cyLec6q6-6gEfnDa8eE8zmq4rhkrt7yCrCka
Effective URL: https://www.packtpub.com/en-us/product/fastapi-cookbook-9781805127857?utm_source=PythonPro+Newsletter&utm_medium=email&ut...
Submission: On September 17 via api from SA — Scanned from DE
Effective URL: https://www.packtpub.com/en-us/product/fastapi-cookbook-9781805127857?utm_source=PythonPro+Newsletter&utm_medium=email&ut...
Submission: On September 17 via api from SA — Scanned from DE
Form analysis
3 forms found in the DOMhttps://www.packtpub.com/en-us/search
<form class="search desktop" data-search="https://www.packtpub.com/api/rebuild/header/search" data-method="POST" action="https://www.packtpub.com/en-us/search">
<svg role="presentation" class="icon icon-5 search-box-icon">
<use href="https://www.packtpub.com/rebuild/build/assets/common-CwvaZMrJ.svg#search"></use>
<desc>Search icon</desc>
</svg>
<input type="text" name="query" class="search-input" placeholder="Search..." id="search" autocomplete="off">
<span class="loader d-none"></span>
<svg role="presentation" class="search-close d-none">
<use href="https://www.packtpub.com/rebuild/build/assets/common-CwvaZMrJ.svg#close"></use>
<desc>Close icon</desc>
</svg>
<div class="search-results d-none scrollbar" id="results"></div>
</form>
GET https://www.packtpub.com/checkout/add/ebook/9781805127857
<form action="https://www.packtpub.com/checkout/add/ebook/9781805127857" method="get">
<button id="product-buy-now" type="submit" class="rebuild-btn rebuild-btn-primary" data-analytics-type="add_to_cart" data-analytics-currency="USD" data-analytics-item-id="US-9781805129776-EBOOK" data-analytics-item-title="FastAPI Cookbook"
data-analytics-item-language="" data-analytics-item-framework="" data-analytics-item-concept="" data-analytics-item-publication-year="2024" data-analytics-item-quantity="1" data-analytics-item-index="0" data-analytics-item-format="ebook"
data-analytics-item-price="24.99" data-analytics-item-discount="11"> Buy Now </button>
</form>
GET https://www.packtpub.com/checkout/add/ebook/9781805127857
<form action="https://www.packtpub.com/checkout/add/ebook/9781805127857" method="get">
<button id="product-buy-now" type="submit" class="rebuild-btn rebuild-btn-primary" data-analytics-type="add_to_cart" data-analytics-currency="USD" data-analytics-item-id="US-9781805129776-EBOOK" data-analytics-item-title="FastAPI Cookbook"
data-analytics-item-language="" data-analytics-item-framework="" data-analytics-item-concept="" data-analytics-item-publication-year="2024" data-analytics-item-quantity="1" data-analytics-item-index="0" data-analytics-item-format="ebook"
data-analytics-item-price="24.99" data-analytics-item-discount="11"> Buy Now </button>
</form>
Text Content
Search icon Close icon Search icon CANCEL Subscription 0 Cart icon Cart Close icon You have no products in your basket yet Save more on your purchases! Buy 2 products and save 10% Buy 3 products and save 15% Buy 5 products and save 20% Savings automatically calculated. No voucher code required Profile icon Account Close icon Sign in New User? Create Account Your Subscription Your Owned Titles Your Account Your Orders Country Selection: CHANGE COUNTRY Modal Close icon Country selected Country selected United States Country selected United Kingdom Country selected India Country selected Germany Country selected France Country selected Canada Country selected Russia Country selected Spain Country selected Brazil Country selected Australia Country selected -------------------------------------------------------------------------------- Argentina Country selected Austria Country selected Belgium Country selected Bulgaria Country selected Chile Country selected Colombia Country selected Cyprus Country selected Czechia Country selected Denmark Country selected Ecuador Country selected Egypt Country selected Estonia Country selected Finland Country selected Greece Country selected Hungary Country selected Indonesia Country selected Ireland Country selected Italy Country selected Japan Country selected Latvia Country selected Lithuania Country selected Luxembourg Country selected Malaysia Country selected Malta Country selected Mexico Country selected Netherlands Country selected New Zealand Country selected Norway Country selected Philippines Country selected Poland Country selected Portugal Country selected Romania Country selected Singapore Country selected Slovakia Country selected Slovenia Country selected South Africa Country selected South Korea Country selected Sweden Country selected Switzerland Country selected Taiwan Country selected Thailand Country selected Turkey Country selected Ukraine Country selected Arrow left icon All Products Best Sellers New Releases Books Videos Audiobooks Learning Hub Newsletters Free Learning Arrow right icon Home > Web Development > Web Programming > FastAPI Cookbook FASTAPI COOKBOOK: DEVELOP HIGH-PERFORMANCE APIS AND WEB APPLICATIONS WITH PYTHON Profile Icon Giunio De Luca By Giunio De Luca $24.99 $35.99 Book Aug 2024 358 pages 1st Edition eBook $24.99 $35.99 Print $32.99 $44.99 Subscription Free Trial Renews at $19.99p/m Profile Icon Giunio De Luca By Giunio De Luca $24.99 $35.99 Book Aug 2024 358 pages 1st Edition eBook $24.99 $35.99 Print $32.99 $44.99 Subscription Free Trial Renews at $19.99p/m eBook $24.99 $35.99 Print $32.99 $44.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 Buy Now ADD TO CART Table of content icon View table of contents Preview book icon Preview Book FASTAPI COOKBOOK 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: * Creation of virtual environments: https://docs.python.org/3/library/venv.html To brush up your knowledge with Git and get familiar with adding, staging and commiting operations, have a look at this guide: * Git simple guide: https://rogerdudler.github.io/git-guide/ UNDERSTANDING FASTAPI BASICS As we embark on our journey with FastAPI, it’s essential to build a solid foundation. FastAPI isn’t just another web framework; it’s a powerful tool designed to make your life as a developer easier, your applications faster, and your code more robust and maintainable. In this recipe, we’ll demystify the core concepts of FastAPI, delve into its unique features such as asynchronous programming, and guide you through creating and organizing your first endpoints. By the end of the recipe, you’ll have your first FastAPI server up and running – a milestone that marks the beginning of an exciting journey in modern web development. FastAPI is a modern, fast web framework for building APIs with Python based on standard Python type hints. Key features that define FastAPI are the following: * Speed: It’s one of the fastest frameworks for building APIs in Python, thanks to its underlying Starlette framework for web parts and Pydantic for data handling * Ease of use: FastAPI is designed to be easy to use, with intuitive coding that accelerates your development time * Automatic documentation: With FastAPI, the API documentation is generated automatically, a feature that is both a time-saver and a boon for developers HOW TO DO IT… We will now explore how to use those features effectively with some general guidance. We will go through the following steps: * Applying asynchronous programming to our existing endpoints to improve time efficiency * Exploring routers and endpoints to better organize large code bases * Running your first FastAPI server with a basic configuration * Exploring the automatic documentation APPLYING ASYNCHRONOUS PROGRAMMING One of the most powerful features of FastAPI is its support for asynchronous programming. This allows your applications to handle more requests simultaneously, making them more efficient. Asynchronous programming is a style of concurrent programming in which tasks are executed without blocking the execution of other tasks, improving the overall performance of your application. To integrate asynchronous programming smoothly, FastAPI leverages the async/await syntax (https://fastapi.tiangolo.com/async/) and automatically integrates asynchronous functions. So, the read_root() function in main.py from the previous code snippet in the Creating a new FastAPI project recipe can be written as follows: @app.get("/") async def read_root(): return {"Hello": "World"} In this case, the behavior of the code will be exactly the same as before. EXPLORING ROUTERS AND ENDPOINTS In FastAPI, organizing your code into routers and endpoints is a fundamental practice. This organization helps in making your code cleaner and more modular. ENDPOINTS Endpoints are the points at which API interactions happen. In FastAPI, an endpoint is created by decorating a function with an HTTP method, such as @app.get("/"). This signifies a GET request to the root of your application. Consider the following code snippet: from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"Hello": "World"} In this snippet, we define an endpoint for the root URL ("/"). When a GET request is made to this URL, the read_root function is invoked, returning a JSON response. ROUTERS When we need to handle multiple endpoints that are in different files, we can benefit from using routers. Routers assist us in grouping our endpoints into different modules, which makes our code base easier to maintain and understand. For example, we could use one router for operations related to users and another for operations related to products. To define a router, first create a new file in the fastapi_start folder called router_example.py. Then, create the router as follows: from fastapi import APIRouter router = APIRouter() @router.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id} You can now reuse it and attach the router to the FastAPI server instance in main.py: import router_example from fastapi import FastAPI app = FastAPI() app.include_router(router_example.router) @app.get("/") async def read_root(): return {"Hello": "World"} You now have the code to run the server that includes the router for the GET /items endpoint importer from another module. RUNNING YOUR FIRST FASTAPI SERVER To run your FastAPI application, you need to point Uvicorn to your app instance. If your file is named main.py and your FastAPI instance is called app, you can start your server like this at the fastapi_start folder level: $ uvicorn main:app --reload The --reload flag makes the server restart after code changes, making it ideal for development. Once the server is running, you can access your API at http://127.0.0.1:8000. If you visit this URL in your browser, you’ll see the JSON response from the "/" endpoint we have just created. EXPLORING THE AUTOMATIC DOCUMENTATION One of the most exciting features of FastAPI is its automatic documentation. When you run your FastAPI application, two documentation interfaces are automatically generated: Swagger UI and Redoc. You can access these at http://127.0.0.1:8000/docs for Swagger UI and http://127.0.0.1:8000/redoc for Redoc. These interfaces provide an interactive way to explore your API and test its functionality. SEE ALSO You can discover more about what we covered in the recipe at the following links: * First Steps: https://fastapi.tiangolo.com/tutorial/first-steps/ * Docs URLs: https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls * Concurrency and async / await: https://fastapi.tiangolo.com/async/ DEFINING YOUR FIRST API ENDPOINT Now that you have a fundamental grasp of FastAPI and your development environment is all set up, it’s time to take the next thrilling step: creating your first API endpoint. This is where the real magic of FastAPI begins to shine. You’ll see how effortlessly you can build a functional API endpoint, ready to respond to HTTP requests. In this recipe, you will create a basic draft of a backend service for a bookstore. GETTING READY Make sure you know how to start a basic FastAPI project from the Creating a new FastAPI project recipe. HOW TO DO IT... In the realm of web APIs, the GET request is perhaps the most common. It’s used to retrieve data from the server. In FastAPI, handling a GET request is simple and intuitive. Let’s create a basic GET endpoint. Imagine you’re building an API for a bookstore. Your first endpoint will provide information about a book when given its ID. Here’s how you do it: 1. Create a new bookstore folder that will contain the code you are going to write. 2. Create in it a main.py file containing the server instance: from fastapi import FastAPI app = FastAPI() @app.get("/books/{book_id}") async def read_book(book_id: int): return { "book_id": book_id, "title": "The Great Gatsby", "author": "F. Scott Fitzgerald" } In the preceding code snippet, the @app.get("/books/{book_id}") decorator tells FastAPI that this function will respond to GET requests at the /books/{book_id} path. {book_id} in the path is a path parameter, which you can use to pass values dynamically. FastAPI automatically extracts the book_id parameter and passes it to your function. Type hints and automatic data validation Notice the use of type hints (book_id: int). FastAPI uses these hints to perform data validation. If a request is made with a non-integer book_id parameter, FastAPI automatically sends a helpful error response. HOW IT WORKS… With your GET endpoint defined, run your FastAPI application using Uvicorn, just as you did previously: $ uvicorn main:app --reload On the terminal, you can read the message logs describing that the server is running on port 8000. One of FastAPI’s most beloved features is its automatic generation of interactive API documentation using Swagger UI. This tool allows you to test your API endpoints directly from your browser without writing any additional code, and you can directly check the presence of the newly created endpoint in it. USING SWAGGER UI To test your new GET endpoint, navigate to http://127.0.0.1:8000/docs in your browser. This URL brings up the Swagger UI documentation for your FastAPI application. Here, you’ll see your /books/{book_id} endpoint listed. Click on it, and you’ll be able to execute a test request right from the interface. Try inputting a book ID and see the response your API generates. POSTMAN – A VERSATILE ALTERNATIVE While Swagger UI is convenient for quick tests, you might want to use a more robust tool such as Postman for more complex scenarios. Postman is an API client that lets you build, test, and document your APIs more extensively. To use Postman, download and install it from Postman’s website (https://www.postman.com/downloads/). Once installed, create a new request. Set the method to GET and the request URL to your FastAPI endpoint, http://127.0.0.1:8000/books/1. Hit Send, and Postman will display the response from your FastAPI server. WORKING WITH PATH AND QUERY PARAMETERS One of the most crucial aspects of API development is handling parameters. Parameters allow your API to accept input from users, making your endpoints dynamic and responsive. In this recipe, we will explore how to capture and handle path, query parameters, and test them efficiently, enhancing the flexibility and functionality of your FastAPI applications. GETTING READY To follow the recipe, make sure you know how to create a basic endpoint from the previous recipe. HOW TO DO IT… Path parameters are parts of the URL that are expected to change. For instance, in an endpoint such as /books/{book_id}, book_id is a path parameter. FastAPI allows you to capture these parameters effortlessly and use them in your function. 1. Let’s expand our bookstore API with a new endpoint that uses path parameters. This time, we’ll create a route to get information about a specific author: @app.get("/authors/{author_id}") async def read_author(author_id: int): return { "author_id": author_id, "name": "Ernest Hemingway" } The name will not change; however, the author_id value will be the one provided by the query request. Query parameters are used to refine or customize the response of an API endpoint. They can be included in the URL after a question mark (?). For instance, /books?genre=fiction&year=2010 might return only books that fall under the fiction genre released in 2010. 2. Let’s add query parameters to our existing endpoint. Suppose we want to allow users to filter books by their publication year: @app.get("/books") async def read_books(year: int = None): if year: return { "year": year, "books": ["Book 1", "Book 2"] } return {"books": ["All Books"]} Here, year is an optional query parameter. By assigning None as a default value, we make it optional. If a year is specified, the endpoint returns books from that year; otherwise, it returns all books. Exercise Using the APIRouter class, refactor each endpoint in a separate file and add the route to the FastAPI server. HOW IT WORKS… Now, from the command terminal, spin up the server with Uvicorn by running the following command: $ uvicorn main:app Testing endpoints with path parameters can be done using Swagger UI or Postman, similar to how we tested our basic GET endpoint. In Swagger UI, at http://localhost:8000/docs, navigate to your /authors/{author_id} endpoint. You’ll notice that it prompts you to enter an author_id value before you can try it out. Enter a valid integer and execute the request. You should see a response with the author’s information. The GET /books endpoint will now show an optional field for the year query parameter. You can test it by entering different years and observing the varying responses. If you use Postman instead, create a new GET request with the http://127.0.0.1:8000/authors/1 URL. Sending this request should yield a similar response. In Postman, append the query parameter to the URL like so: http://127.0.0.1:8000/books?year=2021. Sending this request should return books published in the year 2021. SEE ALSO You can find more about path and query parameters in the FastAPI official documentation at the following links: * Path Parameters: https://fastapi.tiangolo.com/tutorial/path-params/ * Query Parameters: https://fastapi.tiangolo.com/tutorial/query-params/ DEFINING AND USING REQUEST AND RESPONSE MODELS In the world of API development, data handling is a critical aspect that determines the robustness and reliability of your application. FastAPI simplifies this process through its seamless integration with Pydantic, a data validation and settings management library using Python type annotations. The recipe will show you how to define and use request and response models in FastAPI, ensuring your data is well structured, validated, and clearly defined. Pydantic models are a powerful feature for data validation and conversion. They allow you to define the structure, type, and constraints of the data your application handles, both for incoming requests and outgoing responses. In this recipe, we will see how to use Pydantic to ensure that your data conforms to the specified schema, providing an automatic layer of safety and clarity. GETTING READY This recipe requires you to know how to set up a basic endpoint in FastAPI. HOW TO DO IT... We will break the process into the following steps: 1. Creating the model 2. Defining the request body 3. Validating request data 4. Managing response formats CREATING THE MODEL Let’s create a Pydantic BaseModel class for our bookstore application in a new file called models.py. Suppose we want to have a model for a book that includes the title, author, and publication year: from pydantic import BaseModel class Book(BaseModel): title: str author: str year: int Here, Book is a Pydantic BaseModel class with three fields: title, author, and year. Each field is typed, ensuring that any data conforming to this model will have these attributes with the specified data types. DEFINING THE REQUEST BODY In FastAPI, Pydantic models are not just for validation. They also serve as the request body. Let’s add an endpoint to our application where users can add new books: from models import Book @app.post("/book") async def create_book(book: Book): return book In this endpoint, when a user sends a POST request to the /book endpoint with JSON data, FastAPI automatically parses and validates it against the Book model. If the data is invalid, the user gets an automatic error response. VALIDATING REQUEST DATA Pydantic offers advanced validation features. For instance, you can add regex validations, default values, and more: from pydantic import BaseModel, Field class Book(BaseModel): title: str = Field(..., min_length=1, max_length=100) author: str = Field(..., min_length=1, max_length=50) year: int = Field(..., gt=1900, lt=2100) For an exhaustive list of validation features, have a look at Pydantic’s official documentation: https://docs.pydantic.dev/latest/concepts/fields/. Next, you can proceed to manage the response format. MANAGING RESPONSE FORMATS FastAPI allows you to define response models explicitly, ensuring that the data returned by your API matches a specific schema. This can be particularly useful for filtering out sensitive data or restructuring the response. For example, let’s say you want the /allbooks GET endpoint to return a list of books, but only with their titles and authors, omitting the publication year. In main.py, add the following accordingly: from pydantic import BaseModel class BookResponse(BaseModel): title: str author: str @app.get("/allbooks") async def read_all_books() -> list[BookResponse]: return [ { "id": 1, "title": "1984", "author": "George Orwell"}, { "id": 1, "title": "The Great Gatsby", "author": "F. Scott Fitzgerald", }, ] Here, the -> list[BookResponse] function type hint tells FastAPI to use the BookResponse model for responses, ensuring that only the title and author fields are included in the response JSON. Alternatively, you can specify the response type in the endpoint decorator’s arguments as follows: @app.get("/allbooks", response_model= list[BookResponse]) async def read_all_books() -> Any: # rest of the endpoint content The response_model argument takes priority and can be used instead of the type hint to resolve type checker issues that may occur. Check the documentation at http://127.0.0.1:8000/docs. Unroll the /allbooks endpoint details, and you will notice the example value response based on the schema as follows: [ { "title": "string", "author": "string" } ] By mastering Pydantic models in FastAPI, you are now capable of handling complex data structures with ease and precision. You’ve learned to define request bodies and manage response formats, ensuring data consistency and integrity throughout your application. SEE ALSO Pydantic is a standalone project largely used for data validation in Python with many more features than what the recipe has shown. Feel free to have a look at the official documentation at the following link: * Pydantic: https://docs.pydantic.dev/latest/ You can see more on response model usage at the FastAPI official documentation link: * Response Model - Return Type: https://fastapi.tiangolo.com/tutorial/response-model/ HANDLING ERRORS AND EXCEPTIONS Error handling is an essential aspect of developing robust and reliable web applications. In FastAPI, managing errors and exceptions is not just about catching unexpected issues but also about proactively designing your application to respond to various error scenarios gracefully. This recipe will guide you through custom error handling, validating data and handling exceptions, and testing these scenarios to ensure your FastAPI applications are resilient and user-friendly. HOW TO DO IT… FastAPI provides built-in support for handling exceptions and errors. When an error occurs, FastAPI returns a JSON response containing details about the error, which is very useful for debugging. However, there are situations where you might want to customize these error responses for better user experience or security. Let’s create a custom error handler that catches a specific type of error and returns a custom response. For instance, if a requested resource is not found, you might want to return a more friendly error message. To do it, in the main.py file, add the following code accordingly: from fastapi import FastAPI, HTTPException from starlette.responses import JSONResponse @app.exception_handler(HTTPException) async def http_exception_handler(request, exc): return JSONResponse( status_code=exc.status_code, content={ "message": "Oops! Something went wrong" }, ) In this example, the http_exception_handler function will be used to handle HTTPException errors. Whenever an HTTPException error is raised anywhere in your application, FastAPI will use this handler to return a custom response. You can test the response by creating a new endpoint that raises an HTTP exception: @app.get("/error_endpoint") async def raise_exception(): raise HTTPException(status_code=400) The endpoint will explicitly throw the HTTP error response to showcase the customized message defined in the previous step. Now, spin the server from the command line with the following command: $ uvicorn main:app Open the browser at http://localhost:8000/error_endpoint, and you will have a JSON response like this: { "message": "Oops! Something went wrong" } The response returns the default message we defined for any HTTP exception returned by the code. THERE’S MORE… As discussed in the previous recipe, Defining and using request and response models, FastAPI uses Pydantic models for data validation. When a request is made with data that does not conform to the defined model, FastAPI automatically raises an exception and returns an error response. In some cases, you might want to customize the response for validation errors. FastAPI makes this quite straightforward: import json from fastapi import Request, status from fastapi.exceptions import RequestValidationError from fastapi.responses import PlainTextResponse @app.exception_handler(RequestValidationError) async def validation_exception_handler( request: Request, exc: RequestValidationError ): return PlainTextResponse( "This is a plain text response:" f" \n{json.dumps(exc.errors(), indent=2)}", status_code=status.HTTP_400_BAD_REQUEST, ) This custom handler will catch any RequestValidationError error and return a plain text response with the details of the error. If you try, for example, to call the POST /book endpoint with a number type of title instead of a string, you will get a response with a status code of 400 and body: This is a plain text response: [ { "type": "string_type", "loc": [ "body", "author" ], "msg": "Input should be a valid string", "input": 3, "url": "https://errors.pydantic.dev/2.5/v/string_type" }, { "type": "greater_than", "loc": [ "body", "year" ], "msg": "Input should be greater than 1900", "input": 0, "ctx": { "gt": 1900 }, "url": "https://errors.pydantic.dev/2.5/v/greater_than" } ] You can also, for example, mask the message to add a layer of security to protect from unwanted users using it incorrectly. This is all you need to customize responses when a request validation error occurs. You will use this basic knowledge as you move to the next chapter. Chapter 2 will teach you more about data management in web applications, showing you how to set up and use SQL and NoSQL databases and stressing data security. This will not only improve your technical skills but also increase your awareness of creating scalable and reliable FastAPI applications. SEE ALSO You can find more information about customizing errors and exceptions using FastAPI in the official documentation: * Handling Errors: https://fastapi.tiangolo.com/tutorial/handling-errors/ Left arrow icon PAGE 1 OF 9 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. 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 2, 2024 Length 358 pages Edition : 1st Edition Language : English ISBN-13 : 9781805127857 Category : Web Development Concepts : Web Programming Tools : FastAPI 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 Buy Now ADD TO CART PRODUCT DETAILS Publication date : Aug 2, 2024 Length 358 pages Edition : 1st Edition Language : English ISBN-13 : 9781805127857 Category : Web Development Concepts : Web Programming Tools : FastAPI 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 START FREE TRIAL BUY NOW $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 START FREE TRIAL BUY NOW $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 START FREE TRIAL BUY NOW TABLE OF CONTENTS 15 Chapters Preface Chevron down icon Chevron up icon Preface Who this book is for What this book covers To get the most out of this book Conventions used Sections Get in touch Share Your Thoughts 1. Chapter 1: First Steps with FastAPI Chevron down icon Chevron up icon Chapter 1: First Steps with FastAPI Technical requirements 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 2. Chapter 2: Working with Data Chevron down icon Chevron up icon Chapter 2: Working with Data Technical requirements Setting up SQL databases Understanding CRUD operations with SQLAlchemy Integrating MongoDB for NoSQL data storage Working with data validation and serialization Working with file uploads and downloads Handling asynchronous data operations Securing sensitive data and best practices 3. Chapter 3: Building RESTful APIs with FastAPI Chevron down icon Chevron up icon Chapter 3: Building RESTful APIs with FastAPI Technical requirements Creating CRUD operations Creating RESTful Endpoints Testing your RESTful API Handling complex queries and filtering Versioning your API Securing your API with OAuth2 Documenting your API with Swagger and Redoc 4. Chapter 4: Authentication and Authorization Chevron down icon Chevron up icon Chapter 4: Authentication and Authorization Technical requirements Setting up user registration Working with OAuth2 and JWT for authentication Setting up RBAC Using third-party authentication Implementing MFA Handling API key authentication Handling session cookies and logout functionality 5. Chapter 5: Testing and Debugging FastAPI Applications Chevron down icon Chevron up icon Chapter 5: Testing and Debugging FastAPI Applications Technical requirements Setting up testing environments Writing and running unit tests Testing API Endpoints Running tests techniques Handling logging messages Debugging techniques Performance testing for high traffic applications 6. Chapter 6: Integrating FastAPI with SQL Databases Chevron down icon Chevron up icon Chapter 6: Integrating FastAPI with SQL Databases Technical requirements Setting up SQLAlchemy Implementing CRUD operations Working with migrations Handling relationships in SQL databases Optimizing SQL queries for performance Securing sensitive data in SQL databases Handling transactions and concurrency 7. Chapter 7: Integrating FastAPI with NoSQL Databases Chevron down icon Chevron up icon Chapter 7: Integrating FastAPI with NoSQL Databases Technical requirements Setting up MongoDB with FastAPI CRUD operations in MongoDB Handling relationships in NoSQL databases Working with indexes in MongoDB Exposing sensitive data from NoSQL databases Integrating FastAPI with Elasticsearch Using Redis for caching in FastAPI 8. Chapter 8: Advanced Features and Best Practices Chevron down icon Chevron up icon Chapter 8: Advanced Features and Best Practices Technical requirements Implementing dependency injection Creating custom middleware Internationalization and localization Optimizing application performance Implementing rate limiting Implementing background tasks 9. Chapter 9: Working with WebSocket Chevron down icon Chevron up icon Chapter 9: Working with WebSocket Technical requirements Setting up WebSockets in FastAPI Sending and receiving messages over WebSockets Handling WebSocket connections and disconnections Handling WebSocket errors and exceptions Implementing chat functionality with WebSockets Optimizing WebSocket performance Securing WebSocket connections with OAuth2 10. Chapter 10: Integrating FastAPI with other Python Libraries Chevron down icon Chevron up icon Chapter 10: Integrating FastAPI with other Python Libraries Technical requirements Integrating FastAPI with gRPC Connecting FastAPI with GraphQL Using ML models with Joblib Integrating FastAPI with Cohere Integrating FastAPI with LangChain 11. Chapter 11: Middleware and Webhooks Chevron down icon Chevron up icon Chapter 11: Middleware and Webhooks Technical requirements Creating custom ASGI middleware Developing middleware for request modification Developing middleware for response modification Handling CORS with middleware Restricting incoming requests from hosts Implementing webhooks 12. Chapter 12: Deploying and Managing FastAPI Applications Chevron down icon Chevron up icon Chapter 12: Deploying and Managing FastAPI Applications Technical requirements Running the server with the FastAPI CLI Enabling HTTPS on FastAPI applications Running FastAPI applications in Docker containers Running the server across multiple workers Deploying your FastAPI application on the cloud Shipping FastAPI applications with Hatch 13. Index Chevron down icon Chevron up icon Index Why subscribe? 14. Other Books You May Enjoy Chevron down icon Chevron up icon Other Books You May Enjoy Packt is searching for authors like you Share Your Thoughts Download a free PDF copy of this book RECOMMENDATIONS FOR YOU 1 of 10 Left arrow icon Responsive Web Design with HTML5 and CSS Read more Sep 2022 498 pages Full star icon 4 ebook eBook * ebook eBook $24.99 * print Print $44.99 $24.99 $35.99 $44.99 ADD TO CART Building Production-Grade Web Applications with Supabase Read more Aug 2024 534 pages ebook eBook * ebook eBook $27.98 * print Print $49.99 $27.98 $39.99 $49.99 ADD TO CART C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals Read more Nov 2023 828 pages Full star icon 4.5 ebook eBook * ebook eBook $27.98 * print Print $49.99 $27.98 $39.99 $49.99 ADD TO CART Django 5 By Example Read more Apr 2024 820 pages Full star icon 3 ebook eBook * ebook eBook $27.98 * print Print $36.99 $27.98 $39.99 $36.99 $49.99 ADD TO CART Vue.js 3 for Beginners Read more Sep 2024 302 pages ebook eBook * ebook eBook $20.98 * print Print $36.99 $20.98 $29.99 $36.99 ADD TO CART FastAPI Cookbook Read more Aug 2024 358 pages ebook eBook * ebook eBook $24.99 * print Print $32.99 $24.99 $35.99 $32.99 $44.99 ADD TO CART Software Architecture with C# 12 and .NET 8 Read more Feb 2024 756 pages Full star icon 3.5 ebook eBook * ebook eBook $27.98 * print Print $49.99 $27.98 $39.99 $49.99 ADD TO CART Effective Angular Read more Aug 2024 400 pages ebook eBook * ebook eBook $24.99 * print Print $44.99 $24.99 $35.99 $44.99 ADD TO CART Web Development with Blazor Read more Apr 2024 366 pages Full star icon 5 ebook eBook * ebook eBook $27.98 * print Print $49.99 $27.98 $39.99 $49.99 ADD TO CART React and React Native Read more Apr 2024 508 pages Full star icon 5 ebook eBook * ebook eBook $24.99 * print Print $43.99 $24.99 $35.99 $43.99 ADD TO CART Right arrow icon ABOUT THE AUTHOR Profile icon Giunio De Luca LinkedIn icon Giunio De Luca is a software engineer with over 10 years of experience in fields such as physics, sports, and administration. He graduated in industrial engineering from the University of Basilicata and holds a PhD in numerical simulations from Paris-Saclay University. His work spans developing advanced algorithms, creating sports analytics applications, and improving administrative processes. As an independent consultant, he collaborates with research labs, government agencies, and start-ups across Europe. He also supports coding education in schools and universities through workshops, lectures, and mentorship programs, inspiring the next generation of software engineers with his expertise and dedication. Read more See other products by Giunio De Luca 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. Arrow left icon Front End Web Development Web Programming Server Side Web Development CMS Full Stack Web Development Web Design Learning Management System Ecommerce Responsive Web Development Microservices Arrow right icon Legal Terms and Conditions Privacy Policy Cookie Policy Shipping Policy Cancellation Policy Return Policy Support Help Contact Us Business Partnerships Sponsored eBooks Custom eBooks Careers Become an author Packt+ Membership Subscription DataPro SecPro TechLeaders United States Company Address: Packt Publishing Ltd, Grosvenor House, 11 St Paul's Square, Birmingham, B3 1RB © 2024 Packt Publishing Limited All Rights Reserved We use some essential cookies to make this service work. We’d also like to use analytics cookies so we can understand how you use the service and make improvements. ACCEPT ALL COOKIES ACCEPT ESSENTIAL COOKIES REJECT ALL COOKIES -------------------------------------------------------------------------------- Close icon Signed in users are eligible for personalised offers and content recommendations. Country selected Sign in with Packt Gmail Sign in with Google Github Sign in with Github -------------------------------------------------------------------------------- You are browsing a version of our website which may not be the most relevant option for you. We suggest changing to the following version. Country selected OK Germany