Mr. Editor-in-chief Mr. Editor-in-chief March 13, 2022 Updated April 24, 2026

Redis Crash Course

Installation

sudo apt-get install redis
# Start redis server
redis-server
# By default Redis does not run as a daemon. Set daemonize yes from daemonize no in your redis.conf if needed
redis-cli

Redis Through Docker

# Learn Redis with Docker if you don't have a Linux machine available for you to play with
docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:latest
# You can use RedisInsight GUI by pointing your browser to localhost:8001
docker exec -it redis-stack redis-cli
# String
set name kyle
get name
set age 26
get age
keys *
del age
exists age
exists name
flushall
keys *

set name kyle
expire name 10
ttl name
ttl name

setex name 10 kyle
ttl name
ttl name

# List
lpush friends Adam
lrange friends 0 -1

lpush friends Eve
lpop friends
rpush friends Eve
lrange friends 0 -1
rpop friends

# Set
sadd hobbies 'weight lifting'
smembers hobbies

sadd hobbies 'weight lifting'
sadd hobbies 'music'
smembers hobbies

srem hobbies music
smembers hobbies

# Hash
hset person name kyle
hget person name
hgetall person

hset person age 26
hgetall person

hdel person age
hgetall person

hexists person age
hexists person name

A Simple Use Case

# pip install fastapi "uvicorn[standard]" redis requests

# main.py
from fastapi import FastAPI
import redis
import requests
import json

rd = redis.Redis(host='localhost', port=6379, db=0)
app = FastAPI()


@app.get('/photos')
def get_photos():
    if rd.get('photos'):
       print('cache hit')
       photos = rd.get('photos')
       return json.loads(photos)
    else:
        print('cache miss')
        r = requests.get('https://jsonplaceholder.typicode.com/photos')

        # rd.set('photos', r.text)
        # rd.expire('photos', 5)

        # ---- or using redis cli command
        rd.execute_command('set', 'photos', r.text)
        rd.execute_command('expire', 'photos', 5)
        return r.json()

# uvicorn main:app --reload