How to Configure FastAPI to Return XML Responses in Documentation

Open-Source AI Gateway & Developer Portal
How to Configure FastAPI to Return XML Responses in Documentation
FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.6+ based on standard Python type hints. One of the many excellent features of FastAPI is its ability to handle multiple data formats for request and response payloads, including JSON and XML. In this article, we will walk you through the steps needed to configure FastAPI to return XML responses in your documentation.
Table of Contents
- Introduction to FastAPI
- Understanding XML and Its Importance
- Setting Up Your FastAPI Project
- Working with XML Responses
- Updating the API Documentation to Show XML Responses
- Testing XML Responses
- Integrating with AI Gateway and LLM Gateway
- Conclusion
Introduction to FastAPI
FastAPI simplifies the process of building APIs while ensuring performance and ease of use. It is designed to minimize errors and improve productivity. FastAPI provides automatic interactive API documentation using Swagger UI or ReDoc, which makes it possible to test endpoints quickly.
As application architectures evolve to include various components like an AI Gateway or azure, configuring your FastAPI application to support XML can be particularly useful when dealing with legacy systems or specific client requirements.
Understanding XML and Its Importance
XML (Extensible Markup Language) is a versatile data format commonly used for data interchange between systems, particularly in enterprise applications. Despite JSON's increasing popularity for APIs, XML can still be essential for certain scenarios where schema validation or complex data representation is necessary.
When integrating with systems using the LLM (Large Language Model) Gateway or Azure, having the ability to return XML responses can improve compatibility and facilitate smoother data communication.
Setting Up Your FastAPI Project
To get started, you'll need to install FastAPI and an ASGI server like uvicorn
. You can do this with the following pip commands:
pip install fastapi uvicorn
Once you have installed the required packages, create a new directory for your project and set up a main FastAPI application file:
mkdir fastapi_xml_example
cd fastapi_xml_example
touch main.py
Your main.py
can start with the following basic structure:
from fastapi import FastAPI
from fastapi.responses import XMLResponse
app = FastAPI()
@app.get("/", response_class=XMLResponse)
async def read_root():
return "<message>Hello, World!</message>"
In the example above, we define a simple FastAPI app that returns an XML response when the root endpoint is accessed.
Working with XML Responses
FastAPI has built-in support for different response classes. To return XML responses, you can utilize the XMLResponse
class provided by FastAPI. This allows you to structure your API responses in XML format.
Creating Custom XML Responses
If you want to control the structure of your XML response, you can create a function that generates XML data based on the input data. Here's an update to our existing example to return a custom XML response based on some data:
from fastapi import FastAPI
from fastapi.responses import XMLResponse
from typing import Dict
import xml.etree.ElementTree as ET
app = FastAPI()
def dict_to_xml(tag: str, d: Dict) -> str:
elem = ET.Element(tag)
for key, val in d.items():
child = ET.SubElement(elem, key)
child.text = str(val)
return ET.tostring(elem, encoding='unicode')
@app.get("/user/", response_class=XMLResponse)
async def read_user(name: str, age: int):
user_data = {"name": name, "age": age}
return dict_to_xml("user", user_data)
In this newly defined endpoint, the /user/
route expects query parameters for name
and age
, converting them into an XML format.
Updating the API Documentation to Show XML Responses
FastAPI automatically generates documentation for your API using OpenAPI specifications. To include XML responses in your documentation, you need to specify the response media type in the endpoint definitions. Here’s how to enhance the documentation with clear indications of XML responses:
from fastapi import FastAPI, Query
from fastapi.responses import XMLResponse
from fastapi import Response
from typing import Dict
import xml.etree.ElementTree as ET
app = FastAPI()
def dict_to_xml(tag: str, d: Dict) -> str:
elem = ET.Element(tag)
for key, val in d.items():
child = ET.SubElement(elem, key)
child.text = str(val)
return ET.tostring(elem, encoding='unicode')
@app.get("/user/", response_class=XMLResponse)
async def read_user(
name: str = Query(..., description="The name of the user"),
age: int = Query(..., description="The age of the user")
) -> Response:
user_data = {"name": name, "age": age}
return XMLResponse(content=dict_to_xml("user", user_data), media_type="application/xml")
By specifying media_type="application/xml"
in your response, FastAPI will update the API documentation to reflect that the endpoint is capable of returning XML responses.
Testing XML Responses
After setting up the endpoints and configuring to return XML data, it's important to test to ensure the XML responses are correct. You can use tools like Postman or cURL to test your FastAPI application.
Here's an example cURL command to test the /user/
endpoint:
curl -X 'GET' \
'http://127.0.0.1:8000/user/?name=John&age=30' \
-H 'accept: application/xml'
This command will request the user data in XML format, and the output should present the XML that corresponds to the input parameters.
Integrating with AI Gateway and LLM Gateway
When working within the broader context of an API framework that includes an AI Gateway or a LLM Gateway, the ability to correctly format your responses—including XML—becomes crucial. These gateways may require specific parameters or even maps between data formats, necessitating careful management of parameter rewrite or mapping.
To demonstrate how you can integrate the AI Gateway, consider the following example:
@app.get("/custom-ai/", response_class=XMLResponse)
async def custom_ai_service(query: str):
ai_response = call_ai_gateway(query)
xml_content = dict_to_xml("ai_response", {"response": ai_response})
return XMLResponse(content=xml_content, media_type="application/xml")
Here, call_ai_gateway
represents a fictitious function that interfaces with your AI service. Ensure this method handles the interaction properly, potentially involving parameter transformations or mappings as needed by the AI service API.
The integration of XML responses can ensure your FastAPI application seamlessly cooperates with both traditional systems and modern capabilities like AI and LLM frameworks.
APIPark is a high-performance AI gateway that allows you to securely access the most comprehensive LLM APIs globally on the APIPark platform, including OpenAI, Anthropic, Mistral, Llama2, Google Gemini, and more.Try APIPark now! 👇👇👇
Conclusion
Configuring FastAPI to return XML responses in documentation is a straightforward process that enhances the versatility of your API. By utilizing FastAPI's built-in features for response classes and enhancing the documentation with appropriate media types, you can create a rich API that meets diverse integration needs.
Having mastered these techniques, you can expand your API to cater to legacy systems or specific client requests, ensuring that your API remains adaptable and robust in a fast-evolving digital landscape.
Incorporating integration with AI Gateway and LLM Gateway only serves to reinforce your API's ability to interact seamlessly with various data formats and systems. This adaptability can significantly enhance your application's reach and functionality, making it a vital asset in your development toolkit.
Additional Resources
Resource | Link |
---|---|
FastAPI Documentation | https://fastapi.tiangolo.com/ |
Python XML Documentation | https://docs.python.org/3/library/xml.etree.elementtree.html |
AI Gateway Documentation | APIPark AI Integration |
Example Code Repository
For a complete working example of a FastAPI application returning XML responses, refer to the GitHub repository found here: GitHub - FastAPI XML Example.
By compiling these resources and honing your skills in FastAPI, you will be well-prepared to tackle XML data handling in your API projects.
🚀You can securely and efficiently call the Gemni API on APIPark in just two steps:
Step 1: Deploy the APIPark AI gateway in 5 minutes.
APIPark is developed based on Golang, offering strong product performance and low development and maintenance costs. You can deploy APIPark with a single command line.
curl -sSO https://download.apipark.com/install/quick-start.sh; bash quick-start.sh

In my experience, you can see the successful deployment interface within 5 to 10 minutes. Then, you can log in to APIPark using your account.

Step 2: Call the Gemni API.
