vitalik / django-ninja

💨 Fast, Async-ready, Openapi, type hints based framework for building APIs
https://django-ninja.dev
MIT License
7.28k stars 432 forks source link

JSON:API #41

Closed HrachMD closed 1 year ago

HrachMD commented 3 years ago

This one also not issue, but a proposal. It will be very useful for response schema validation in jsonapi standards.

vitalik commented 3 years ago

hi @HrachMD

Not sure I understand... do you have any references/links to this schema validation ?

HrachMD commented 3 years ago

Thank you for your response. I mean if we have such response schema:

class SigninOutput(Schema):

email: EmailStr name: str

Then do not return just {'email': '', 'name': ''} But instead do this kind transformation: {'data': {'type': 'sometype', attributes: {'email': '', 'name': ''}}}

hbutau commented 3 years ago

Maybe we need something like this :point_right: https://github.com/django-json-api/django-rest-framework-json-api

skorokithakis commented 3 years ago

We're having this issue as well, and currently the responses are a bit awkward because JSONAPI uses an "envelope" that the actual data gets wrapped in, so Ninja only ever sees the "envelope" and the resulting names are "wrong" (it basically thinks that every API returns a class of type Envelope).

Maybe it would be nice to have something that takes the proper classes and wraps them in the envelope.

vitalik commented 3 years ago

maybe what you need is custom renderer ? https://django-ninja.rest-framework.com/tutorial/response-renderers/

Note: Django Ninja is designed on top of OpenAPI specifcation/standard

while JSON:API is an alternative standard

technically with custom renderer you can achieve responses like you describe, but autogenerated openapi docs and schema will be useless

skorokithakis commented 3 years ago

Ah, that makes sense, thank you.

skorokithakis commented 3 years ago

Does OpenAPI mandate the response schema that APIs should return? What is the recommended way of returning e.g. relationships in Ninja? Currently, if we need to return, for example, a User object and a Subscription object, we'll need to have a UserSubscriptionResponse class that contains them, and that can quickly become unwieldy with larger APIs.

stephenrauch commented 3 years ago

@skorokithakis You can use generics to help cleanup the code with embedded pydantic models. Here is an example for JSONAPI:

https://github.com/DeanWay/pydantic-jsonapi

skorokithakis commented 3 years ago

Hm, that's an interesting solution, thanks @stephenrauch. I don't think our juniors are going to love it, as generics are a rather advanced type concept, but it seems to solve the problem well, thanks.