Generating FastAPI server using OpenAPI Generator
Published on April 18, 2025 by Dai Tran
project api fastapi openapi generator factory blog
3 min READ
This blog post discusses the use of the OpenAPI Generator tool developed by the OpenAPI Generator project to generate Python FastAPI server code from prepared OpenAPI specs. It allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3).
NOTE: Currently it only supports up to Python 3.12
.
pyenv
is needed to managed multiple Python versions.
brew update
brew install pyenv
Once installed, update your .zshrc with the following lines:
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(pyenv init -)"' >> ~/.zshrc
source ~/.zshrc
Now you can install and run another version of python in your shell. The following will install Python 3.12 and set your current terminal window to use it.
pyenv install 3.12.10
pyenv shell 3.12.10
Follow the instructions for Homebrew.
brew install openapi-generator
Follow the following instructions to generate the FastAPI HelloWorld API server code from the HelloWorld OpenAPI specs prepared in advance as the input.
cd api/generator/helloworld/server
openapi-generator generate -i openapi.yaml -g python-fastapi -o .
OpenAPI Generator will populate the server
directory with the FastAPI server code.
The generated code is just a skeleton. Business logic needs to be added. As an example, in the api/generator/helloworld/server/src/openapi_server/apis/default_api.py
, replace the following code:
async def hello_get(
) -> str:
"""Returns a simple \"Hello World\" message."""
if not BaseDefaultApi.subclasses:
raise HTTPException(status_code=500, detail="Not implemented")
return await BaseDefaultApi.subclasses[0]().hello_get()
with the following:
async def hello_get(
) -> str:
"""Returns a simple \"Hello World\" message."""
return "Hello World!"
OpenAPI Generator requires Rust and Cargo, the Rust package manager, to compile extensions. To install Cargo and Rust using the following command:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
There is a bug in the function test_person_post
of the test module tests/test_default_api.py
. Here is the buggy code:
person_post_request = openapi_server.PersonPostRequest()
Replace it with the following code:
person_post_request = PersonPostRequest()
Update auto-generated Dockerfile
to use internal Docker registry and image.
To run the server, please execute the following from the root directory:
cd api/generator/helloworld/server
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
PYTHONPATH=src uvicorn openapi_server.main:app --host localhost --port 8080
To run the server on a Docker container, please execute the following from the root directory:
docker-compose up --build