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:
When we call the /openapi.json
endpoint:
- 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:
{
"info": {
"title": "FastAPI",
"version": "0.1.0"
},
"openapi": "3.0.2",
"paths": {
"/": {
"get": {
"description": "This is home.",
"operationId": "home__get",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {}
}
},
"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.
As most of my examples, we'll use potatoes:
When we call /openapi.json
, as we did above, we'll get the following OpenAPI JSON as response:
{
"components": {
"schemas": {
"PotatoOutput": {
"description": "Super potato.\n",
"properties": {},
"title": "PotatoOutput",
"type": "object"
}
}
},
"info": {
"title": "FastAPI",
"version": "0.1.0"
},
"openapi": "3.0.2",
"paths": {
"/": {
"get": {
"operationId": "get_potato__get",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PotatoOutput"
}
}
},
"description": "Successful Response"
}
},
"summary": "Get Potato"
}
}
}
}
Tip
We can also use jq
to get the part of the JSON that we are interested.
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.