Returning objects with multiple types in a RESTful way - rest

I'm currently designing an API to handle requests from mobile clients. To achieve some degree of decoupling between backend and client I would like to define the webservices in a RESTful way. The challenge that I am facing is returning multiple objects with different types for a single call.
Lets say we have the following Model:
Harbour ... Top level entry
Boat shed ... Assigned to a specific harbour (0..n)
Boat ... Assigned to a specific boat shed (0..n), or directly to a harbour (0..n)
As far as i understand REST, if I now want to display all the boats and sheds in the harbour I would send two requests:
/harbours/{harbour_id}/boats Returning a list of all boats. Boats in a shed would contain an id linking to the shed they are in
/harbours/{harbour_id}/sheds Returning a list of all sheds
As I want to use the web service in a mobile scenario, it would be ideal to combine these two calls into one. This could then either return the list of boats with the shed object nested within, or both object types side by side:
/harbours/22/boats
[
{
"id":1,
"boatName":"Mary",
"boatShed":{
"id":1,
"shedName":"Dock 1",
"capacity":55
}
},
{
"id":2,
"boatName":"Jane",
"boatShed":{
"id":1,
"shedName":"Dock 1",
"capacity":55
}
}
]
or
/harbours/22/boats
{
"boats":[
{
"id":1,
"boatName":"Mary",
"boatShedId":1
},
{
"id":2,
"boatName":"Jane",
"boatShedId":1
}
],
"sheds":[
{
"id":1,
"shedName":"Dock 1",
"capacity":55
}
]
}
My question now is, which of these ways is closer to the idea behind REST, or is it not RESTful at all?

As #Tarken mentioned /boats request should not return sheds in the top level (since the url assumes you're asking for collection of resource Boat)
If you have relations defined as follows
Harbour:
boats: Boat[]
sheds: Shed[]
Shed:
boats: Boat[]
Boat:
harbour: Harbour
shed: Shed
/harbours/ID then returns a Harbour representation with boats and sheds relation set.
{
boats:
[
{ Boat },
{ Boat },
..
],
sheds:
[
{ Shed },
{ Shed },
..
],
...
}
Nothing is against restful principles here - the url uniquely identifies a resource and resource representation can be anything, with links to other resources as well.

Create a Harbour model which contains both Boat Shed and Boat information. If i am implementing the service in Java, then i would have done something like this :
class Boat{
...
}
class BoatShed{
...
}
class Harbour{
List<Boat> boats;
List<BoatShed> boatSheds;
...
}
You can create an API like /api/harbours/{harbourId}.
As per your question you want to display all the boats and sheds in the harbour, say id=1234, you can make a request like this :
GET /api/harbours/1234
This will return list of Boats and list of Boat Sheds like this:
{
"boats":[
{
"id":1,
"boatName":"Mary",
"boatShedId":1
},
{
"id":2,
"boatName":"Mary2",
"boatShedId":2
}
],
"sheds":[
{
"id":1,
"shedName":"Dock 1",
"capacity":55
},
{
"id":2,
"shedName":"Dock 2",
"capacity":50
}
]
}
EDIT
As you want to get boats and Sheds side by side by sending one request, the api/hourbours/{id} looks good according to REST API design principles.
Getting all sheds while requesting for boats is not in accordance with ideal REST API design, but if you want to achieve the same you can d the following.
If you want that way, then first one /api//harbours/{id}/boats looks good to me.

Related

Custom filters that accept objects - lighthouse-php

