Reader small image

You're reading from  Building Data Science Applications with FastAPI - Second Edition

Product typeBook
Published inJul 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781837632749
Edition2nd Edition
Languages
Tools
Concepts
Right arrow
Author (1)
François Voron
François Voron
author image
François Voron

François Voron graduated from the University of Saint-Étienne (France) and the University of Alicante (Spain) with a master's degree in machine learning and data mining. A full stack web developer and a data scientist, François has a proven track record working in the SaaS industry, with a special focus on Python backends and REST APIs. He is also the creator and maintainer of FastAPI Users, the #1 authentication library for FastAPI, and is one of the top experts in the FastAPI community.
Read more about François Voron

Right arrow

Developing a RESTful API with FastAPI

Now it’s time to begin learning about FastAPI! In this chapter, we’ll cover the basics of FastAPI. We’ll go through very simple and focused examples that will demonstrate the different features of FastAPI. Each example will lead to a working API endpoint that you’ll be able to test yourself using HTTPie. In the final section of this chapter, we’ll show you a more complex FastAPI project, with routes split across several files. It will give you an overview of how you can structure your own application.

By the end of this chapter, you’ll know how to start a FastAPI application and how to write an API endpoint. You’ll also be able to handle request data and build a response according to your own logic. Finally, you’ll learn a way to structure a FastAPI project into several modules that will be easier to maintain and work with in the long term.

In this chapter, we’ll cover the following...

Technical requirements

You’ll need a Python virtual environment, as we set up in Chapter 1, Python Development Environment Setup.

You’ll find all the code examples of this chapter in the dedicated GitHub repository: https://github.com/PacktPublishing/Building-Data-Science-Applications-with-FastAPI-Second-Edition/tree/main/chapter03..

Creating a first endpoint and running it locally

FastAPI is a framework that is easy to use and quick to write. In the following example, you’ll realize that this is not just a promise. In fact, creating an API endpoint involves just a few lines:

chapter03_first_endpoint_01.py

from fastapi import FastAPIapp = FastAPI()
@app.get("/")
async def hello_world():
    return {"hello": "world"}

In this example, we define a GET endpoint at the root path, which always returns the {"hello": "world"} JSON response. To do this, we first instantiate a FastAPI object, app. It will be the main application object that will wire all the API routes.

Then, we simply define a coroutine that contains our route logic, the path operation function. Its return value is automatically...

Handling request parameters

The main goal of a representational state transfer (REST) API is to provide a structured way to interact with data. As such, it’s crucial for the end user to send some information to tailor the response they need, such as path parameters, query parameters, body payloads, headers, and so on.

Web frameworks usually ask you to manipulate a request object to retrieve the parts you are interested in and manually apply validation to handle them. However, that’s not necessary with FastAPI! Indeed, it allows you to define all of your parameters declaratively. Then, it’ll automatically retrieve them in the request and apply validation based on the type hints. This is why we introduced type hinting in Chapter 2, Python Programming Specificities: it’s used by FastAPI to perform data validation!

Next, we’ll explore how you can use this feature to retrieve and validate this input data from different parts of the request.

Path...

Customizing the response

In the previous sections, you learned that directly returning a dictionary or a Pydantic object in your path operation function was enough for FastAPI to return a JSON response.

Most of the time, you’ll want to customize this response a bit further; for instance, by changing the status code, raising validation errors, and setting cookies. FastAPI offers different ways to do this, from the simplest case to the most advanced one. First, we’ll learn how to customize the response declaratively by using path operation parameters.

Path operation parameters

In the Creating a first endpoint and running it locally section, you learned that in order to create a new endpoint, you had to put a decorator on top of the path operation function. This decorator accepts a lot of options, including ones to customize the response.

The status code

The most obvious thing to customize in an HTTP response is the status code. By default, FastAPI will always...

Structuring a bigger project with multiple routers

When building a real-world web application, you’re likely to have a lot of code and logic: data models, API endpoints, and services. Of course, all of those can’t live in a single file; we have to structure the project so that it’s easy to maintain and evolve.

FastAPI supports the concept of routers. They are “sub-parts” of your API and are usually dedicated to a single type of object, such as users or posts, which are defined in their own files. You can then include them in your main FastAPI app so that it can route it accordingly.

In this section, we’ll explore how to use routers and how you can structure a FastAPI project. While this structure is one way to do it and works quite well, it’s not a golden rule and can be adapted to your own needs.

In the code examples repository, there is a folder named chapter03_project, which contains a sample project with this structure:...

Summary

Well done! You’re now acquainted with all the basic features of FastAPI. Throughout this chapter, you learned how to create and run API endpoints where you can validate and retrieve data from all parts of an HTTP request: the path, the query, the parameters, the headers, and, of course, the body. You also learned how to tailor the HTTP response to your needs, whether it is a simple JSON response, an error, or a file to download. Finally, you looked at how to define separate API routers and include them in your main application to keep a clean and maintainable project structure.

You have enough knowledge now to start building your own API with FastAPI. In the next chapter, we’ll focus on Pydantic models. You now know that they are at the core of the data validation features of FastAPI, so it’s crucial to fully understand how they work and how to manipulate them efficiently.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Building Data Science Applications with FastAPI - Second Edition
Published in: Jul 2023Publisher: PacktISBN-13: 9781837632749
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
François Voron

François Voron graduated from the University of Saint-Étienne (France) and the University of Alicante (Spain) with a master's degree in machine learning and data mining. A full stack web developer and a data scientist, François has a proven track record working in the SaaS industry, with a special focus on Python backends and REST APIs. He is also the creator and maintainer of FastAPI Users, the #1 authentication library for FastAPI, and is one of the top experts in the FastAPI community.
Read more about François Voron