Appearance
Python Examples
Integration examples for Python applications.
Installation
bash
pip install requestsBasic Example
python
import requests
import os
def generate_og_image(title, subtitle="", theme="dark"):
"""Generate an OG image and return the image bytes."""
response = requests.post(
"https://ogimageapi.io/api/generate",
headers={
"Content-Type": "application/json",
"X-API-Key": os.environ.get("OG_IMAGE_API_KEY")
},
json={
"title": title,
"subtitle": subtitle,
"theme": theme
}
)
response.raise_for_status()
return response.content
# Usage
image_bytes = generate_og_image(
title="Hello from Python",
subtitle="A simple example"
)
with open("og-image.png", "wb") as f:
f.write(image_bytes)Full-Featured Client
python
# og_image_client.py
import requests
import os
from typing import Optional
from dataclasses import dataclass
@dataclass
class Usage:
plan: str
quota: int
used: int
remaining: int
percent_used: float
reset_date: str
class OGImageClient:
"""Client for OG Image API."""
def __init__(self, api_key: Optional[str] = None):
self.api_key = api_key or os.environ.get("OG_IMAGE_API_KEY")
self.base_url = "https://ogimageapi.io"
if not self.api_key:
raise ValueError("API key is required")
def generate(
self,
title: str,
subtitle: str = "",
author_name: str = "",
author_avatar_url: str = "",
theme: str = "dark",
template: str = "default"
) -> bytes:
"""Generate an OG image."""
response = requests.post(
f"{self.base_url}/api/generate",
headers={
"Content-Type": "application/json",
"X-API-Key": self.api_key
},
json={
"title": title,
"subtitle": subtitle,
"author_name": author_name,
"author_avatar_url": author_avatar_url,
"theme": theme,
"template": template
}
)
if not response.ok:
error = response.json()
raise Exception(f"API Error: {error.get('message', 'Unknown error')}")
return response.content
def get_usage(self) -> Usage:
"""Get current usage statistics."""
response = requests.get(
f"{self.base_url}/api/user/usage",
headers={"X-API-Key": self.api_key}
)
response.raise_for_status()
data = response.json()
return Usage(
plan=data["plan"],
quota=data["quota"],
used=data["used"],
remaining=data["remaining"],
percent_used=data["percent_used"],
reset_date=data["reset_date"]
)Usage:
python
from og_image_client import OGImageClient
client = OGImageClient()
# Generate image
image = client.generate(
title="Python Integration Guide",
subtitle="Step-by-step tutorial",
theme="dark",
template="vibrant"
)
with open("guide.png", "wb") as f:
f.write(image)
# Check usage
usage = client.get_usage()
print(f"Used {usage.used}/{usage.quota} ({usage.percent_used}%)")Django Integration
python
# views.py
from django.http import HttpResponse
from django.views import View
import requests
import os
class OGImageView(View):
"""Generate OG images on-demand."""
def get(self, request):
title = request.GET.get("title", "Default Title")
subtitle = request.GET.get("subtitle", "")
response = requests.post(
"https://ogimageapi.io/api/generate",
headers={
"Content-Type": "application/json",
"X-API-Key": os.environ.get("OG_IMAGE_API_KEY")
},
json={
"title": title,
"subtitle": subtitle,
"theme": "dark"
}
)
if not response.ok:
return HttpResponse(
response.json().get("message", "Error"),
status=response.status_code
)
return HttpResponse(
response.content,
content_type="image/png"
)
# urls.py
from django.urls import path
from .views import OGImageView
urlpatterns = [
path("og/", OGImageView.as_view(), name="og-image"),
]Flask Integration
python
from flask import Flask, request, Response
import requests
import os
app = Flask(__name__)
@app.route("/og")
def og_image():
title = request.args.get("title", "Default Title")
subtitle = request.args.get("subtitle", "")
response = requests.post(
"https://ogimageapi.io/api/generate",
headers={
"Content-Type": "application/json",
"X-API-Key": os.environ.get("OG_IMAGE_API_KEY")
},
json={
"title": title,
"subtitle": subtitle,
"theme": "dark"
}
)
if not response.ok:
return response.json(), response.status_code
return Response(
response.content,
mimetype="image/png",
headers={"Cache-Control": "public, max-age=86400"}
)
if __name__ == "__main__":
app.run()Batch Processing
python
import requests
import os
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
API_KEY = os.environ.get("OG_IMAGE_API_KEY")
OUTPUT_DIR = Path("./og-images")
def generate_image(post):
"""Generate a single OG image."""
response = requests.post(
"https://ogimageapi.io/api/generate",
headers={
"Content-Type": "application/json",
"X-API-Key": API_KEY
},
json={
"title": post["title"],
"subtitle": post.get("subtitle", ""),
"theme": "dark"
}
)
if response.ok:
output_path = OUTPUT_DIR / f"{post['slug']}.png"
output_path.write_bytes(response.content)
print(f"✓ {post['slug']}")
return True
else:
print(f"✗ {post['slug']}: {response.json().get('message')}")
return False
def main():
posts = [
{"slug": "intro", "title": "Introduction", "subtitle": "Getting started"},
{"slug": "basics", "title": "The Basics", "subtitle": "Core concepts"},
{"slug": "advanced", "title": "Advanced Topics", "subtitle": "Deep dive"},
]
OUTPUT_DIR.mkdir(exist_ok=True)
# Process in parallel (be mindful of rate limits)
with ThreadPoolExecutor(max_workers=3) as executor:
results = list(executor.map(generate_image, posts))
success = sum(results)
print(f"\nGenerated {success}/{len(posts)} images")
if __name__ == "__main__":
main()