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

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:

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