blog / · fastapi
FastAPI Escape Character
Today, we’ll talk about a small feature of FastAPI that might be useful for you: the escape character. 🤓
What is the escape character?
The escape character \f is a character that can be used to tell to FastAPI to truncate what should go to the endpoint description on
the OpenAPI.
Let’s see it in practice. Consider we have the following endpoint:
Code
main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def home():
"""This is home.
\f
This is not on the OpenAPI.
"""
Run
Install the dependencies:
python -m pip install uvicorn fastapi
Then run uvicorn:
uvicorn main:app
When we call the /openapi.json endpoint:
http GET :8000/openapi.json
- The HTTP client used is called HTTPie, but you can use
curl, or just go to the browser, and accesshttp://localhost:8000/openapi.json.
You’ll see the following OpenAPI JSON on the response:
,
"openapi": "3.0.2",
"paths":
}
},
"description": "Successful Response"
}
},
"summary": "Home"
}
}
}
}
Observe the “description” field does not contain the “This is not on OpenAPI” part of the docstring.
The reason is the escape character we used. Everything after the \f will not appear on that field.
This feature may be useful if you are using a docstring linter tool, like darglint.
What’s new?
If you are a FastAPI veteran (😎), you are probably familiar with the above. What you probably don’t know, is that now (since FastAPI 0.82.0) it’s possible to use it on the Pydantic models you use on your FastAPI application.
Let’s see another example.
Code
As most of my examples, we’ll use potatoes:
main.py
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class PotatoOutput(BaseModel):
"""Super potato.
\f
This is not on the OpenAPI.
"""
@app.get("/", response_model=PotatoOutput)
def get_potato():
...
Run
Install the dependencies:
python -m pip install uvicorn fastapi
Then run uvicorn:
uvicorn main:app
When we call /openapi.json, as we did above, we’ll get the following OpenAPI JSON as response:
,
"title": "PotatoOutput",
"type": "object"
}
}
},
"info": ,
"openapi": "3.0.2",
"paths":
}
},
"description": "Successful Response"
}
},
"summary": "Get Potato"
}
}
}
}
As we can see, the description of PotatoOutput doesn’t contain the “This is not on the OpenAPI.” part as well.
Yey! Now you can use those docstring linter tools as you want with FastAPI! 🙌
Thanks for reading this blog post! 🥳
If you have any suggestions on what I can write about, please feel free to suggest below. 🙏
Was this useful? Consider sponsoring my open source work. ❤️