REST-API database-relationships back-referencing - mysql

I’m developing a REST-API with NodeJS and Express with a MySQL-backend. The existing database has a lot of 1:n relationships and I’m struggling to find the right URI-scheme for these specific cases.
A simple example:
user {
id
name
}
comment {
id
text
user_id
}
Now, when I try to get the a list of all users, my uri would be: /users
- for one specific user: /user/{id}
- data for one specific user: /user/{id}/name
- for a list of all comments: /comment
- for one specific comment: /comment/{id}
- data for one specific comment: /comment/{id}/text
Now, the part where I’m struggling.
There is a 1:n relationship between user and comment. One user can have multiple comments, one comment belongs to one user. I want to implement something like a ‘back-reference’, so that when I access the data (meaning one specific field) for one specific comment, I can also get the information about the user the comment ‘belongs’ to.
The API doesn't know about these relationships, I'm also not using an ORM, so I have to hard code the information about the relationships somewhere anyway.
I already implemented a route where I can make a request on /comment/{id}/user_id where I redirect the request to /user/{id} with the id the comment belongs to. But this would be the same request for when I just want to get the user id for that comment, not the whole dataset for the user.
I've read a lot about the REST architecture and roy fielding always talks about making the API "browsable" or "explorable". One approach I came upon was adding a reference uri to the linked dataset, in my example that would mean expanding the user_id field to something like this :
user_id {
id:id
ref:/user/id
}
The results I'm getting from the database are much more complex than that and extracting the respective fields and adding this information seems like a bit much to do for this ‘simple’ problem.
I don't know if I'm missing something here, I'm developing this API for a project on which I also write a paper about and I try to follow the rules of the REST architecture as much as I can, but I'm a bit stuck right now.

What about publishing the comments "under" the user resources like this:
/user/{userid}
/user/{userid}/comments/{commentid}
Note, that you don't have to publish "database rows" one-to-one in a REST API. Indeed, this is usually frowned upon by REST people.
Also note, you don't have to publish each attribute of a resource as a resource. The resource /user/{userid} could very well return a complex (json, xml, etc.) representation that includes all the necessary data. Of course there are reasons to do it your way, for example I would make the text of a comment a separate resource if it is available in pdf, text, html, or in other formats which I don't control.
A minor point about Fielding's "browsable" API: What he means is that these resources reference each other through links in the returned data representations. Comments would reference the users (link to user), and users should reference their comments (links to comments). The client should never have to "guess" or "construct" an URI on its own, it should "browse" resources by following links only!

Related

What is the use of all GET, PUT, DELETE when anything can be done by POST in the most secured way of communication in REST API calls

