REST API Design: Resource Binding

Suppose I have two top-level resources Foo and Bar . Now Foo needs to be associated with some of the Bar . In a Java class, it might look something like this:

 public class Foo { Set<Bar> bars; } public class Bar { … } 

I would like to formulate an XML Foo view something like this:

 GET /foos/1 <foo> … <atom:link rel="self" href="/foos/1" /> <atom:link rel="bars" href="/foos/1/bars" /> </foo> 

Therefore, I pretty much highlight Bar assigned to Foo as an embedded resource. This means that the Bar resource has an individual life cycle (aggregation instead of composition). A nested resource can then expose all related Bar something like this:

 GET /foos/1/bars <bars> <atom:link rel="bar" href="/foos/1/bars/1" /> <atom:link rel="bar" href="/foos/1/bars/2" /> </bars> 

Alternatively, I could embed the collection in an upfront <foo> element. However, I still have some questions: although this allows me to nicely remove Bar from Foo by running a DELETE query, for example. /foos/1/bars/1 , but how would I assign a Bar a Foo ? Assuming the client gets access to /bars :

 GET /bars <bars> <bar> … <atom:link rel="self" href="/bars/4711" /> </bar> </bars> 

and deciding that he wants to assign /bars/1 to /foo/1/bars . I thought about the POST request /foo/1/bars , but did not know what to actually send. A link pointing to a Bar resource, for example the following:

 POST /foos/1/bars <atom:link href="/bars/4711" /> 

This looks pretty normal, as clients still don't have to create URLs, and we still meet the REST restrictions. However, this is a little strange for POST server links. Is there a better solution for this scenario?

+6
source share
1 answer

I think about this in terms of resources understood by the server, not XML representations that come in response to (say) a GET request. I have RESTful services that return JSON or XML or potentially other views.

So, I agree with your POSTING or PUTing on

  /foos/{fooId}/bars 

to indicate either a complete list of bars or the addition of some bars.

The format of the hosted payload can be any natural serialized form for the media type you are using. In my case, this is often a JSON string, so in my implementation of the service, we deserialize and see an array of reference reference strings resoruse.

If your

 <atom:link href="/bars/4711" /> 

we also deserialize nicely, then I don’t see a problem if the serialized form is a little, um, decorative.

Summary: do what is natural for the serializer (de).

+4
source

Source: https://habr.com/ru/post/905701/


All Articles