Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
FastAPI Cookbook

You're reading from   FastAPI Cookbook Develop high-performance APIs and web applications with Python

Arrow left icon
Product type Paperback
Published in Aug 2024
Publisher Packt
ISBN-13 9781805127857
Length 358 pages
Edition 1st Edition
Languages
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Giunio De Luca Giunio De Luca
Author Profile Icon Giunio De Luca
Giunio De Luca
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Chapter 1: First Steps with FastAPI FREE CHAPTER 2. Chapter 2: Working with Data 3. Chapter 3: Building RESTful APIs with FastAPI 4. Chapter 4: Authentication and Authorization 5. Chapter 5: Testing and Debugging FastAPI Applications 6. Chapter 6: Integrating FastAPI with SQL Databases 7. Chapter 7: Integrating FastAPI with NoSQL Databases 8. Chapter 8: Advanced Features and Best Practices 9. Chapter 9: Working with WebSocket 10. Chapter 10: Integrating FastAPI with other Python Libraries 11. Chapter 11: Middleware and Webhooks 12. Chapter 12: Deploying and Managing FastAPI Applications 13. Index 14. Other Books You May Enjoy

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.

You have been reading a chapter from
FastAPI Cookbook
Published in: Aug 2024
Publisher: Packt
ISBN-13: 9781805127857
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.
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 $19.99/month. Cancel anytime
Banner background image