FastAPI SEO and hiding the API docs
· 4 min read
FastAPI is built for APIs, and an API has nothing to rank. If your app serves JSON to a mobile app or a separate front end, you can skip this post. If it also serves pages that people should find in a search engine, the pages need the same basics as any site. The good news is that a FastAPI app can render HTML on the server with Jinja templates, and search engines are happy with that. This post covers the code, and one trap that is specific to FastAPI.
Render real HTML
Install Jinja2 (add jinja2 to requirements.txt) and set up templates:
import os
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.responses import PlainTextResponse, Response
from fastapi.templating import Jinja2Templates
SITE_URL = os.environ.get("SITE_URL", "http://localhost:8000").rstrip("/")
DOCS_ON = os.environ.get("DEBUG", "") == "1"
app = FastAPI(
docs_url="/docs" if DOCS_ON else None,
redoc_url=None,
openapi_url="/openapi.json" if DOCS_ON else None,
)
templates = Jinja2Templates(directory=Path(__file__).parent / "templates")
templates.env.globals["site_url"] = SITE_URL
@app.get("/")
def home(request: Request):
return templates.TemplateResponse(request, "home.html", {"title": "Home", "description": "What this site does, in one sentence."})
Why SITE_URL from an environment variable instead of reading the address from the request? Behind a proxy, the app often sees http and an internal host, so any absolute link you build from the request comes out wrong. Setting the real public address once, and using it everywhere, avoids that whole class of bug. On Pharos you set it on the app's Environment page, for example to https://yourapp.example.com with no trailing slash.
Title, description, canonical, one h1
Put these in a base template and let each page fill them in:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ title }}</title>
<meta name="description" content="{{ description }}">
<link rel="canonical" href="{{ site_url }}{{ request.url.path }}">
</head>
<body>
<h1>{{ title }}</h1>
Jinja escapes values by default, so a title with a quote or an angle bracket cannot break the page. Keep titles under about 60 characters and descriptions between 70 and 160, give every page its own, and use exactly one h1. The canonical link is built from the path alone, so tracking parameters such as ?utm_source= do not create duplicate pages.
A sitemap and a robots.txt
FastAPI has no sitemap helper, and you do not need one. Two small routes do the job:
PAGES = ["/", "/about", "/pricing"]
@app.get("/sitemap.xml", include_in_schema=False)
def sitemap():
urls = "".join(f"<url><loc>{SITE_URL}{path}</loc></url>" for path in PAGES)
xml = f'<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">{urls}</urlset>'
return Response(xml, media_type="application/xml")
@app.get("/robots.txt", include_in_schema=False)
def robots():
lines = ["User-agent: *", "Allow: /", f"Sitemap: {SITE_URL}/sitemap.xml"]
return PlainTextResponse("\n".join(lines))
If your pages come from a database, build the PAGES list from a query instead. Never leave Disallow: / in a robots file you copied from a staging site, because it tells search engines to skip everything. And remember that robots.txt is a request to polite crawlers, not protection. Anything private needs a login.
Return a real 404
By default FastAPI answers an unknown address with a JSON body and a 404 status. The status is right, but a visitor sees raw JSON. Show a normal page and keep the status:
from starlette.exceptions import HTTPException as StarletteHTTPException
@app.exception_handler(StarletteHTTPException)
async def http_error(request: Request, error: StarletteHTTPException):
if error.status_code == 404:
return templates.TemplateResponse(request, "404.html", {"title": "Page not found", "description": "That page does not exist."}, status_code=404)
return PlainTextResponse(str(error.detail), status_code=error.status_code)
The status_code=404 is the important part. A friendly page that returns 200 is a soft 404, and search engines treat it as a real page with no content.
The trap: your API docs are public
FastAPI publishes interactive documentation at /docs and /redoc, and the raw schema at /openapi.json, on every app by default. The schema lists every route, every parameter and every model, including the admin-style endpoints you never meant to advertise. Search engines can index those pages, and anyone who finds your site gets a free map of your API.
The code above turns them off unless DEBUG=1 is set. That is the simple fix: documentation on your laptop, none in production. If you want docs in production for your own team, put them behind a login instead of leaving them open. Either way, after a deploy, open /docs and /openapi.json on the live address and check they answer 404.
Speed and compression
Add compression for text responses with one line:
from fastapi.middleware.gzip import GZipMiddleware
app.add_middleware(GZipMiddleware, minimum_size=1000)
Serve CSS and images from a static folder with app.mount("/static", StaticFiles(directory="static"), name="static"), keep images small, and avoid loading fonts and scripts from other sites unless you need them. A page that is ready in under a second on a phone is a better result than any meta tag.
Check your work
View the source of your home page and look for the title, description, canonical link, lang attribute and a single h1. Open /sitemap.xml, /robots.txt and a made up address, and confirm that the last one is a 404 in the browser's network tab.
If your app runs on Pharos, the Launch checklist on the app page repeats these checks from outside after each deploy, and the exposure scan flags open API docs. Start with a 14-day trial, then A$27 a month. What the scanner looks at.
More posts
Read your Google Search Console results
3 November 2026 · 5 min read
A pre-launch checklist for a vibe-coded web app
31 October 2026 · 5 min read
Make your Django app SEO friendly in an afternoon
25 October 2026 · 5 min read