I read a lot about each and every function of those mentioned in the title,
But I always have doubt that what is the primary use of all individual functions. Can someone explain to me in detail? Thank you.
What is the use of all GET, PUT, DELETE when anything can be done by POST
This is a pretty important question.
Note that, historically, SOAP essentially did everything by POST; effectively reducing HTTP from an application protocol to a transport protocol.
The big advantage of GET/PUT/DELETE is that the additional semantics that they promise (meaning, the semantics that are part of the uniform interface agreed to by all resources) allow us to build general purpose components that can do interesting things with the meta data alone, without needing to understand anything specific about the body of the message.
The most important of these is GET, which promises that the action of the request is safe. What this means is that, for any resource in the world, we can just try a GET request to "see what happens".
In other words, because GET is safe, we can have web crawlers, and automated document indexing, and eventually Google.
(Another example - today, I can send you a bare URI, like https://www.google.com and it "just works" because GET is understood uniformly, and does not require that we share any further details about a payload or metadata.)
Similarly, PUT and DELETE have additional semantic constraints that allow general purpose components to do interesting things like automatically retry lost requests when the network is unreliable.
POST, however, is effectively unconstrained, and this greatly restricts the actions of general purpose components.
That doesn't mean that POST is the wrong choice; if the semantics of a request aren't worth standardizing, then POST is fine.
In API perspective,
GET - It is to retrieve record/data from a source. API would need no data from client/UI to retrieve all records , or would need query param / path param to filter records based on what is required - either record with a particular ID or other properties.
POST - it is to store a new record at a source . API would get that record from client/UI through request body and store it.
PUT - it is to update an existing record at a source . API would receive updated record along with Id and update it with existing record whose id match with one passed from UI.
DELETE - it is to delete a record present in source. UI would send nothing to delete whole all records at source or send id to remove a particular record.
Source refers to any database.

Best practice for URI pattern for REST api and UI web pages

after years of absence from web programming I now start to write a new web application from scratch. I learned the ropes of REST and found some helfful presentations and webinars about good and bad "URI styles". But all these tutorials seems to assume that there are only ressources that can be mapped to entitities that persist in a database. If one needs to GET a HTML (user-friendly) version of something, then the prevalent answer is to use content negiotation via HTTP header fields. The ultimate goal seems to have only URIs that follow the REST paradigm.
But what is the "correct" way to display web pages that cannot be mapped to an entity but are required anyway?
Perhaps I make an example to clarify what I mean. Assume we have a collection Persons and the entity Person.
Then we have
POST /Persons/ to create a new person in the collection
DELETE /Person/{id}/ to delete the person
PUT /Person/{id}/ to modifiy the person (yes, I know it can also mean to create one)
GET /Persons/ to get the list of all persons
GET /Person/{id}/ to get an individual person
and so on
With respect to the GET operations I generally found the advice to use the Accept and X-Requested-With header fields of the request to create a response that either returns the "bare" person object in a computer-readable respresentation (i.e. JSON, XML, etc.) or that returns a fully-fledged web page for a browser.
But what is about the PUT operation. Ultimately, this operation will send a bare person object (i.e. JSON, XLM) that is going to be created, but before this step I need to collect the data from the user. This means I need some empty web form that is just "eye-candy" for the human user. Of course, I could habe something like GET /newPersonForm/ but it seems that this contradict the REST philosophy, because /newPersonForm/ is an URI that only points to some user interface element.
At the moment I see to options:
Use the same name space for both kind of URIs:
POST /Persons/ --> REST api
DELETE /Person/{id}/ --> REST api
PUT /Persons/{id}/ --> REST api
GET /Persons/ --> REST api or UI (after content negiotation)
GET /Person/{id}/ --> REST api or UI (after content negiotation)
GET /Person/creationForm --> non-REST, pure UI
GET /aboutus --> non-REST, pure UI, additional company information
Make separate name spaces:
/api/... --> contains everything for REST
/ui/... --> contains html web pages
With the first approach I feel that it is somebit "unclean". Although the second approach seems cleaner, I see two problems. Firstly, if one follows this approach cleanly, one gets much double URIs, because one dispense with content negiotation and has an UI web page for every REST function. I have GET /api/Person/{id}/ to return a JSON object and GET /ui/Person/{id} to return a browser version. Secondly, I feel that this approach contradict REST philosophy because search egines and web crawlers cannot understand the structure of the site.
Any recommendations what the best practice is?
First of all, let's get a few misconceptions out of the way.
Anything for which you have semantics identifiable by an URI is a resource.
The HTTP methods don't map to CRUD operations like that. Read this answer for more on that. I recommend you read it before continuing reading this answer. This one is probably going to be helpful too.
There's no such thing as an URI that follows the REST paradigm. The only constraints REST imposes on URIs is that they must identify one and only one resource, and they must be treated as atomic identifiers. The semantics of the URI is irrelevant, although obviously you should design URIs that make sense for the developers and users.
As you already figured out, the correct way to return an user-friendly representation of something is through negotiation via the Accept header. It doesn't matter if it's not something that maps to a database. That's an implementation detail only the server knows, and that's what REST is about. When you retrieve something from a REST API, it doesn't matter if it's coming from the application server, from a cache somewhere, from a static file served by Amazon S3, or even an FTP link. The client should simply follow links, like when you click a link on a webpage and you don't care where the result comes from.
Both options you present are valid, but that has nothing to do with REST. Separating them in api and ui is a nice way to organize things for you, but what really matters to REST is how the client obtains those links. If they are implementing clients by reading those URIs in documentation and filling up values, that's not REST.
Think about it from a web browsing perspective. How do you reach that /newPersonForm html page? You followed a link somewhere else that had a label telling you to click on it to create a new Person. If you are the one clicking, it doesn't matter if it's /newPersonForm or /forms/newperson or simply /persons. REST works in the exact same way.

Correct database structure for message table

I'm trying to write a messaging app using PhoneGap, AngularJS and Firebase. I'm trying to work out what the correct the correct database structure should be given Firebase unusual query methods (1, 2).
I need a messages 'table' where all messages are stored, however the issue is that this is a NoSQL table, so it's quite hard to retrieve data if it's not formatted specifically.
For example, I originally considered something like /messages/{userId} to get all messages for a user, and /messages/{userId}/{partnerId} to get a specific message chain, but I can't do that because it would mean that data has to be duplicated, once for the person sending the message and once for the person receiving.
Can anyone suggest a layout which would work well with Firebase's query structure, and allows:
Retrieval of all messages to/from a user
Retrieval of a specific thread from one user to another
look in this post about data denormalizing . I faced a similar challenge and the solution which worked for me was storing all data under auto ID in specific object and if needed I stored a reference to that data in as many places as required.
Applying this to your problem, if simplified, I would go for something like this:
root/messages/{message_by_auto_id}/{message_body}
root/users/{user_id}/messages_this_user_can_see/{ref_to_message}
so If a user posts a message the app needs to save the message in messages and save the reference to that message to each friend as above.

Database and html DOM id mapping

I am working on a portal, where users can submit and retrieve data from a database via ajax and servlet responses.
My question is how should i not reveal the real ids of the database in the html DOM. To be more spesific, i need to know which is the best way for mapping between "real" and DOMS's ids, and if this should be happening on server or client side.
Thanks!
I think you would like to populate the doms with unique IDs to identify the element in the page. In that case there will be numerous ways.
easy one would be a Fancy value put in the dom like
dom_id = 'itu~#'+(your_id*1001)+'#rand()'
Then when requested you can retrieve your_id with the '#'separated and divide by 1001 .
OR
be more complex you may write any complex function
Happy coding.

RESTful address for image list

I've looked at many SO answers about REST, but the concept is still not clear.
At least, it seemed to me naming(the URL) properly is central to what REST is.
How do I make my address scheme below restful?
(I have list of images, but for each request I present different subset of them)
image_list/recent (all image sorted in descending)
image_list/recent/front/ (to request newer images than a client has. client will provide the latest image id he has)
image_list/popular (sorted in popularity)
image_list/following/ (list of images of users that a client follows)
image_list/user_like/ (list of images a client likes)
how about when you have many operations that you can perform on a resource?
image/upload/
image/delete/
image/like/
image/dislike/
image/hide/
EDIT
This is the solution after looking at answers.
(But I still have doubts and did indicate so)
First set
images/?mode=recent
images/?mode=recent_front
images/?mode=popular
images/?mode=following&user_id=3
images/?mode=like&user_id=3
Isn't it a convention to use images/ for all images even though the all images set keeps changing?
Why can't I just use images/recent then?
Second set
images/ POST (to create)
images/ DELETE
(to delete, ok but I have not seen anyone using `DELETE`. Does anyone use it?)
images/3/like POST (OK there's a `like` DB entity)
images/3/dislike POST (umm but there's no dislike DB entity)
images/3/hide .. (there's no hide entity, it's a merely a field on image)
As I'm sure you know, REST is much more than a naming scheme for URLs.
What's important with your URI naming scheme is that the URI uniquely identifies a particular resource/entity. Quoting directly from the Wiki page:
An important concept in REST is the existence of resources (sources of
specific information), each of which is referenced with a global
identifier (e.g., a URI in HTTP).
In your case, you want your URIs to structured so that they can uniquely identify an image or the collection of all images as a whole. There is more than one way to do this. Some people prefer query strings and others (including myself) prefer including identifiers as part of the URI folder structure. REST doesn't dictate one or the other.
Think about what you need to identify an image--it could be a filename, but if your application is database driven, it's more likely you'd be using an index ID number. You could setup your URI as such:
http://YOURDOMAIN.TLD/API/IMAGE/232423
Where 232423 uniquely identifies the image.
Now on to your second question:
how about when you have many operations that you can perform on a resource?
With REST APIs over HTTP, the action is typically specified by the HTTP method you utilize. GET for retrieving data, POST for updating/inserting data and DELETE for deleting data. It's not common practice to have the URI itself specify the action--as you've done above. Please note, that I'm talking about what's common practice--the principles of REST don't dictate what HTTP methods should be used or the URI naming structure.
Taking your example of likes on an image, you should treat the likes on the page as a resource--a unique entity. There are different actions that you want to do with this entity such as: 1. look up the number of likes on an image, 2. add a new like to the total.
For your REST method to like an image, you could set it up as a POST to a URI like this:
http://YOURDOMAIN.TLD/API/IMAGE/232423/LIKE
Where 232423 is an identifier for the image and LIKE refers to the likes on that particular image.
If you wanted to retrieve the number of likes on the image, use the same URI, but switch the HTTP method to GET.