Python – How to define and share a JSON schema between the front-end and back-end of an application

backendfront-endjsonpythonschema

We have a mobile app that accepts input into some fields, formalises them as a JSON document and then sends it to the back-end for processing.

We want to agree on a schema for this document that can be validated and referenced indirectly in both the back-end and the front-end.

One of the motivations is that the input can change depending on the language, so in a different language, although the
structure will be the same, the JSON entries will have different values and so we cannot have those hardcoded at either end (but especially at the back-end).

I'm primarily concerned with how such a schema can be represented and how it can be validated at the back-end.
Shall I define an interface for it? If so, is there something standardised already that accomplishes this painlessly?

The target back-end language is Python on Django, we're happy to go with any package as long as it does the job.

Best Answer

We use json schema to validate the objects we send around.

In case you have functional dependencies in a schema, in Python, the library allows you to use functions to validate sub-entries. Example: With jsonschema you can validate that both attributes are numbers. With Python you can additionally validate that one number is greater than the other.

Note on architecture: Schemas can reference each other. We put them into a folder including documentation on how to add, remove and standardize attributes. Each commit creates a new Python package but could also generate a JavaScript, Java, ... package.

What I like about this approach:

  • The schemas have a separate place because their job is to ease communication. So, they do not belong into frontend/backend/any code base.
  • The repository is the place of the communication about what the different applications need. Documentation, issues and pull-requests about the communication process are in one place, not split up over all the different sources that communicate with eachother.