Post arbitrary JSON data (dynamic form) to FastAPI using AJAX
FastAPI is a modern, fast, web framework for building APIs with Python 3.6+ based on standard Python-type hints.
In a usual way, FastAPI uses Pydantic models to declare a request body. We declare a data model as a class that inherits from BaseModel. Declare the query parameter’s type as the model. Then we can easily access all the attributes of the model object directly:
It’s quite convenient, only this way forces the JSON to have a specific structure. In some use cases, we know the request body contains a JSON but its structure may be variable.
One simple solution here is to use type hint Dict to tell FastAPI that we are expecting any valid JSON:
At client-side
Say we have a dynamic form to be posted, its structure variated from time to time:
<form id=”dform”>…</form>
Firstly, we create a function to convert the form data to be indexed: