by IgorPartola · 4y ago · 0 comments
1. A custom made serializer. This is the most complicated 150 lines of code in that it can traverse Django ORM objects/query sets and output them to JSON. It supports explicit included and excluded fields and included relationships which it automatically prefetches.
2. Custom middleware that parses any application/json request bodies in request.data.
3. I use Django forms on any data going from client to server for validation. Works great, no reason to make this complicated.
That’s it. Now I can have a REST API written as normal Django views. It is significantly more performant Thant DRF since it doesn’t need to check for a whole lot of different complicated field types when serializing. It’s easy to understand (just call serialize(users, excluded_fields=[“password”], relationships=[“books.chapters”]) to return JSON to the client; you can also annotate your models to include/exclude fields and relationships by default). It has validation errors built in via Django forms. It just works.
Never saw the need for API testing if I am the user of the API.
It does indeed have a standardized format.
Non-cookie auth is actually handled in some of my projects with about a dozen lines of a header parser that then passes it to Django sessions.
Pagination in my latest project is handled as date filters or done client side. Way faster for the user that way and removes a lot of PITA.
Throttling is handled by other bits of infrastructure. If you do that inside a Django view or middleware you are likely doing it wrong.
Frankly it’s not hard to do: you need a parser for author.books.chapters, then a bit of code to look up fields from a model’s Meta class, and then a recursive function to traverse model instances and include the correct field/value pairs based on the type that each field is (scalar, iterable, dict, model instance). My latest version includes a couple of niceties like the annotation on the models of fields to always include/exclude, support for custom properties, and caching of the above. The output is a dict or a list of dicts that can be serialized by Django’s JSON serializer.
Django actually sort of includes a version of this already for serializing model instances, it’s just not very robust.