We have a resource called messages
. We want to have two ways of listing its collection. One would return only messages that are mandatory and have been viewed; the other, all messages. Each one has fields that are not necessary for the other, thus we would like to not return them. E.g.
One response should look like this:
public class MessageListingResponse {
private Long messageId;
private String title;
private String imageUrl;
private LocalDateTime createdAt;
private Boolean isViewed;
}
The other one is like this:
public class MandatoryMessageListingResponse {
private Long messageId;
private String title;
private String imageUrl;
private LocalDateTime createdAt;
private String description;
}
I could not find a common rule for this scenario. So, which option follows REST?
/messages/mandatories
/messages?view=mandatories
/messages?mandatoryListing=true
/mandatory-messages
CodePudding user response:
First of all, if it's messages, then /messages
should be there because the resource is message.
After that, messages/mandatories
means that there a listing of mandatories, that it's a subset of messages. Do you intend to add or update a mandatory message with put, post or patch, messages/mandatories
is the right way.
But if it's only a filter for messages that are mandatory, the best way to do it is with a GET
like this: /messages?status=mandatories
Where status
is the field that indicate if the message is mandatory
CodePudding user response:
This is borderline opinion-based but this is how I would do it.
The most RESTful way would be using a query parameter, so something like /messages?view=mandatories
. The problem with this (might not be a problem for your use case, you need to think about it) is that the response model will need to be the same as for /messages
, which means that you would need to have a model as follows (merging MessageListingResponse
and MandatoryMessageListingResponse
):
public class MessageListingResponse {
private Long messageId;
private String title;
private String imageUrl;
private LocalDateTime createdAt;
private Boolean isViewed;
private String description;
}
If this is not wanted (I would also avoid it), then I would go with a not-so-RESTful approach, such as /messages/mandatories
. It is not so RESTful because messages
are your resource and the following path information should be an ID so that you can get only one message. Another possibility would be something like /messages/view:mandatories
which I understand might seem weird to most people. Whatever structure you use, with this approach you have the benefit of having a specific model for this and thus you can have very specific model for each endpoint, avoiding properties that would be null
in some cases and not null
in another.