Crafting an integrated REST API model with interconnected data

This question revolves around the implementation of a specific scenario rather than a problem I am facing. Let's say we have a User and a Resource, where a User can have multiple Resource but a Resource can have only 1 User. How should API endpoints be structured to interact with this data?

Should it follow a format like

// POST /api/users/resource (to create a resource)

Or perhaps something like

// POST /api/resource

This is just one example of many questions that arise when contemplating this issue. It would be helpful if someone with knowledge on best practices could provide an example of how to organize API endpoints for relational data like this.

Any guidance or advice would be greatly appreciated. Thank you!

Answer №1

In this scenario, I believe choosing the latter option is more beneficial. By opting for the endpoint /api/resource, we are not restricted to creating resources solely based on users. This opens up the possibility of creating resources for other entities such as a fictional "Supplier" in the future. This decision provides us with greater flexibility and avoids the need to modify the endpoint specifically for Suppliers.

Answer №2

One of the key principles of REST is the concealment of the server's resource implementation behind a standard interface. Essentially, it should be difficult to discern from the resource identifiers whether you are dealing with "relational data".

On one hand, this offers freedom in designing the most suitable resource model for your requirements; on the other hand, it can lead to overthinking due to the abundance of options available.


POST /api/users/resource 
POST /api/resource

Both options are acceptable. Machines can handle either message without issue. In fact, creating an API that caters to both scenarios would also work just fine.

So how do we make a decision?

The answer has two components. The first involves understanding resources, which are essentially abstractions of documents. When requesting a document on the web, one possibility is that the document may be cached. If sending a message intended to modify a document, it's vital to invalidate previously cached versions of that document.

The URI serves as the primary identifier for cached documents.

In the scenario where a message is sent to the server to store a new document and the server is expected to assign its own identifier to the copy, targeting the resource serving as the index of documents on the server makes logical sense.

This explains why CreateItem operations are typically implemented as POST handlers on a Collection resource - if an item is successfully added, cached responses to GET /collection should be invalidated.

Is this the only way to approach it? No, it's a matter of considering trade-offs and choosing one option. Opting for a separate resource for the CreateItem operation is equally valid.

The second aspect involves the URI itself - having determined which document will handle requests, what naming convention should be used for the identifier of that document.

Once again, machines aren't overly concerned. It must adhere to RFC 3986 standards, and using a spelling that aligns well with URI Templates can simplify matters. However, there is still flexibility in this decision.

The general advice? Consider the end users - those viewing browser histories, crafting API documentation, or analyzing access logs to comprehend traffic patterns. Choose a naming convention that is user-friendly and serves the individuals you prioritize.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In order to use DIV jQuery, it is necessary to have at least one input

In my form, there are 5 input fields. On button click using JQuery, I need to validate that at least one of these inputs is filled out. <div id='myForm'> <input name="baz" type="text" /> <input name="bat" type="text" /> ...

Are two JavaScript functions conflicting with each other?

Seeking assistance with integrating a Javascript/PHP/AJAX clock into my website to display various timezones (tutorial link: ) The clock implementation is functional, but it conflicts with an existing javascript stopwatch on the page, causing the clock no ...

Is there a way to validate form elements in HTML prior to submitting the form?

In my form, I am utilizing PHP for validation and processing, but I am interested in verifying elements as they are being filled out. Is there a way to check the current value of an element before the form is submitted? ...

Determine the date 7 days before today using JavaScript

I've been trying to calculate the date that is 12 days before today's date, but I'm running into an issue where it's not returning the correct result. For instance, if today is November 11, 2013 (mm/dd/yyyy), the code returns October 30 ...

Display a collection of pictures from a directory on a website using JavaScript

