django-ninja API for IntegerChoices
Meta: This article was written using the STAR method.
Situation
We were developing an API using Django Ninja which relies on Djangos IntegerChoices like this:
# models.py
"""
Gütestufeskala gemäss Mini-ICF-APP Work.
"""
= 0,
= 1,
= 2,
= 3,
= 4,
Task
Make sure the generated Typescript interfaces are properly named, matching the Django model definition. This ensures type safety on the frontend and maintains consistency between the code bases of backend and the frontend.
Action
We came up with a mixin-class, that makes use of x-enum-varnames and x-enum-descriptions to make sure, the API will be generated accordingly.
# utils/mixins.py
"""
Mixin to inject x-enum-varnames into the OpenAPI schema for Django Choices.
"""
# Generate the default schema (type: integer, enum: [0, 1, ...])
=
# Inject the custom extensions for openapi-generator
=
=
return
Result
Finally, just inherit from the mixin-class like this:
... # see [Ellipsis](#ellipsis)
Did you notice the three dots (
...) above? In case you don't already know them, check out the section below to learn more about them.
Using OpenAPI Generator with the typescript-fetch generator lead to the following code:
/**
* Gütestufeskala gemäss Mini-ICF-APP Work.
* @export
*/
;
;
Ellipsis
The three dots ... are called Ellipsis. Because it's a builtin constant, the code above is valid Python code, I shit you not. (And this was my favorite, yet a bit unprofessional, English phrase.)
You could also replace the Ellipsis with pass and it would do exactly the same thing (which is actually, nothing except leading to syntactically correct code. Check out my question on Stackoverflow I asked once, when I was new to Python.