REST API & Ember (data) - Many-to-Many relation with attributes - json

I have two resources in my system users and organizations.
Each has a name and a relation with the other (many to many).
In my REST API I have:
/organizations - returns all organizations in the system (public)
/users - return all users in the system (public)
After this I needed to add properties to the relation (e.g. role in the organization). For this I created the concept of worker, a person in an organization.
What I have tried:
A new model, a "full resource"; it doesn't comply with a good rest design.
A nested resource inside organizations; better in json, but in Ember using EmbeddedRecordsMixin I lose the ability to manipulate the model - e.g. usage of adapter or serializer to change the resource.
How to design the REST api?
How to define Ember models and how to manipulate them?

Suggest making a 3rd resource that contains the role properties and relations to user and organization
You can use links, an example response for an organization:
{
id: 1,
links: {
users: "/organizations/1/users"
}
}

Related

Spring POST json entities

I'll try to make it simple, because I can't find a tutorial with this problem, I think it belongs to best practices designing REST APIs.
I have two entities
- Role (id, name)
- User (id, name, Role, etc.)
When making a POST Request to some controller what is the best approach to do it, in a json way.
{
"id": 1,
"name": "Luis",
"rol":{
"id": 1,
"name":Administrator,
"users" : [
//I think this is for the bidirectional relationship so
can I avoid this property as well??
]
},
"another" : bla bla bla
}
For this approach do I have to put all the properties of the entity that is related?? Meaning that i have to create a json with this structure, or can ommit properties, here a question get out of my head How Spring knows this is an entity so it can make a Role object and hence a relationship to User?
Or do I have to post like this:
{
"id": 1,
"name": "Luis",
"role_id" : 1,
"another" : bla bla bla
}
So when the controller knwos about this, first it will find a Role by using, lets say Role.findById() of course I use a service layer... and then attach it to the user.
What is the best approach for this?
Thank you.
In my opinion this question is particularly interesting because it recalls a very common developers' pitfall i.e. understanding the borders between design and implementation.
First, let's point out a very important concept: your API is decoupled from your business object. Your API could be designed by an architect who knows nothing about Java or Spring and cares even less of your User or Role classes.
In REST, servers and clients exchange resources representations and this means that the server is free to determine the most meaningful representation for that resource. In other words, whether you are using JSON, XML or whatever, you are not forced to include in your API some information just because it's present in some form in your backing object.
Resources exposed in your API live in another dimension. They are agnostic with respect of the Spring controller.
So, the answer to your question is: send the information that is meaningful for that operation. The server knows the rest.
I have to admit that your second question "How Spring knows this is an entity so it can make a Role object and hence a relationship to User?" sounds a little weird to me. Spring Controllers bind HTTP requests to class methods. Those methods are like the following
#RequestMapping(value = "/users", method = RequestMethod.POST)
public String createUser(#RequestBody UserModel user) {
//...
}
so when you fire the POST to the right URL the request will be dispatched from the AS to your DispatcherServlet and finally to your Controller and createUser method. The payload, i.e. the JSON representation, is now unmarshalled into a UserModel class defined accordingly to your user representation (for example including id, name and roleId). At this point you are in control of everything since you have your user available for performing all the operations you need. Probably you will create a Role object and a User object, fulfill the dependencies between the two classes, calling your DAO or whathever, wait for the persistence layer to complete its operation and return your 201 created HTTP status to the client (with the location header filled, if you want to be RESTful).

Jackson #JsonIgnore fields based on spring security roles

In all of my Spring REST Web application, I have a lot of domain objects and DTOs.
I need to filter some domain object or DTOs fields based on the spring security roles of the user who makes the request. I want Jackson to filter the output JSON to allow/disallow specific class fields to be serialized , based on the Spring GrantedAuthorities roles of the user who tries to access the resource.
I can't create new DTO for every different view combination because it would be a mess.
I have found this solution :
Spring 3.2: Filtering Jackson JSON output based on Spring Security role
But it doesn't work, the filter is only applied once, when the first user logins. Then all the other users obtain the same filtering , no matter what their role is.
I cannot explain my problem better than Ray Holland on this blog post :
http://jackson-users.ning.com/forum/topics/jackson-custom-serialization
This is the exact same problem I'm trying to solve for a few days.
I couldn't find a clean way to do that so far.
It's better to use #JsonView in spring project (example)
If #JsonView isn't enough, there isn't easy solution. It is unavoidable to define specific class(interface) to implement #JsonIgnoreProperties and #JsonFilter (
take a look Jackson: Skip Objects Conditionally )

How to handle 'intermediate' JSON rest service parameters in Spring?

I'm new to Spring development and am currently looking for best practices for creating objects based on JSON data passed to a rest service, which are then to be stored using JPA.
As an example, let's assume a simplified file upload service where clients can post the following JSON object to:
{"filename":"myfile.pdf", "data":someByteArray, "extension":"pdf"}
On the server, I don't want to store the file's raw data in the database, but upload it to some cloud storage and just store a link to it. So once the "data" parameter content is stored and the link is received, it is obsolete.
The options I've come up with is:
a) define one 'union' class to deserialize the request body that comprises all fields ("filename", "link", "extension" AND "data"), marking 'intermediate' data as #Transient, so it won't be stored in the database,
b) define two classes: one solely for deserializing the request body ("filename", "data", "extension") which is then used to construct the desired entity class ("filename", "link", "extension") that is to be stored,
c) define a custom JsonDeserializer that parses the request body and constructs the entity class ("filename", "link", "extension").
While all of the approaches will probably work, in a more complex scenario, option a) will clutter the entity's class with members that are only required for deserializing once, while option b) and c) may result in a lot of additional classes.
Is there any best practice for this? Btw, thanks for reading this far :)

JSON web token - applying different user roles to different routes

What is the standard practice for using JWTs in authentication mechanisms which require roles?
Should roles be contained somewhere within the predefined public claim names?
['iss', 'sub', 'aud', 'exp', 'nbf', 'iat', 'jti]
... Or should an application specific private claim name be used?
Or should the application refrain from putting roles in JWTs and keep all role based logic within the application only?
More detail:
When using JSON web tokens as a user authentication mechanism, and you apply the authentication on a set of routes, when a token is valid, authentication is valid for all routes in the set. If the token is not valid, it is invalid for all routes in the set.
This is great if all users have the same level of access. However, if users have different roles, say "user" and "admin", and only the "admin"s have access to certain routes, this falls down.

Data types between the Service (Application/Controller) and UI layers

Consider the common layered architecture of:
UIService/Application/ControllerDomainPersistancy
What should be the types between the Service and the UI layers?
Should the return types of the methods in the Service layer be primitives? Can they be objects from the Domain layer?
The motivation:
We are building a forum system. Somewhere in the Service layer there should be a method like "getForums". I am wondering what should be its return type -
Should it be some collection of forumID's (primitives) - we would need to issue many more calls to the Service layer in order to present the topic and description of the forum (using its ID).
Should it be some collection of Forum objects (from the domain layer) - we could end up with a UI that has direct access to the Domain layer (sounds really bad to me)
Should it be some collection of specially made objects (representing only the topic, description and ID of a forum)? (sounds like too much code for nothing)
You could use the Data Transfer Object pattern:
http://www.martinfowler.com/eaaCatalog/dataTransferObject.html
This would be implemented between the UI and the Service layer and can be tailored to the view of the data that the UI requires.