Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying FastAPI Cookbook
  • Table Of Contents Toc
  • Feedback & Rating feedback
FastAPI Cookbook

FastAPI Cookbook

By : Giunio De Luca
4.3 (4)
close
close
FastAPI Cookbook

FastAPI Cookbook

4.3 (4)
By: Giunio De Luca

Overview of this book

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.
Table of Contents (15 chapters)
close
close

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.

Create a Note

Modal Close icon
You need to login to use this feature.
notes
bookmark search playlist download font-size

Change the font size

margin-width

Change margin width

day-mode

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Delete Note

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Edit Note

Modal Close icon
Write a note (max 255 characters)
Cancel
Update Note

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY