Chris Pickford
Chris Pickford

Reputation: 8991

Conditonally return different REST API response object for same endpoint

The following scenario does not follow RESTful standards and would be keen to know how best to structure my API to achieve the same goal.

For a given GET request against a resource, e.g. GET /api/person/1, if the principle contains a claim I would like to return additional properties.

E.g.

GET /api/person/1 (Without IsAdmin claim)
{
  name: "Buck Rogers",
  dateOfBirth: 2000-01-01T00:00:00.000
}
GET /api/person/1 (With IsAdmin claim)
{
  name: "Buck Rogers",
  dateOfBirth: 2000-01-01T00:00:00.000,
  adminNote: "Something private"
}

So I'd conditionally be returning two different DTOs for the same resource request, which isn't allowed.

How can I achieve this in a RESTful way?

Update:

It was suggested I could define the adminNote property and NULL it based on the condition. How would I deal with the case where there might be multiple conditionals that determine which properties are included? E.g.

GET /api/person/1 (With IsModerator claim)
{
  name: "Buck Rogers",
  dateOfBirth: 2000-01-01T00:00:00.000,
  moderatorNote: "Something else private"
}

I would be keen to avoid adding extra properties that will only ever not be null in one particular case.

Upvotes: 8

Views: 3283

Answers (2)

JJ Geewax
JJ Geewax

Reputation: 10579

I think you've got the right idea here based on your update.

It's perfectly fine to define a schema that has a set of fields that are only populated given certain circumstances. One example is the "with admin" claim, but another is the idea of a user-provided field mask or views (see AIP-161 for an example of this).

If you're concerned about a lot of these piling up, you could always group the field to be adminInfo that contains all the admin fields, but that's probably not necessary...

Upvotes: 0

Vinayak Nair
Vinayak Nair

Reputation: 203

you can create a Person resource with all the three fields and when the IsAdmin is false or without claim , you could set adminNotes to null.And to not return that property you can use @JsonInclude(Include.NON_NULL) (its for java, something like this might be available in asp.net) as well.So you don't need to create two separate entities or DTO's.

Upvotes: 0

Related Questions