REST design principles: Referencing related objects vs Nesting objectsRESTful URL design for searchRepresentational state transfer (REST) and Simple Object Access Protocol (SOAP)How to design RESTful search/filtering?best approach to design a rest web service with binary data to be consumed from the browserWhat are best practices for REST nested resources?Best practices for authentication and authorization in Angular without breaking RESTful principles?REST API Update DesignTFS REST API for workitem missing relations section in JSON returnedHow to convert enrollment code to course id?Django Rest Framework Filter related model by lookup_field (uuid) in DRF instead of pk

Visualizing a complicated Region

How do I tell my manager that his code review comment is wrong?

When do aircrafts become solarcrafts?

What happens if I start too many background jobs?

Survey Confirmation - Emphasize the question or the answer?

How to efficiently calculate prefix sum of frequencies of characters in a string?

If Earth is tilted, why is Polaris always above the same spot?

Was the ancestor of SCSI, the SASI protocol, nothing more than a draft?

Airbnb - host wants to reduce rooms, can we get refund?

Visa for volunteering in England

Shoteh in the gemara

Why do freehub and cassette have only one position that matches?

How to avoid grep command finding commented out strings in the source file?

Sower of Discord, Gideon's Sacrifice and Stuffy Doll

Why are notes ordered like they are on a piano?

Pigeonhole Principle Problem

Unidentified items in bicycle tube repair kit

Was Unix ever a single-user OS?

How to compensate for height when using a ranged attack

Is lying to get "gardening leave" fraud?

Is it cheaper to drop cargo than to land it?

Is it the same airport YUL and YMQ in Canada?

Public Salesforce Site and Security Review

Is balancing necessary on a full-wheel change?



REST design principles: Referencing related objects vs Nesting objects


RESTful URL design for searchRepresentational state transfer (REST) and Simple Object Access Protocol (SOAP)How to design RESTful search/filtering?best approach to design a rest web service with binary data to be consumed from the browserWhat are best practices for REST nested resources?Best practices for authentication and authorization in Angular without breaking RESTful principles?REST API Update DesignTFS REST API for workitem missing relations section in JSON returnedHow to convert enrollment code to course id?Django Rest Framework Filter related model by lookup_field (uuid) in DRF instead of pk






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















My team and I we are refactoring a REST-API and I have come to a question.
For terms of brevity, let us assume that we have an SQL database with 4 tables: Teachers, Students, Courses and Classrooms.
Right now all the relations between the items are represented in the REST-API through referencing the URL of the related item. For example for a course we could have the following



 "id":"Course1", "teacher": "http://server.com/teacher1", ... 


In addition, if ask a list of courses thought a call GET call to /courses, I get a list of references as shown below:




... //pagination details
"items": [
"href": "http://server1.com/course1",
"href": "http://server1.com/course2"...
]



All this is nice and clean but if I want a list of all the courses titles with the teachers' names and I have 2000 courses and 500 teachers I have to do the following:



  • Approximately 2500 queries just to read the data.

  • Implement the join between the teachers and courses

  • Optimize with caching etc, so that I will do it as fast as possible.

My problem is that this method creates a lot of network traffic with thousands of REST-API calls and that I have to re-implement the natural join that the database would do way more efficiently.
Colleagues say that this is approach is the standard way of implementing a REST-API but then a relatively simple query becomes a big hassle.



My question therefore is:
1. Is it wrong if we we nest the teacher information in the courses.
2. Should the listing of items e.g. GET /courses return a list of references or a list of items?



Edit: After some research I would say the model I have in mind corresponds mainly to the one shown in jsonapi.org. Is this a good approach?










