Python FastAPI Redis

Introduction

In this article, we will explore how to use Redis with FastAPI in Python. Redis is an open-source, in-memory data structure store, used as a database, cache, and message broker. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+.

We will cover the following topics:

  1. What is Redis?
  2. Why use Redis with FastAPI?
  3. Installing Redis and FastAPI
  4. Redis Basics
  5. Integrating Redis with FastAPI
  6. Caching with Redis in FastAPI
  7. Pub-Sub with Redis in FastAPI
  8. Conclusion

1. What is Redis?

Redis is an in-memory data structure store that can be used as a database, cache, and message broker. It supports various data structures such as strings, lists, sets, and hashes, and provides atomic operations on these data structures. Redis is known for its high performance, scalability, and flexibility. It can be used in a wide range of applications, from simple caching to real-time analytics and messaging systems.

2. Why use Redis with FastAPI?

FastAPI is a modern web framework that is designed to be fast and efficient. It is built on top of Starlette, which is a high-performance asyncio web framework. By combining FastAPI with Redis, we can take advantage of Redis's speed and efficiency to enhance the performance of our FastAPI applications. Redis can be used for caching data, storing session information, and implementing real-time features such as pub-sub.

3. Installing Redis and FastAPI

To get started, we need to install Redis and FastAPI. You can install Redis by following the instructions on the official Redis website. For FastAPI, you can install it using pip:

pip install fastapi

4. Redis Basics

Before we dive into integrating Redis with FastAPI, let's quickly go over some Redis basics.

Connecting to Redis

To connect to Redis from Python, we can use the redis package. We first need to import the package and create a Redis client:

import redis

# Create a Redis client
r = redis.Redis(host='localhost', port=6379, db=0)

Setting and Getting Values

We can set a value in Redis using the set command:

r.set('key', 'value')

To get the value, we can use the get command:

value = r.get('key')

Expiring Keys

We can set an expiration time for a key in Redis using the expire command:

r.expire('key', 60)  # Expire the key after 60 seconds

Pub-Sub

Redis supports Pub-Sub messaging, where publishers send messages to channels and subscribers receive messages from channels. To publish a message, we can use the publish command:

r.publish('channel', 'message')

To subscribe to a channel and receive messages, we can use the subscribe command:

p = r.pubsub()
p.subscribe('channel')

for message in p.listen():
    print(message)

5. Integrating Redis with FastAPI

Now that we have covered the basics of Redis, let's see how we can integrate it with FastAPI.

Creating a Redis Client

First, we need to create a Redis client and establish a connection to the Redis server. We can do this in the main FastAPI file:

import redis
from fastapi import FastAPI

app = FastAPI()

# Create a Redis client
r = redis.Redis(host='localhost', port=6379, db=0)

Using Redis in FastAPI Endpoints

We can now use the Redis client in our FastAPI endpoints. For example, let's create an endpoint to get and set a value in Redis:

@app.get('/redis/{key}')
def get_value(key: str):
    value = r.get(key)
    return {'key': key, 'value': value}

@app.put('/redis/{key}')
def set_value(key: str, value: str):
    r.set(key, value)
    return {'key': key, 'value': value}

Running the FastAPI Application

To run the FastAPI application, we can use the uvicorn command:

uvicorn main:app --reload

6. Caching with Redis in FastAPI

One of the main benefits of using Redis with FastAPI is caching. We can cache the responses of our API endpoints to improve performance and reduce the load on our backend services.

Using Redis Cache Middleware

FastAPI provides a built-in cache middleware called CacheControlMiddleware, which can be used to cache responses based on the Cache-Control header. To enable caching, we need to add the middleware to our FastAPI application:

from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisCacheBackend

# Create a Redis cache backend
cache_backend = RedisCacheBackend(redis=r)

# Add the Redis cache backend to FastAPI
FastAPICache.init(cache_backend)
app