OG Images in Python

This guide shows you how to generate OG images in Python with FastOG — Django, FastAPI, or Flask — by signing an HMAC URL and rendering dynamic Open Graph images on the fly. Credit-based with a free account (100 starter credits; create your API key in the dashboard); hit the Free OG Image Tester to see a template before you integrate.

Complete guide to implementing HMAC-signed OG image URLs in Python.

Quick Start

1. Create the signer module

python
# utils/fastog.py
import hmac
import hashlib
import time
import os
from urllib.parse import urlencode, urlparse, urlunparse

def generate_signed_og_url(params: dict, options: dict = None) -> str:
    options = options or {}
    base_url = options.get('base_url', os.environ.get('FASTOG_BASE_URL', 'https://fastog.com/api/v1/og'))
    api_key = options.get('api_key', os.environ.get('FASTOG_API_KEY'))
    hmac_secret = options.get('hmac_secret', os.environ.get('FASTOG_HMAC_SECRET'))

    if not api_key or not hmac_secret:
        raise ValueError("Missing FASTOG_API_KEY or FASTOG_HMAC_SECRET")

    timestamp = int(time.time())
    key = api_key

    # Build signature
    message = f"GET/api/v1/og{timestamp}{key}"
    signature = hmac.new(
        hmac_secret.encode(),
        message.encode(),
        hashlib.sha256
    ).hexdigest()

    # Build URL
    query_params = {**params, 'key': key, 's': signature, 't': timestamp}
    return f"{base_url}?{urlencode(query_params)}"

2. Environment variables

bash
# .env
FASTOG_API_KEY=sk_your_full_api_key_here
FASTOG_HMAC_SECRET=your_64_char_hex_secret_here
bash
pip install python-dotenv
python
# config.py
from dotenv import load_dotenv
load_dotenv()

Django

Signer Service

python
# services/fastog.py
from utils.fastog import generate_signed_og_url

class QuickogService:
    @staticmethod
    def get_og_url(template: str, **params) -> str:
        return generate_signed_og_url({
            'template': template,
            **params,
        })

View

python
# views.py
from django.shortcuts import render
from services.fastog import QuickogService

def blog_post(request, slug):
    post = get_post(slug)

    og_image_url = QuickogService.get_og_url(
        template='blog',
        title=post.title,
        subtitle=post.excerpt,
        author=post.author.name,
    )

    return render(request, 'blog/post.html', {
        'post': post,
        'og_image_url': og_image_url,
    })

Template

django
{# templates/blog/post.html #}
<!DOCTYPE html>
<html>
<head>
    <meta property="og:image" content="{{ og_image_url }}" />
    <meta property="og:title" content="{{ post.title }}" />
    <meta property="og:description" content="{{ post.excerpt }}" />
</head>
<body>
    <h1>{{ post.title }}</h1>
    <p>{{ post.excerpt }}</p>
</body>
</html>

Custom Template Tag

python
# templatetags/fastog_tags.py
from django import template
from services.fastog import QuickogService

register = template.Library()

@register.simple_tag
def og_image_url(template_name, **params):
    return QuickogService.get_og_url(template_name, **params)
django
{# In template #}
{% load fastog_tags %}
<meta property="og:image" content="{% og_image_url 'blog' title=post.title subtitle=post.excerpt %}" />

FastAPI

python
# main.py
from fastapi import FastAPI, Query
from pydantic import BaseModel
from utils.fastog import generate_signed_og_url

app = FastAPI()

class OgRequest(BaseModel):
    title: str
    template: str = "default"
    subtitle: str | None = None

@app.get("/api/og")
def generate_og(title: str = Query(...), template: str = Query("default")):
    og_url = generate_signed_og_url({
        'template': template,
        'title': title,
    })
    return {"ogImageUrl": og_url}

@app.get("/blog/{slug}")
async def blog_post(slug: str):
    post = await get_post(slug)

    og_url = generate_signed_og_url({
        'template': 'blog',
        'title': post.title,
        'subtitle': post.excerpt,
    })

    return {"post": post, "ogImageUrl": og_url}

Flask

python
# app.py
from flask import Flask, render_template, request, jsonify
from utils.fastog import generate_signed_og_url

app = Flask(__name__)

@app.route("/blog/<slug>")
def blog_post(slug):
    post = get_post(slug)

    og_image_url = generate_signed_og_url({
        'template': 'blog',
        'title': post['title'],
        'subtitle': post['excerpt'],
    })

    return render_template('blog/post.html', post=post, og_image_url=og_image_url)

@app.route("/api/og")
def api_og():
    title = request.args.get('title')
    template = request.args.get('template', 'default')

    if not title:
        return jsonify({'error': 'Missing title'}), 400

    og_url = generate_signed_og_url({
        'template': template,
        'title': title,
    })

    return jsonify({'ogImageUrl': og_url})

E-commerce Example

python
# views.py
def product_detail(request, product_id):
    product = get_product(product_id)

    og_image_url = generate_signed_og_url({
        'template': 'ecommerce',
        'title': product.name,
        'price': product.formatted_price,
        'image': product.image_url,
    })

    return render(request, 'products/detail.html', {
        'product': product,
        'og_image_url': og_image_url,
    })

User Profile Example

python
def user_profile(request, username):
    user = get_user(username)

    og_image_url = generate_signed_og_url({
        'template': 'profile',
        'name': user.name,
        'avatar': user.avatar_url,
        'bio': user.bio,
    })

    return render(request, 'profile/show.html', {
        'user': user,
        'og_image_url': og_image_url,
    })

Common Pitfalls

Timestamp in Milliseconds

Wrong: int(time.time() * 1000)

Correct: int(time.time())

Wrong Message Format

Wrong: f"GET:/api/v1/og:{timestamp}:{key}"

Correct: f"GET/api/v1/og{timestamp}{key}"

Using Full API Key

Wrong: 'key': api_key

Correct: 'key': api_key

Full API Reference

Related

Try it free — no signup required

Preview and test dynamic OG images in seconds.

Open the Free OG Image Tester