RESTful address for image list - html

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.

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.

GET request in Django

I have a doubt. When is a GET request sent. I mean, I have seen a lot of people using if request.method == 'GET', when they render the form for the first time, but when the form is submitted, they do a `POST' request.
While they explicitly mention when defining the form in html that the method will be 'POST', they don't do the same for 'GET' request which is made when an empty form is requested.
How does django know it's a GET request?
And, why is it done so?
Thanks,
I'm not an expert but I think Django "knows" this because like all things on the Internet it uses the HTTP protocol. There are several HTTP methods. If not specified the default method will always be GET
GET
A GET is usually used to retrieve information. Typically a GET function has no side-effects (this means that data in the database is not changed, that no files in the filesystem are modified, etc.).
Strictly speaking this is not always true, since some webservers log requests (themselves) and thus add an entry to the database that a specific user visited a specific page at a specific timestamp, etc.
A typical GET request is idempotent. This means that there is no difference between doing a query one time, or multiple times (two times, three times, five times, thousand times).
GET queries are therefore typically used to provide static content, as well as pages that contain data about one or more entries, search queries, etc.
POST
POST on the other hand typically ships with data (in the POST parameters), and usually the idea is that something is done with this data that creates a change in the persistent structures of the webserver. For example creating a new entry in some table, or updating the table with the values that are provided. Since these operations are not always idempotent, it can be dangerous if the user refreshes the page in the browser (since that could for example create two orders, instead of the single order the user actually wanted to create).
Therefore in Django a POST request will typically result in some changes to the database, and a redirect as result. This means that the user will typically obtain a new address, and perform a GET request on that page (and that GET is idempotent, hence it will not construct a new order).
PUT, PATCH and DELETE
Besides the popular GET and POST, there are other typical requests a client can make to a webserver. For example PUT, PATCH and DELETE.
PUT
PUT is the twin of a POST request. The main difference is that the URI it hits, specifies what entry to construct or update. PUT is usually an idempotent operation.
This means that if we would for example perform a POST server.com/blog/create to create a blog, PUT will typically look like PUT server.com/blog/123/. So we specify the id in advance. In case the object does not yet exists, a webserver will typically construct one. In case the entity already exists, a new entity will typically be constructed for that URI. So performing the same PUT operation twice, should have no effect.
Note that in case of a PUT request, typically one should specify all fields. The fields that are not specified will typically be filled in with default values (in case such values exist). We thus do not really "update" the entity: we destroy the old entity and create a new one in case that entity already exists.
PATCH
PATCH is a variant of PUT that updates the entity, instead of creating a new one. The fields that are thus missing in a PATCH request, typically remain the same as the values in the "old" entity so to speak.
DELETE
Like the name already suggests, if we perform a DELETE server.com/blog/123/ request, then we will typically remove the corresponding element.
Some servers do not immediately remove the corresponding element. You can see it as scheduling the object for deletion, so sometimes the object is later removed. The DELETE request, thus typically means that you signal the server to eventually remove the entity.
Actually Django is based on HTTP responses-requests. HTTP is fully textuall. So Django parses each request and finds in its header information about what kind of request is it. I may be mistaken in details, but as I understand when server receives request - Django creates it's object request, which contains all the data from HTTP. And then you decide if you need a specific action on GET or POST and you check the type of request with request.method.
P.S. And yes, by default each request is GET.

REST-API database-relationships back-referencing

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!

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.

HTML Hyperlinks using url query strings

Some sites use hyper links like:
www.example.com\index.php?x=test.php
www.example.com\index.php?test.php
www.example.com\index.php?\test.php
instead of simply:
www.example.com\test.php
Are there any advantages of linking to other pages using query strings instead of simple hyperlinks.
When to use them
If the order is irrelevant or if they can be combined in different ways. In many cases like pagination not all query strings are needed to get the desired result. So the are usually always optional.
Advantages
They do not have the encoding issues of named params and are pretty much the way all other web apps also use such volatile params. So it is the de facto standard for web apps.
With query strings the short-routed action names (usually all index actions) don’t pop up anymore as long as you don’t use passed params:
URLs are passed in Referrer headers – if a secure page uses resources, such as javascript, images or analytics services, the URL is passed in the Referrer request header of each embedded request. Sometimes the query string parameters may be delivered to and stored by third party sites.
It can be useful wile posting a data on a webservice, or u can even pass a session ID along with the URL in query parameters provided they are encoded.
The type of notation that you mentioned earlier is aided by the concept called url rewriting.
Many php frameworks these days use MVC architecture for code organisation into three tiers. This enhance code scalability and web application's security.
All the requests to the server are directed to index.php where they are resolved to load a particular action, thus hiding the background layout of the code.
Here test.php can be present either at the root or inside some other folder depending upon the location specified to the routing algorithms that are called in index.php