Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONAPI best way for responding a non-resource data like a access token with jsonapi-resources

I'm implementing this API and the first thing I did was the login with access token. I'm using the jsonapi-resources gem https://github.com/cerebris/jsonapi-resources

I have two problems now. I want to return a user AND the generated access token in case of success and a failure message otherwise.

Now I got two problems:

1- The first one is, how can I return this kind of data (the User record PLUS the access token). Reading the JSONAPI specification I believe a compound document would be the way to go, but how can I do it with this gem

2- How can I respond, with this gem, to a non-CRUD route like login? Do I have to make something in the controller? And how can I handle a resource object in this case?

like image 927
Victor Ferreira Avatar asked Nov 27 '25 08:11

Victor Ferreira


1 Answers

There is no such thing as non-resource data. You can model pretty much everything in terms of resources.

Those resources do not have to map directly to tables or even exist as identifiable entities in your persistence layer. From an api consumer's perspective it is mostly irrelevant whether or not the resource representation is an actual database row or document or a entirely abstract entity conjured on demand.

Implementing Abstract resources using JR is straightforward and is supported out of the box:

Abstract Resources

Resources that are not backed by a model (purely used as base classes for other resources) should be declared as abstract.

Because abstract resources do not expect to be backed by a model, they won't attempt to discover the model class or any of its relationships.

Now, coming back to your use cases:

  1. This can be modelled as an AuthToken resource (with a single attribute) that is related to (many-to-one association) a User resource. And in your case it may happen that your user resource is included along with the AuthToken resource in the same API response.

  2. Again, if you model your entire domain around resources, any and all actions can be modelled as CRUD actions. Login is just creation of a UserSession resource.

JSON:API specification allows inclusion of related resources:

Inclusion of Related Resources

An endpoint MAY return resources related to the primary data by default.

An endpoint MAY also support an include request parameter to allow the client to customize which related resources should be returned.

And this feature is fully supported by JR as well.

like image 135
lorefnon Avatar answered Nov 29 '25 00:11

lorefnon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!