Ready to Create XML Sitemap Using FastAPI? In this tutorial, you will learn how to create a dynamic, crawlable XML file that powers better indexing and stronger FastAPI SEO. We’ll use simple Python patterns, keep code clean, and ship a production-friendly result.
With Build a Dynamic XML Sitemap with FastAPI and Python, you can scale from a few pages to thousands and keep search engines updated as your site grows.
Why an XML sitemap matters with FastAPI
An XML sitemap informs Google and Bing of every important URL, even if you have a deep nav or your pages load through JavaScript. For a FastAPI app, this will improve the crawl coverage, index new content faster, support large sites by listing fresh and frequently changing pages. An effective, well-structured FastAPI XML Sitemap will help lift your overall visibility.
Create XML Sitemap Using FastAPI without package
Let’s take and example for basic sitemap generation using FastAPI. Here, we will add static pages like home, about, blog.
from fastapi import FastAPI, Response
from fastapi.responses import PlainTextResponse
from datetime import datetime
from typing import List, Dict
app = FastAPI()
BASE_URL = "https://example.com"
def xml_escape(s: str) -> str:
return s.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """).replace("'", "'")
def get_pages() -> List[Dict[str, str]]:
today = datetime.utcnow().date().isoformat()
return [
{"path": "/", "lastmod": today, "changefreq": "daily", "priority": "1.0"},
{"path": "/blog", "lastmod": today, "changefreq": "daily", "priority": "0.8"},
{"path": "/about", "lastmod": today, "changefreq": "monthly", "priority": "0.5"}
]
def build_sitemap_xml(urls: List[Dict[str, str]]) -> str:
parts = ['<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">']
for u in urls:
parts.append("<url>")
parts.append(f"<loc>{xml_escape(BASE_URL + u['path'])}</loc>")
parts.append(f"<lastmod>{xml_escape(u['lastmod'])}</lastmod>")
parts.append(f"<changefreq>{xml_escape(u['changefreq'])}</changefreq>")
parts.append(f"<priority>{xml_escape(u['priority'])}</priority>")
parts.append("</url>")
parts.append("</urlset>")
return "\n".join(parts)
@app.get("/sitemap.xml")
def sitemap():
xml = build_sitemap_xml(get_pages())
headers = {"Content-Disposition": "attachment; filename=sitemap.xml"}
return Response(content=xml, media_type="application/xml", headers=headers)As you can see in above example, we have created an endpoint that return sitemap.xml file as response. We have also created function called build_sitemap_xml() which handles most of the logic for generating XML data. On output of this function will render XML data for home, about and blog page.
Make it dynamic from your data
Sometimes you need to add URLs dynamically like for blog posts and services pages. Update lastmod when content changes so crawlers prioritize fresh URLs. Let’s take another example to make dynamic sitemap content:
from datetime import datetime
from typing import List, Dict
posts = [
{"slug": "hello-fastapi", "updated_at": datetime(2025, 1, 12)},
{"slug": "sitemap-best-practices", "updated_at": datetime(2025, 2, 5)}
]
def get_pages() -> List[Dict[str, str]]:
today = datetime.utcnow().date().isoformat()
urls = [{"path": "/", "lastmod": today, "changefreq": "daily", "priority": "1.0"}]
for p in posts:
urls.append({
"path": f"/blog/{p['slug']}",
"lastmod": p["updated_at"].date().isoformat(),
"changefreq": "weekly",
"priority": "0.8"
})
return urlsThis Dynamic XML Sitemap FastAPI pattern scales well for categories, service pages, or knowledge base routes. Many teams generate hundreds of URLs from a CMS and ship one lightweight endpoint.
Conclusion
You can Create XML Sitemap Using FastAPI with a few clear steps and see immediate SEO gains. Keep the XML valid, update it as content changes, and submit to major engines. With this guide, you built a scalable FastAPI XML Sitemap that will support growth and improve discoverability. You can checkout our guide to Encrypt and Decrypt Files in Python.