I am using lighthouse-php as Api Gateway in a micro services architecture.
So for all my types I make a request internally through Guzzle.
But I am needing to implement filters that are suitable for any type and that give flexibility when making queries.
I need to implement a query like this:
query news (
order_by: {publication_date: desc}
where: {
_or: {categories_id: { _eq: 1 }, title: { _ilike: "news" } }
}
limit: 10
offset: 20
) {
id
category_name: name
photo
publication_date
text
title
}
But I have no idea how to implement this "where" filter that receives a composite object as in this example.
Remember that this query will not use any model within lumen, since it will be a custom query that will make a request to the microservice of news.
What I need is the way that my query receives whatever comes in where, limit and order, to send it on request. But I have no idea how to build something like this in the scheme.
Anyone have any idea how to do it?
Thanks friends.
Yes, you can.
Just now I'm making an component that will receive criterias to filter in graphql query so I need to fill filter's where params with those criterias.
Imagine the following schema:
type News{
id: ID!
title: String!
views: Int!
}
type Query{
getNews(where: _ #whereConditions(columns:["title", "views"])) : [News!] #all
}
We can make a query and fill where variables later
query GetNews($whereNews: [GetNewsWhereWhereConditions!]){
getNews(where: {OR: $whereNews}){
title
views
}
}
When querying we can fill the variables sending an object like
{
"where":[
{"column": "TITLE", "operator": "LIKE", "value": "Amazing title"},
{"column": "VIEWS", "operator": "GTE", "value": 10,
]
}

REST, cross-references and performances, which compromise?

After reading this excellent thread REST Complex/Composite/Nested Resources about nested structures in REST responses, I still have a question. What's the best choice in terms of performance about the response ?
Let's take an example.
I have an Category object, which contains some Questions. Those Questions contains some Answers. All of these structures have meta-informations.
Now, when querying an url like GET http://<base_url>/categories/, should I include a description of the Categories only, include Question description ? Which one, full description or simplified one ?
In other terms, what's the best solution between those :
{
"results":[
{
'id':1,
'name':'category1',
'description':'foobar',
'questions':[
{
'id':1234,
'question':'My question',
'author' : 4235345,
'answers':[
{
'id':56786,
'user':456,
'votes':6,
'answer':'It's an answer !'
},
{
'id':3486,
'user':4564,
'votes':2,
'answer':'It's another answer !'
},
]
},
...
]
}
...
]
}
OR SOLUTION 2 :
{
"results":[
{
'id':1,
'name':'category1',
'description':'foobar',
'questions':[
{
'id':1234,
'url':'http://foobar/questions/1234'
'answers':[
{
'id':56786,
'url':'http://foobar/answers/56786'
},
{
'id':3486,
'url':'http://foobar/answers/3486'
},
]
},
...
]
}
...
]
}
OR SOLUTION 3 :
{
"results":[
{
'id':1,
'name':'category1',
'description':'foobar',
'questions':'http://foobar/categories/1/questions'
}
...
]
}
Or maybe another solution ?
Thanks !
That depends on what the application will do with the data. If it is only going to display a list of categories, then it is very inefficient to transfer all the data it ever needs at once, especially if the categories are many, which will decrease response time of user (absolute no no).
These scenarios depend heavily on application and usage of data.
One optimization that we can do is, we can create two requests,
GET http://<base_url>/categories
Which will return minimal data immediately and another request,
GET http://<base_url>/categories?all=true
Which will return all data.
Then the client app can make some clever optimizations like, when user requests for categories, request one is sent and it will immediately render the data. Then after getting the list of categories the user will be idle for some time looking and we can use this opportunity to request all data using request two.
However, as I said this will largely depend on the application.

RESTful master/detail

Having 3 dropdown pickers in a web application. The web application uses a Restful service to populate pickers data.
The two first pickers get their values from something like /years and /colors. The third one should get its values depending on the settings of the two.
So it could be something like /models?year=1&color=red.
The question is, how to make this HATEOAS-compliant (so that the dev does not have to know the way he should create an url to get the models).
The root / gets me a number of links, such as:
{
"_links": {
"colors": "/colors",
"years": "/years",
"models": "???" }
}
What should be instead of ???? If there was some kind of template /models?color={color}&year={year}, the dev would have to create the url. Is this OK?
Or there could be a link to list of years on each color got from /colors and then a link to list of models on each year got from /years?color=red, but i'd have to first choose color, then populate years and then populate models. Any idea if i want to have the model dependent on both color and year, not just the year populated from color?
Is it even possible in this situation to make it hateoas-compliant?
I have not heard of HATEOAS before, but based on what I just read about it, it seems that it supposed to return links to where the consumer of the service can go forward in the "state machine".
In your case that would translate to the links being "function calls". The first two (/colors and /years) are functions that take no parameters (and return "something" at this point), while the third is a function call that takes two parameters: one that is a representation of a color, the other a year. For the first two having a simple URL will suffice for the link, but for the third, you need to include the parameter name/type information as well. Something like:
{
"_links": {
"colors": "/colors",
"years": "/years",
"models": {
"url": "/models",
"param1": {"color"}
"param2": {"year"}
}
}
}
Note: you can use the same layout as "models" for "colors" and "years" as well.
At this point the client knows what the URL to access the functions are and what the parameter (if any) names are to be passed to the function.
One more thing is missing: types. Although you could just use "string", it will not be obvious that the "color" parameter is actually a value from what "/colors" returns. You can be introducing a "type" Color that describes a color (and any functions that operate on a color: give a displayable name, HTML color code, etc.)
The "beefed up" signature becomes:
{
"_links": {
"colors": {
"url": "/colors",
"return": "/type/List?type=/type/Color"
},
"years": {
"url": "/years",
"return": "/type/List?type=/type/Integer"
},
"models": {
"url": "/models",
"param1": {
"name": "color",
"type": "/type/Color"
},
"param2": {
"name": "year",
"type": "/type/Integer"
}
"return": "/type/List?type=/type/Model"
}
}
}
Note: the path "/type" is used just to separate the types from functions, but is not necessary.
This will interchangeably and discoverably describe the functions, what parameters they take, and what values they are returning, so you can use the right value at the right place.
Of course implementing this on the service end will not be easy (especially with parameterized types, like "/type/List" -- think Generics in Java or templates in C++), but this is the most "safe" and "portable" way you can describe your interface to your clients.

Using ObjectMarshaller to return a RESTful paginated list

I'd like to use a customized DomainClassMarshaller/ObjectMarshaller class in grails to get a nice paginated list.
I'd like the full like to appear something like this:
> GET /api/company/1/bookings
< 200 OK
{
"url": "/api/company/1/bookings",
"size": 42,
"pageSize": 10,
"nextPage": "/api/company/1/bookings/?page=2,
"prevPage": null,
"items": [
{ ... // booking 1
},
...
{ ... // booking 10
},
]
}
Whereas if there's has_a relationship between domain objects, and you get the parent object you'll just get the URL, which you can then dive into if necessary.
> GET /api/company/1
< 200 OK
{
"url": "/api/company/1"
...
"bookings": "/api/company/1/bookings"
}
However, if you're faced with a list of simple types, just go ahead and output them:
> GET /api/user/1
< 200 OK
{
"url": "/api/user/1",
"name" "Bob,
"favoriteThings": [
"Raindrops on roses",
"Whiskers on kittens",
"Bright copper kettles",
"Warm woolen mittens"
]
}
DomainClassMarshaller has a very nice little method called asShortObject which seems like it would do the trick.
My first thought would be to register a DomainClassMarshaller that only accepts Lists of domain classes, and another one that accepts simple lists. Is that the best approach?
Are there any resources out there on doing something similar to this? I can't believe I'm the first one to have this requirement.
Thanks for all your help,
David

Does it make sense to use internal anchors for filtering a REST API's representation?

As a follow up to my previous question about REST URIs for retrieving statistical information for a web forum Resource, I want to know if it is possible to use the internal anchors as filter hints. See example below:
a) Get all statistics:
GET /group/5t7yu8i9io0op/stat
{
group_id: "5t7yu8i9io0op",
top_ranking_users: {
[ { user: "george", posts: 789, rank: 1 },
{ user: "joel", posts: 560, rank: 2 } ...]
},
popular_topics: {
[ ... ]
},
new_topics: {
[ ... ]
}
}
b) GET only popular topics
GET /group/5t7yu8i9io0op/stat#popular_topics
{
group_id: "5t7yu8i9io0op",
popular_topics: {
[ ... ]
}
}
c) GET only top ranking users
GET /group/5t7yu8i9io0op/stat#top_ranking_users
{
group_id: "5t7yu8i9io0op",
top_ranking_users: {
[ { user: "george", posts: 789, rank: 1 },
{ user: "joel", posts: 560, rank: 2 } ...]
}
}
Or should I be using query parameters ?
Not sure what you are trying to do exactly, but make sure you understand that fragment identifiers are not seen by the server, they are chopped off by the client connector.
See: http://www.nordsc.com/blog/?p=17
I've never seen anchors being used that way - it's interesting. That being said, I'd suggest using query parameters for a couple of reasons:
They're standard - and consumers of your api will be comfortable with them. There's nothing more annoying that dealing with a quirky api.
Many frameworks will auto-parse the query parameters and set them in a dictionary on the request object (or whatever analogue exists in your framework / http server library).
I think it would make more sense to have:
/group/5t7yu8i9io0op/stat/top_users
/group/5t7yu8i9io0op/stat/popular_topics
/group/5t7yu8i9io0op/stat/new_topics
/group/5t7yu8i9io0op/stat/user/george
No you cannot do that because as Jan points out the server will never see that fragment identifier. Literally, that part of the url will not reach the server.