Post arbitrary JSON data (dynamic form) to FastAPI using AJAX

Shawn Wong
3 min readApr 24, 2021

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:

--

--

Shawn Wong

Ruby on Rails developer, AWS cloud practitioner, GeoBlacklight, Omeka practitioner.