share|improve this question






























    0















    My team and I we are refactoring a REST-API and I have come to a question.
    For terms of brevity, let us assume that we have an SQL database with 4 tables: Teachers, Students, Courses and Classrooms.
    Right now all the relations between the items are represented in the REST-API through referencing the URL of the related item. For example for a course we could have the following



     "id":"Course1", "teacher": "http://server.com/teacher1", ... 


    In addition, if ask a list of courses thought a call GET call to /courses, I get a list of references as shown below:




    ... //pagination details
    "items": [
    "href": "http://server1.com/course1",
    "href": "http://server1.com/course2"...
    ]



    All this is nice and clean but if I want a list of all the courses titles with the teachers' names and I have 2000 courses and 500 teachers I have to do the following:



    • Approximately 2500 queries just to read the data.

    • Implement the join between the teachers and courses

    • Optimize with caching etc, so that I will do it as fast as possible.

    My problem is that this method creates a lot of network traffic with thousands of REST-API calls and that I have to re-implement the natural join that the database would do way more efficiently.
    Colleagues say that this is approach is the standard way of implementing a REST-API but then a relatively simple query becomes a big hassle.



    My question therefore is:
    1. Is it wrong if we we nest the teacher information in the courses.
    2. Should the listing of items e.g. GET /courses return a list of references or a list of items?



    Edit: After some research I would say the model I have in mind corresponds mainly to the one shown in jsonapi.org. Is this a good approach?










    share|improve this question


























      0












      0








      0








      My team and I we are refactoring a REST-API and I have come to a question.
      For terms of brevity, let us assume that we have an SQL database with 4 tables: Teachers, Students, Courses and Classrooms.
      Right now all the relations between the items are represented in the REST-API through referencing the URL of the related item. For example for a course we could have the following



       "id":"Course1", "teacher": "http://server.com/teacher1", ... 


      In addition, if ask a list of courses thought a call GET call to /courses, I get a list of references as shown below:




      ... //pagination details
      "items": [
      "href": "http://server1.com/course1",
      "href": "http://server1.com/course2"...
      ]



      All this is nice and clean but if I want a list of all the courses titles with the teachers' names and I have 2000 courses and 500 teachers I have to do the following:



      • Approximately 2500 queries just to read the data.

      • Implement the join between the teachers and courses

      • Optimize with caching etc, so that I will do it as fast as possible.

      My problem is that this method creates a lot of network traffic with thousands of REST-API calls and that I have to re-implement the natural join that the database would do way more efficiently.
      Colleagues say that this is approach is the standard way of implementing a REST-API but then a relatively simple query becomes a big hassle.



      My question therefore is:
      1. Is it wrong if we we nest the teacher information in the courses.
      2. Should the listing of items e.g. GET /courses return a list of references or a list of items?



      Edit: After some research I would say the model I have in mind corresponds mainly to the one shown in jsonapi.org. Is this a good approach?










      share|improve this question
















      My team and I we are refactoring a REST-API and I have come to a question.
      For terms of brevity, let us assume that we have an SQL database with 4 tables: Teachers, Students, Courses and Classrooms.
      Right now all the relations between the items are represented in the REST-API through referencing the URL of the related item. For example for a course we could have the following



       "id":"Course1", "teacher": "http://server.com/teacher1", ... 


      In addition, if ask a list of courses thought a call GET call to /courses, I get a list of references as shown below:




      ... //pagination details
      "items": [
      "href": "http://server1.com/course1",
      "href": "http://server1.com/course2"...
      ]



      All this is nice and clean but if I want a list of all the courses titles with the teachers' names and I have 2000 courses and 500 teachers I have to do the following:



      • Approximately 2500 queries just to read the data.

      • Implement the join between the teachers and courses

      • Optimize with caching etc, so that I will do it as fast as possible.

      My problem is that this method creates a lot of network traffic with thousands of REST-API calls and that I have to re-implement the natural join that the database would do way more efficiently.
      Colleagues say that this is approach is the standard way of implementing a REST-API but then a relatively simple query becomes a big hassle.



      My question therefore is:
      1. Is it wrong if we we nest the teacher information in the courses.
      2. Should the listing of items e.g. GET /courses return a list of references or a list of items?



      Edit: After some research I would say the model I have in mind corresponds mainly to the one shown in jsonapi.org. Is this a good approach?







      rest






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 22 at 20:37







      orestis

















      asked Mar 22 at 19:59









      orestisorestis

      331215




      331215






















          3 Answers
          3






          active

          oldest

          votes


















          1















          My problem is that this method creates a lot of network traffic with thousands of REST-API calls and that I have to re-implement the natural join that the database would do way more efficiently. Colleagues say that this is approach is the standard way of implementing a REST-API but then a relatively simple query becomes a big hassle.




          Have you actually measured the overhead generated by each request? If not, how do you know that the overhead will be too intense? From an object-oriented programmers perspective it may sound bad to perform each call on their own, your design, however, lacks one important asset which helped the Web to grew to its current size: caching.



          Caching can occur on multiple levels. You can do it on the API level or the client might do something or an intermediary server might do it. Fielding even mad it a constraint of REST! So, if you want to comply to the REST architecture philosophy you should also support caching of responses. Caching helps to reduce the number of requests having to be calculated or even processed by a single server. With the help of stateless communication you might even introduce a multitude of servers that all perform calculations for billions of requests that act as one cohesive system to the client. An intermediary cache may further help to reduce the number of requests that actually reach the server significantly.



          A URI as a whole (including any path, matrix or query parameters) is actually a key for a cache. Upon receiving a GET request, i.e., an application checks whether its current cache already contains a stored response for that URI and returns the stored response on behalf of the server directly to the client if the stored data is "fresh enough". If the stored data already exceeded the freshness threshold it will throw away the stored data and route the request to the next hop in line (might be the actual server, might be a further intermediary).



          Spotting resources that are ideal for caching might not be easy at times, though the majority of data doesn't change that quickly to completely neglect caching at all. Thus, it should be, at least, of general interest to introduce caching, especially the more traffic your API produces.



          While certain media-types such as HAL JSON, jsonapi, ... allow you to embed content gathered from related resources into the response, embedding content has some potential drawbacks such as:



          • Utilization of the cache might be low due to mixing data that changes quickly with data that is more static

          • Server might calculate data the client wont need

          • One server calculates the whole response

          If related resources are only linked to instead of directly embedded, a client for sure has to fire off a further request to obtain that data, though it actually is more likely to get (partly) served by a cache which, as mentioned a couple times now throughout the post, reduces the workload on the server. Besides that, a positive side effect could be that you gain more insights into what the clients are actually interested in (if an intermediary cache is run by you i.e.).




          1. Is it wrong if we we nest the teacher information in the courses.



          It is not wrong, but it might not be ideal as explained above




          1. Should the listing of items e.g. GET /courses return a list of references or a list of items?



          It depends. There is no right or wrong.



          As REST is just a generalization of the interaction model used in the Web, basically the same concepts apply to REST as well. Depending on the size of the "item" it might be beneficial to return a short summary of the items content and add a link to the item. Similar things are done in the Web as well. For a list of students enrolled in a course this might be the name and its matriculation number and the link further details of that student could be asked for accompanied by a link-relation name that give the actual link some semantical context which a client can use to decide whether invoking such URI makes sense or not.



          Such link-relation names are either standardized by IANA, common approaches such as Dublin Core or schema.org or custom extensions as defined in RFC 8288 (Web Linking). For the above mentioned list of students enrolled in a course you could i.e. make use of the about relation name to hint a client that further information on the current item can be found by following the link. If you want to enable pagination the usage of first, next, prev and last can and probably should be used as well and so forth.



          This is actually what HATEOAS is all about. Linking data together and giving them meaningful relation names to span a kind of semantic net between resources. By simply embedding things into a response such semantic graphs might be harder to build and maintain.



          In the end it basically boils down to implementation choice whether you want to embed or reference resources. I hope, I could shed some light on the usefulness of caching and the benefits it could yield, especially on large-scale systems, as well as on the benefit of providing link-relation names for URIs, that enhance the semantical context of relations used within your API.






          share|improve this answer






























            1















            My problem is that this method creates a lot of network traffic with thousands of REST-API calls and that I have to re-implement the natural join that the database would do way more efficiently. Colleagues say that this is approach is the standard way of implementing a REST-API but then a relatively simple query becomes a big hassle.




            Your colleagues have lost the plot.



            Here's your heuristic - how would you support this use case on a web site?



            You would probably do it by defining a new web page, that produces the report you need. You'd run the query, you the result set to generate a bunch of HTML, and ta-da! The client has the information that they need in a standardized representation.



            A REST-API is the same thing, with more emphasis on machine readability. Create a new document, with a schema so that your clients can understand the semantics of the document you return to them, tell the clients how to find the target uri for the document, and voila.



            Creating new resources to handle new use cases is the normal approach to REST.






            share|improve this answer






























              0














              Yes, I totally think you should design something similar to jsonapi.org. As a rule of thumb, I would say "prefer a solution that requires less network calls". It's especially true if amount of network calls will be less by order of magnitude.
              Of course it doesn't eliminate the need to limit the request/response size if it becomes unreasonable.



              Real life solutions must have a proper balance. Clean API is nice as long as it works.



              So in your case I would so something like:



              GET /courses?include=teachers


              Or



              GET /courses?includeTeacher=true


              Or



              GET /courses?includeTeacher=brief|full


              In the last one the response can have only the teacher's id for brief and full teacher details for full.






              share|improve this answer























                Your Answer






                StackExchange.ifUsing("editor", function ()
                StackExchange.using("externalEditor", function ()
                StackExchange.using("snippets", function ()
                StackExchange.snippets.init();
                );
                );
                , "code-snippets");

                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "1"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );













                draft saved

                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55307011%2frest-design-principles-referencing-related-objects-vs-nesting-objects%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                1















                My problem is that this method creates a lot of network traffic with thousands of REST-API calls and that I have to re-implement the natural join that the database would do way more efficiently. Colleagues say that this is approach is the standard way of implementing a REST-API but then a relatively simple query becomes a big hassle.




                Have you actually measured the overhead generated by each request? If not, how do you know that the overhead will be too intense? From an object-oriented programmers perspective it may sound bad to perform each call on their own, your design, however, lacks one important asset which helped the Web to grew to its current size: caching.



                Caching can occur on multiple levels. You can do it on the API level or the client might do something or an intermediary server might do it. Fielding even mad it a constraint of REST! So, if you want to comply to the REST architecture philosophy you should also support caching of responses. Caching helps to reduce the number of requests having to be calculated or even processed by a single server. With the help of stateless communication you might even introduce a multitude of servers that all perform calculations for billions of requests that act as one cohesive system to the client. An intermediary cache may further help to reduce the number of requests that actually reach the server significantly.



                A URI as a whole (including any path, matrix or query parameters) is actually a key for a cache. Upon receiving a GET request, i.e., an application checks whether its current cache already contains a stored response for that URI and returns the stored response on behalf of the server directly to the client if the stored data is "fresh enough". If the stored data already exceeded the freshness threshold it will throw away the stored data and route the request to the next hop in line (might be the actual server, might be a further intermediary).



                Spotting resources that are ideal for caching might not be easy at times, though the majority of data doesn't change that quickly to completely neglect caching at all. Thus, it should be, at least, of general interest to introduce caching, especially the more traffic your API produces.



                While certain media-types such as HAL JSON, jsonapi, ... allow you to embed content gathered from related resources into the response, embedding content has some potential drawbacks such as:



                • Utilization of the cache might be low due to mixing data that changes quickly with data that is more static

                • Server might calculate data the client wont need

                • One server calculates the whole response

                If related resources are only linked to instead of directly embedded, a client for sure has to fire off a further request to obtain that data, though it actually is more likely to get (partly) served by a cache which, as mentioned a couple times now throughout the post, reduces the workload on the server. Besides that, a positive side effect could be that you gain more insights into what the clients are actually interested in (if an intermediary cache is run by you i.e.).




                1. Is it wrong if we we nest the teacher information in the courses.



                It is not wrong, but it might not be ideal as explained above




                1. Should the listing of items e.g. GET /courses return a list of references or a list of items?



                It depends. There is no right or wrong.



                As REST is just a generalization of the interaction model used in the Web, basically the same concepts apply to REST as well. Depending on the size of the "item" it might be beneficial to return a short summary of the items content and add a link to the item. Similar things are done in the Web as well. For a list of students enrolled in a course this might be the name and its matriculation number and the link further details of that student could be asked for accompanied by a link-relation name that give the actual link some semantical context which a client can use to decide whether invoking such URI makes sense or not.



                Such link-relation names are either standardized by IANA, common approaches such as Dublin Core or schema.org or custom extensions as defined in RFC 8288 (Web Linking). For the above mentioned list of students enrolled in a course you could i.e. make use of the about relation name to hint a client that further information on the current item can be found by following the link. If you want to enable pagination the usage of first, next, prev and last can and probably should be used as well and so forth.



                This is actually what HATEOAS is all about. Linking data together and giving them meaningful relation names to span a kind of semantic net between resources. By simply embedding things into a response such semantic graphs might be harder to build and maintain.



                In the end it basically boils down to implementation choice whether you want to embed or reference resources. I hope, I could shed some light on the usefulness of caching and the benefits it could yield, especially on large-scale systems, as well as on the benefit of providing link-relation names for URIs, that enhance the semantical context of relations used within your API.






                share|improve this answer



























                  1















                  My problem is that this method creates a lot of network traffic with thousands of REST-API calls and that I have to re-implement the natural join that the database would do way more efficiently. Colleagues say that this is approach is the standard way of implementing a REST-API but then a relatively simple query becomes a big hassle.




                  Have you actually measured the overhead generated by each request? If not, how do you know that the overhead will be too intense? From an object-oriented programmers perspective it may sound bad to perform each call on their own, your design, however, lacks one important asset which helped the Web to grew to its current size: caching.



                  Caching can occur on multiple levels. You can do it on the API level or the client might do something or an intermediary server might do it. Fielding even mad it a constraint of REST! So, if you want to comply to the REST architecture philosophy you should also support caching of responses. Caching helps to reduce the number of requests having to be calculated or even processed by a single server. With the help of stateless communication you might even introduce a multitude of servers that all perform calculations for billions of requests that act as one cohesive system to the client. An intermediary cache may further help to reduce the number of requests that actually reach the server significantly.



                  A URI as a whole (including any path, matrix or query parameters) is actually a key for a cache. Upon receiving a GET request, i.e., an application checks whether its current cache already contains a stored response for that URI and returns the stored response on behalf of the server directly to the client if the stored data is "fresh enough". If the stored data already exceeded the freshness threshold it will throw away the stored data and route the request to the next hop in line (might be the actual server, might be a further intermediary).



                  Spotting resources that are ideal for caching might not be easy at times, though the majority of data doesn't change that quickly to completely neglect caching at all. Thus, it should be, at least, of general interest to introduce caching, especially the more traffic your API produces.



                  While certain media-types such as HAL JSON, jsonapi, ... allow you to embed content gathered from related resources into the response, embedding content has some potential drawbacks such as:



                  • Utilization of the cache might be low due to mixing data that changes quickly with data that is more static

                  • Server might calculate data the client wont need

                  • One server calculates the whole response

                  If related resources are only linked to instead of directly embedded, a client for sure has to fire off a further request to obtain that data, though it actually is more likely to get (partly) served by a cache which, as mentioned a couple times now throughout the post, reduces the workload on the server. Besides that, a positive side effect could be that you gain more insights into what the clients are actually interested in (if an intermediary cache is run by you i.e.).




                  1. Is it wrong if we we nest the teacher information in the courses.



                  It is not wrong, but it might not be ideal as explained above




                  1. Should the listing of items e.g. GET /courses return a list of references or a list of items?



                  It depends. There is no right or wrong.



                  As REST is just a generalization of the interaction model used in the Web, basically the same concepts apply to REST as well. Depending on the size of the "item" it might be beneficial to return a short summary of the items content and add a link to the item. Similar things are done in the Web as well. For a list of students enrolled in a course this might be the name and its matriculation number and the link further details of that student could be asked for accompanied by a link-relation name that give the actual link some semantical context which a client can use to decide whether invoking such URI makes sense or not.



                  Such link-relation names are either standardized by IANA, common approaches such as Dublin Core or schema.org or custom extensions as defined in RFC 8288 (Web Linking). For the above mentioned list of students enrolled in a course you could i.e. make use of the about relation name to hint a client that further information on the current item can be found by following the link. If you want to enable pagination the usage of first, next, prev and last can and probably should be used as well and so forth.



                  This is actually what HATEOAS is all about. Linking data together and giving them meaningful relation names to span a kind of semantic net between resources. By simply embedding things into a response such semantic graphs might be harder to build and maintain.



                  In the end it basically boils down to implementation choice whether you want to embed or reference resources. I hope, I could shed some light on the usefulness of caching and the benefits it could yield, especially on large-scale systems, as well as on the benefit of providing link-relation names for URIs, that enhance the semantical context of relations used within your API.






                  share|improve this answer

























                    1












                    1








                    1








                    My problem is that this method creates a lot of network traffic with thousands of REST-API calls and that I have to re-implement the natural join that the database would do way more efficiently. Colleagues say that this is approach is the standard way of implementing a REST-API but then a relatively simple query becomes a big hassle.




                    Have you actually measured the overhead generated by each request? If not, how do you know that the overhead will be too intense? From an object-oriented programmers perspective it may sound bad to perform each call on their own, your design, however, lacks one important asset which helped the Web to grew to its current size: caching.



                    Caching can occur on multiple levels. You can do it on the API level or the client might do something or an intermediary server might do it. Fielding even mad it a constraint of REST! So, if you want to comply to the REST architecture philosophy you should also support caching of responses. Caching helps to reduce the number of requests having to be calculated or even processed by a single server. With the help of stateless communication you might even introduce a multitude of servers that all perform calculations for billions of requests that act as one cohesive system to the client. An intermediary cache may further help to reduce the number of requests that actually reach the server significantly.



                    A URI as a whole (including any path, matrix or query parameters) is actually a key for a cache. Upon receiving a GET request, i.e., an application checks whether its current cache already contains a stored response for that URI and returns the stored response on behalf of the server directly to the client if the stored data is "fresh enough". If the stored data already exceeded the freshness threshold it will throw away the stored data and route the request to the next hop in line (might be the actual server, might be a further intermediary).



                    Spotting resources that are ideal for caching might not be easy at times, though the majority of data doesn't change that quickly to completely neglect caching at all. Thus, it should be, at least, of general interest to introduce caching, especially the more traffic your API produces.



                    While certain media-types such as HAL JSON, jsonapi, ... allow you to embed content gathered from related resources into the response, embedding content has some potential drawbacks such as:



                    • Utilization of the cache might be low due to mixing data that changes quickly with data that is more static

                    • Server might calculate data the client wont need

                    • One server calculates the whole response

                    If related resources are only linked to instead of directly embedded, a client for sure has to fire off a further request to obtain that data, though it actually is more likely to get (partly) served by a cache which, as mentioned a couple times now throughout the post, reduces the workload on the server. Besides that, a positive side effect could be that you gain more insights into what the clients are actually interested in (if an intermediary cache is run by you i.e.).




                    1. Is it wrong if we we nest the teacher information in the courses.



                    It is not wrong, but it might not be ideal as explained above




                    1. Should the listing of items e.g. GET /courses return a list of references or a list of items?



                    It depends. There is no right or wrong.



                    As REST is just a generalization of the interaction model used in the Web, basically the same concepts apply to REST as well. Depending on the size of the "item" it might be beneficial to return a short summary of the items content and add a link to the item. Similar things are done in the Web as well. For a list of students enrolled in a course this might be the name and its matriculation number and the link further details of that student could be asked for accompanied by a link-relation name that give the actual link some semantical context which a client can use to decide whether invoking such URI makes sense or not.



                    Such link-relation names are either standardized by IANA, common approaches such as Dublin Core or schema.org or custom extensions as defined in RFC 8288 (Web Linking). For the above mentioned list of students enrolled in a course you could i.e. make use of the about relation name to hint a client that further information on the current item can be found by following the link. If you want to enable pagination the usage of first, next, prev and last can and probably should be used as well and so forth.



                    This is actually what HATEOAS is all about. Linking data together and giving them meaningful relation names to span a kind of semantic net between resources. By simply embedding things into a response such semantic graphs might be harder to build and maintain.



                    In the end it basically boils down to implementation choice whether you want to embed or reference resources. I hope, I could shed some light on the usefulness of caching and the benefits it could yield, especially on large-scale systems, as well as on the benefit of providing link-relation names for URIs, that enhance the semantical context of relations used within your API.






                    share|improve this answer














                    My problem is that this method creates a lot of network traffic with thousands of REST-API calls and that I have to re-implement the natural join that the database would do way more efficiently. Colleagues say that this is approach is the standard way of implementing a REST-API but then a relatively simple query becomes a big hassle.




                    Have you actually measured the overhead generated by each request? If not, how do you know that the overhead will be too intense? From an object-oriented programmers perspective it may sound bad to perform each call on their own, your design, however, lacks one important asset which helped the Web to grew to its current size: caching.



                    Caching can occur on multiple levels. You can do it on the API level or the client might do something or an intermediary server might do it. Fielding even mad it a constraint of REST! So, if you want to comply to the REST architecture philosophy you should also support caching of responses. Caching helps to reduce the number of requests having to be calculated or even processed by a single server. With the help of stateless communication you might even introduce a multitude of servers that all perform calculations for billions of requests that act as one cohesive system to the client. An intermediary cache may further help to reduce the number of requests that actually reach the server significantly.



                    A URI as a whole (including any path, matrix or query parameters) is actually a key for a cache. Upon receiving a GET request, i.e., an application checks whether its current cache already contains a stored response for that URI and returns the stored response on behalf of the server directly to the client if the stored data is "fresh enough". If the stored data already exceeded the freshness threshold it will throw away the stored data and route the request to the next hop in line (might be the actual server, might be a further intermediary).



                    Spotting resources that are ideal for caching might not be easy at times, though the majority of data doesn't change that quickly to completely neglect caching at all. Thus, it should be, at least, of general interest to introduce caching, especially the more traffic your API produces.



                    While certain media-types such as HAL JSON, jsonapi, ... allow you to embed content gathered from related resources into the response, embedding content has some potential drawbacks such as:



                    • Utilization of the cache might be low due to mixing data that changes quickly with data that is more static

                    • Server might calculate data the client wont need

                    • One server calculates the whole response

                    If related resources are only linked to instead of directly embedded, a client for sure has to fire off a further request to obtain that data, though it actually is more likely to get (partly) served by a cache which, as mentioned a couple times now throughout the post, reduces the workload on the server. Besides that, a positive side effect could be that you gain more insights into what the clients are actually interested in (if an intermediary cache is run by you i.e.).




                    1. Is it wrong if we we nest the teacher information in the courses.



                    It is not wrong, but it might not be ideal as explained above




                    1. Should the listing of items e.g. GET /courses return a list of references or a list of items?



                    It depends. There is no right or wrong.



                    As REST is just a generalization of the interaction model used in the Web, basically the same concepts apply to REST as well. Depending on the size of the "item" it might be beneficial to return a short summary of the items content and add a link to the item. Similar things are done in the Web as well. For a list of students enrolled in a course this might be the name and its matriculation number and the link further details of that student could be asked for accompanied by a link-relation name that give the actual link some semantical context which a client can use to decide whether invoking such URI makes sense or not.



                    Such link-relation names are either standardized by IANA, common approaches such as Dublin Core or schema.org or custom extensions as defined in RFC 8288 (Web Linking). For the above mentioned list of students enrolled in a course you could i.e. make use of the about relation name to hint a client that further information on the current item can be found by following the link. If you want to enable pagination the usage of first, next, prev and last can and probably should be used as well and so forth.



                    This is actually what HATEOAS is all about. Linking data together and giving them meaningful relation names to span a kind of semantic net between resources. By simply embedding things into a response such semantic graphs might be harder to build and maintain.



                    In the end it basically boils down to implementation choice whether you want to embed or reference resources. I hope, I could shed some light on the usefulness of caching and the benefits it could yield, especially on large-scale systems, as well as on the benefit of providing link-relation names for URIs, that enhance the semantical context of relations used within your API.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 22 at 23:10









                    Roman VottnerRoman Vottner

                    6,23812541




                    6,23812541























                        1















                        My problem is that this method creates a lot of network traffic with thousands of REST-API calls and that I have to re-implement the natural join that the database would do way more efficiently. Colleagues say that this is approach is the standard way of implementing a REST-API but then a relatively simple query becomes a big hassle.




                        Your colleagues have lost the plot.



                        Here's your heuristic - how would you support this use case on a web site?



                        You would probably do it by defining a new web page, that produces the report you need. You'd run the query, you the result set to generate a bunch of HTML, and ta-da! The client has the information that they need in a standardized representation.



                        A REST-API is the same thing, with more emphasis on machine readability. Create a new document, with a schema so that your clients can understand the semantics of the document you return to them, tell the clients how to find the target uri for the document, and voila.



                        Creating new resources to handle new use cases is the normal approach to REST.






                        share|improve this answer



























                          1















                          My problem is that this method creates a lot of network traffic with thousands of REST-API calls and that I have to re-implement the natural join that the database would do way more efficiently. Colleagues say that this is approach is the standard way of implementing a REST-API but then a relatively simple query becomes a big hassle.




                          Your colleagues have lost the plot.



                          Here's your heuristic - how would you support this use case on a web site?



                          You would probably do it by defining a new web page, that produces the report you need. You'd run the query, you the result set to generate a bunch of HTML, and ta-da! The client has the information that they need in a standardized representation.



                          A REST-API is the same thing, with more emphasis on machine readability. Create a new document, with a schema so that your clients can understand the semantics of the document you return to them, tell the clients how to find the target uri for the document, and voila.



                          Creating new resources to handle new use cases is the normal approach to REST.






                          share|improve this answer

























                            1












                            1








                            1








                            My problem is that this method creates a lot of network traffic with thousands of REST-API calls and that I have to re-implement the natural join that the database would do way more efficiently. Colleagues say that this is approach is the standard way of implementing a REST-API but then a relatively simple query becomes a big hassle.




                            Your colleagues have lost the plot.



                            Here's your heuristic - how would you support this use case on a web site?



                            You would probably do it by defining a new web page, that produces the report you need. You'd run the query, you the result set to generate a bunch of HTML, and ta-da! The client has the information that they need in a standardized representation.



                            A REST-API is the same thing, with more emphasis on machine readability. Create a new document, with a schema so that your clients can understand the semantics of the document you return to them, tell the clients how to find the target uri for the document, and voila.



                            Creating new resources to handle new use cases is the normal approach to REST.






                            share|improve this answer














                            My problem is that this method creates a lot of network traffic with thousands of REST-API calls and that I have to re-implement the natural join that the database would do way more efficiently. Colleagues say that this is approach is the standard way of implementing a REST-API but then a relatively simple query becomes a big hassle.




                            Your colleagues have lost the plot.



                            Here's your heuristic - how would you support this use case on a web site?



                            You would probably do it by defining a new web page, that produces the report you need. You'd run the query, you the result set to generate a bunch of HTML, and ta-da! The client has the information that they need in a standardized representation.



                            A REST-API is the same thing, with more emphasis on machine readability. Create a new document, with a schema so that your clients can understand the semantics of the document you return to them, tell the clients how to find the target uri for the document, and voila.



                            Creating new resources to handle new use cases is the normal approach to REST.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 23 at 2:13









                            VoiceOfUnreasonVoiceOfUnreason

                            22.2k22251




                            22.2k22251





















                                0














                                Yes, I totally think you should design something similar to jsonapi.org. As a rule of thumb, I would say "prefer a solution that requires less network calls". It's especially true if amount of network calls will be less by order of magnitude.
                                Of course it doesn't eliminate the need to limit the request/response size if it becomes unreasonable.



                                Real life solutions must have a proper balance. Clean API is nice as long as it works.



                                So in your case I would so something like:



                                GET /courses?include=teachers


                                Or



                                GET /courses?includeTeacher=true


                                Or



                                GET /courses?includeTeacher=brief|full


                                In the last one the response can have only the teacher's id for brief and full teacher details for full.






                                share|improve this answer



























                                  0














                                  Yes, I totally think you should design something similar to jsonapi.org. As a rule of thumb, I would say "prefer a solution that requires less network calls". It's especially true if amount of network calls will be less by order of magnitude.
                                  Of course it doesn't eliminate the need to limit the request/response size if it becomes unreasonable.



                                  Real life solutions must have a proper balance. Clean API is nice as long as it works.



                                  So in your case I would so something like:



                                  GET /courses?include=teachers


                                  Or



                                  GET /courses?includeTeacher=true


                                  Or



                                  GET /courses?includeTeacher=brief|full


                                  In the last one the response can have only the teacher's id for brief and full teacher details for full.






                                  share|improve this answer

























                                    0












                                    0








                                    0







                                    Yes, I totally think you should design something similar to jsonapi.org. As a rule of thumb, I would say "prefer a solution that requires less network calls". It's especially true if amount of network calls will be less by order of magnitude.
                                    Of course it doesn't eliminate the need to limit the request/response size if it becomes unreasonable.



                                    Real life solutions must have a proper balance. Clean API is nice as long as it works.



                                    So in your case I would so something like:



                                    GET /courses?include=teachers


                                    Or



                                    GET /courses?includeTeacher=true


                                    Or



                                    GET /courses?includeTeacher=brief|full


                                    In the last one the response can have only the teacher's id for brief and full teacher details for full.






                                    share|improve this answer













                                    Yes, I totally think you should design something similar to jsonapi.org. As a rule of thumb, I would say "prefer a solution that requires less network calls". It's especially true if amount of network calls will be less by order of magnitude.
                                    Of course it doesn't eliminate the need to limit the request/response size if it becomes unreasonable.



                                    Real life solutions must have a proper balance. Clean API is nice as long as it works.



                                    So in your case I would so something like:



                                    GET /courses?include=teachers


                                    Or



                                    GET /courses?includeTeacher=true


                                    Or



                                    GET /courses?includeTeacher=brief|full


                                    In the last one the response can have only the teacher's id for brief and full teacher details for full.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Mar 22 at 20:50









                                    TarlogTarlog

                                    8,57523665




                                    8,57523665



























                                        draft saved

                                        draft discarded
















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid


                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.

                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55307011%2frest-design-principles-referencing-related-objects-vs-nesting-objects%23new-answer', 'question_page');

                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                        용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                                        155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해