I am having trouble displaying a collection of images from a specific folder using JavaScript/jQuery. Below is the code snippet I am working with: $(document).ready(function(){ var dir = "images/"; // specified folder location var fileextension ...

Analyzing two arrays and utilizing ng-style to highlight matching entries within the arrays

My list displays words queried from a database, allowing me to click on a word to add it to another list that I can save. This functionality enables me to create multiple word lists. My goal is to visually distinguish the words in my query list that have a ...

Obtain the name of the checkbox that has been selected

I'm new to JavaScript and HTML, so my question might seem silly to you, but I'm stuck on it. I'm trying to get the name of the selected checkbox. Here's the code I've been working with: <br> <% for(var i = 0; i < ...

What is the best way to narrow down the content cards displayed on the page?

I have recently developed a blog post featuring three distinct categories: digital marketing, tips and advice, and cryptocurrency. My goal is to implement a filtering system for these categories. For instance, I would like users to be able to click on a b ...

Execute code after selecting the link

To simplify my question, I will provide an example: Suppose I have two sample pages that I want to demonstrate: Page 01 <script> var demo = 'X1'; alert(demo); $( document ).ready(function() { $("#cont").on("click" ...

A guide on retrieving information from a database with PHP and transferring it to Javascript

As I work on creating a website using HTML, CSS, MySQL, and JavaScript, my goal is to allow users to log in and engage in a quiz with 40 questions. Below is the JavaScript code for a countdown timer that includes the "questions" variable. After 40 seconds ...

Sending data from an Ionic application to a server

I came across this solution on a forum, but it lacks detailed explanation for me to customize it according to my requirements. The author also mentions a stack overflow question, which led to various "different" solutions leaving me feeling confused. Belo ...

Detecting collisions using CSS animation

I'm currently working on a unique "game" project. Check out the code snippet here: jsfiddle function update() { coyote.applyForce(gravity); coyote.edges(); coyote.update(); cactus.update(); if (coyote.intersects(cactus)){ alert("colisio ...

What is the point of utilizing angular.extend in this situation?

After inheriting a codebase, I stumbled upon the following code snippet (with some parameters simplified and anonymized): /** * @param {float} num1 * @param {string} str1 * @param {string} str2 * @param {boolean} flag & @return (object) */ sr ...

Attempting to demonstrate how to handle a duplicate entry error within a MySQL database through the use of Express.js and React.js

I have developed a CRUD application that is functioning perfectly. Now, I am working on adding validation to it in order to notify users when they try to insert an entry that already exists in the database. This is what I have implemented so far: console ...

End your Idp session and log out using passport-saml

Encountering a 400 bad request error when attempting to log out a user from the idp session. Despite successfully logging out the user from the application/passport session, they remain logged in to the idp session. The logout and callback endpoints are c ...

Troubleshooting an AngularJS and Express routing problem

While working with AngularJS and ExpressJS, I encountered an issue with routing. Despite looking at several other solutions online, none of them seemed to solve my problem. Below are the routes defined in Express: module.exports = function(app, auth) { ...

When trying to use `slug.current` in the link href(`/product/${slug.current}`), it seems to be undefined. However, when I try to log it to the console, it is displaying correctly

import React from 'react'; import Link from 'next/link'; import { urlFor } from '../lib/clients'; const Product = ({ product: { image, name, slug, price } }) => { return ( <div> <Link href={`/product/ ...

Exploring the use of MediaSource for seamless audio playback

Currently working on integrating an audio player into my Angular web application by following a tutorial from Google Developers and seeking guidance from a thread on Can't seek video when playing from MediaSource. The unique aspect of my implementati ...

An issue occurred while trying to establish a WebSocket connection: the 'Connection' header is missing from the handshake

Brand new to the world of Node and Socket.io, I recently launched my first chat application on spaiglas.com. Despite encountering a straightforward error in the developer console, the app is up and running smoothly... WebSocket connection to 'ws://ex ...

Switch up Google Fusion URL using Jquery

Looking to modify Google Fusion query using jQuery, here is the code snippet: var fusionid= ""; function initMap() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: {lat: 28.3268, lng: 84.1855}, zoom: 7 } ...