Get a resource in rest API based on an alternative identificator - rest

What would be a rest API convention to get a resource based on a different identificator?
For example
GET
/resource/{id}
GET
/resource/{guid}
Since this could be considered as a dupliate resource and setting routes for this could be a problem, what is an alternative then would follow rest API guidelines?
Maybe
/resources/?guid={guid}
or
/resources/guid/{guid}
or something else?

Short answer
You could use both /resource/{id} and /resource/{guid}. Many frameworks support regular expressions for matching path parameter values.
Long answer
REST is an architectural style and not a cookbook for designing URIs (see notes below). It doesn't enforce any URI design and it's totally up to you to pick the URIs that better identify your resources.
What you should keep in mind is: it's perfectly fine to have multiple mappings for the same entity. And each mapping is a resource, according to Fielding's dissertation:
A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time.
With that being said, if you are supporting DELETE, it's important to mention how it's supposed to work:
4.3.5. DELETE
The DELETE method requests that the origin server remove the association between the target resource and its current functionality. In effect, this method is similar to the rm command in UNIX: it expresses a deletion operation on the URI mapping of the origin server rather than an expectation that the previously associated information be deleted. [...]
Note 1: The URI syntax is defined in the RFC 3986. As general rule, the path is organized in hierarchical form (with segments separated by /) and can contain non-hierarchical data in the query component (starting with ?).
Note 2: The REST architectural style is described in the chapter 5 of Roy T. Fielding's dissertation and it defines a set of constraints that must be followed by the applications that follow such architecture. However it says nothing about what the URIs must be like.
Note 3: The examples of a popular article written by Martin Fowler explaining a model defined by Leonard Richardson suggest a URI structure that looks friendly and easy to read.

I wouldn't normally duplicate an endpoint. The question would be:
why does one client have an id while another has a guid?
what design choice allowed that to happen?
I would leave it as a single resource endpoint:
GET
/resource/{id}
so clients who access resources via their id will use the above endpoint. I'd allow clients who access resources via their guid to exchange what they have (guid) for what they need (id):
GET
/id/{guid}
The above returns a resource id for the given resource guid. The client can then call the main resource endpoint with the id they have just received:
GET
/resource/{id}
but ultimately I'd look into why some clients use a guid rather than an id and change that so all clients access the API in the same way.

Related

Sub-resource creation url

Lets assume we have some main-resource and a related sub-resource with 1-n relation;
User of the API can:
list main-resources so GET /main-resources endpoint.
list sub-resources so GET /sub-resources endpoint.
list sub-resources of a main-resource so one or both of;
GET /main-resources/{main-id}/sub-resources
GET /sub-resouces?main={main-id}
create a sub-resource under a main-resource
POST /main-resource/{main-id}/sub-resouces: Which has the benefit of hierarchy, but in order to support this one needs to provide another set of endpoints(list, create, update, delete).
POST /sub-resouces?main={main-id}: Which has the benefit of having embedded id inside URL. A middleware can handle and inject provided values into request itself.
create a sub-resource with all parameters in body POST /sub-resources
Is providing a URI with main={main-id} query parameter embedded a good way to solve this or should I go with the route of hierarchical URI?
In a true REST environment the spelling of URIs is not of importance as long as the characters used in the URI adhere to the URI specification. While RFC 3986 states that
The path component contains data, usually organized in hierarchical form, that, along with data in the non-hierarchical query component (Section 3.4), serves to identify a resource within the scope of the URI's scheme and naming authority (if any). The path is terminated by the first question mark ("?") and number sign ("#") character, or by the end of the URI. (Source)
it does not state that a URI has to have a hierarchical structure assigned to it. A URI as a whole is a pointer to a resource and as such a combination of various URIs may give the impression of some hierarchy involved. The actual information of whether URIs have some hierarchical structure to it should though stem from link relations that are attached to URIs. These can be registered names like up, fist, last, next, prev and the like or Web linking extensions such as https://acme.org/rel/parent which acts more like a predicate in a Semantic Web relation basically stating that the URI at hand is a parent to the current resource. Don't confuse rel-URIs for real URIs though. Such rel-URIs do not necessarily need to point to an actual resource or even to a documentation. Such link relation extensions though my be defined by media-types or certain profiles.
In a perfect world the URI though is only used to send the request to the actual server. A client won't parse or try to extract some knowledge off an URI as it will use accompanying link relation names to determine whether the URI is of relevance to the task at hand or not. REST is full of such "indirection" mechanism in order to help decoupling clients from servers.
I.e. what is the difference between a URI like https://acme.org/api/users/1 and https://acme.org/api/3f067d90-8b55-4b60-befc-1ce124b4e080? Developers in the first case might be tempted to create a user object representing the data returned by the URI invoked. Over time the response format might break as stuff is renamed, removed and replaced by other stuff. This is what Fielding called typed resources which REST shouldn't have.
The second URI doesn't give you a clue on what content it returns, and you might start questioning on what benefit it brings then. While you might not be aware of what actual content the service returns for such URIs, you know at least that your client is able to process the data somehow as otherwise the service would have responded with a 406 Not Acceptable response. So, content-type negotiation ensures that your client will with high certainty receive data it is able to process. Maintaining interoperability in a domain that is likely to change over time is one of RESTs strong benefits and selling points. Depending on the capabilities of your client and the service, you might receive a tailored response-format, which is only applicable to that particular service, or receive a more general-purpose one, like HTML i.e.. Your client basically needs a mapping to translate the received representation format into something your application then can use. As mentioned, REST is probably all about introducing indirections for the purpose of decoupling clients from servers. The benefit for going this indirection however is that once you have it working it will work with responses issued not only from that server but for any other service that also supports returning that media type format. And just think a minute what options your client has when it supports a couple of general-purpose formats. It then can basically communicate and interoperate with various other services in that ecosystem without a need for you touching it. This is how browsers operate on the Web for decades now.
This is exactly why I think that this phrase of Fielding is probably one of the most important ones but also the one that is ignored and or misinterpreted by most in the domain of REST:
A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types. (Source)
So, in a true REST environment the form of the URI is unimportant as clients rely on other mechanisms to determine whether to use that URI or not. Even for so called "REST APIs" that do not really care about the true meaning of REST and treat it more like old-school RPC the question at hands is probably very opinionated and there probably isn't that one fits all solution. If your framework supports injecting stuff based on the presence of certain query parameters, use that. If you prefer the more hierarchical structure of URIs, go for those. There isn't a right or wrong in such cases.
According to the URI standard when you have a hierarchical relationship between resources, then better to add it to the path instead of the query. https://datatracker.ietf.org/doc/html/rfc3986#page-22 Sometimes it is better to describe the relation itself, not just the sub-resource, but that happens only if the sub-resource can belong to multiple main resources, which is n:m relationship.

Is resource will be always on servers in REST?

Using HTTP POST method/AnyMethod If a client is sending some information like name, number etc in a representation to server and server is storing it to DB then here name and number is called a resource?
or we are creating a resource in server with the information what client gave?
then client will not have a resource at any time?
Let's take a theoretical look at this:
resource = the intended conceptual target of a hypertext reference
[...]
The key abstraction of information in REST is a resource. Any
information that can be named can be a resource: a document or image,
a temporal service (e.g. "today's weather in Los Angeles"), a
collection of other resources, a non-virtual object (e.g. a person),
and so on. In other words, any concept that might be the target of an
author's hypertext reference must fit within the definition of a
resource. A resource is a conceptual mapping to a set of entities, not
the entity that corresponds to the mapping at any particular point in
time.
Source: Fielding, Roy Thomas. Architectural Styles and the Design of Network-based Software Architectures. Doctoral dissertation, University of California, Irvine, 2000 as referenced in RFC 7231.
In a brief interpretation that means that the resource is never any particular data but rather a mapping. Let's put it into something tangible:
GET /members
-> A resource called members (= set of entities) consisting out of username, e-mail address.
Members is considered a resource because it describes what the set of entities represent and because I've decided so.
To answer your questions:
> name and number is called a resource?
Depends on the context. Are you storing the name and number alone and independent from each other? Then they are resources, if they are part of something else, the resource would be the thing the two values describe (e.g. contact information).
Since the concept is abstract, you may even define three resources here: names, contact information and numbers. As it said, any information can be a resource, but that's not a must. So you are free to decide what you call a resource and what not.
> or we are creating a resource in server with the information what
> client gave?
No. We are creating an entity within a resource. The resource was defined by you earlier.
> then client will not have a resource at any time?
To be frank, I am sitting over this question for quite some time now - the dissertation doesn't state something specific but from interpreting and understanding the abstract concept, I'd say no. The server always holds the state of a resource, the client just gets or modifies it, but never provides any resource itself.
Related Questions:
What are REST resources?
What is the difference between resource and resource representation in REST?

REST API - what is the proper way for sending ID on http request?

Let's say I have this URI endpoint:
:GET /v1/permissions
Which select all of the permissions on version 1.
One also can request this:
:GET /permissions
Which will request all permissions by the latest default version.
Now I want to select all of the permissions from a specific user.
I want to know what is the proper and respectable way to send the identifier of the user - in the URI endpoint OR in the http request headers OR as a GET param.
For example:
Method 1:
:GET /v1/groups/:id/permissions
Method 1.1:
:GET /v1/:id/permissions
Method 2:
:GET /v1/permissions,
"If-Match": "[REPLACE_ID_HERE]" (header)
Method 3:
:GET /v1/permissions/?groups=REPLACE_ID_HERE
All of them will work.
But which is the proper way?
But which is the proper way?
It's a common misconception.
The REST architectural style doesn't enforce any URI design (see notes below). It's totally up to you to pick the URIs that better identify your resources.
The URI syntax is defined in the RFC 3986. As general rule, the path is organized in hierarchical form (with segments separated by /) and can contain non-hierarchical data in the query component (starting with ?).
These approaches seem to be fine to identify the permissions of a particular group:
/v1/groups/:id/permissions
/v1/permissions?groups=id
The "right" approach would depend on your needs and how you model your API. In the first approach, the hierarchy expresses that the permissions belong to a particular group (the permissions depend on a group to exist). The second approach is more like filtering a collection of permissions by group.
Note 1: The REST architectural style is described in the chapter 5 of Roy T. Fielding's dissertation and it defines a set of constraints that must be followed by the applications that follow such architecture. However it says nothing about what the URIs must be like.
Note 2: The examples of a popular article written by Martin Fowler explaining a model defined by Leonard Richardson suggest a URI structure that looks friendly and easy to read.
Two points upfront:
There is no official REST specification issued by a central authority. The entire paradigm originates from a rather slim (yet ingenious) technical outline written by Roy Fielding in the year 2000.
However, there are several good books on the matter and hundreds of thousands of implementations that have led to a firm industry standard.
One of those standards is that REST Urls are specific to resources and ids embedded in those Urls reference resources of the same type. Thus GET /groups/:groupdId is orthodox (a standard implementation that matches the expectations of most programmers) whereas GET /groups/:permissionId is not.
Coming back to the 4 alternatives you contemplate:
Method 1:
:GET /v1/groups/:id/permissions
Is orthodox, since the resource managed by the endpoint is of type Group and :id is a Group id.
Method 1.1:
:GET /v1/:id/permissions
Is unorthodox since there is no indication of what resource type the Url refers to.
Method 2:
:GET /v1/permissions,
"If-Match": "[REPLACE_ID_HERE]" (header)
Is unorthodox, since resource ids are expected to be passed as part of the Url.
Method 3:
:GET /v1/permissions/?groups=REPLACE_ID_HERE
Is orthodox, since here the resource is Permission and the groupId is applied as a filter, for which request parameters are the adequate means.
The most common way of designing a REST API is following the resources (and - or sub-resources) structure. i.e. api url will start with your resource name followed by a unique ID for the resource in case of Single resource GET, PUT(update) or DELETE.
Ex :
1. /users/$unique_user_id - HTTP GET - Fetches the single user detail.
/users/$unique_user_id - HTTP PUT - updates the user details identified by the id with the related data.
/users/$unique_user_id - HTTP DELETE - Deletes the user identified by the ID.
If your case handles a well established relation between 2 resources you can handle them as sub-resources of the parent.
Ex :
/users/$user_id/permissions
/groups/$group_id/permissions
This model will suit if you won’t get a requirement to fetch permissions for multiple resources(kind of filtering)
Ex :
/permissions?group_ids=1,2,3
/permissions?user_ids=4,5,6
As per REST spec, you first need to determine what is the base resource you are requesting for. The name of the resource comes first in the URI. In your case, it's the Permission. Hence the URI will begin with permission, with an optional version prefix (as the whole API is versioned)
Following the resource name, you need to mention either a specific resource or a query parameters to get a broad list. Now here you have two options, based on what you are retrieving.
1) permission for a person: In this case, you need to put query param as the api itself won't be able to guess what is the id for. Hence it will be permissions/?personId=123
2) permission detail of a particular permission: Used when you have a list of permissions pre fetched, maybe as result of above api. In this case the identifier will belong to the resource itself, hence it will be specified as the resource identifier as permissions/5e55 where 5e55 is the primary key of the specified permission of whom detail is being sought after.
The major complexity in such design is properly identify the resource primary identifier and secondary identifier...
The primary identifier is put directly in type 2 and secondary is specified as query param.
All said, technically nothing will stop the either request style from working as long as you provide the parsing logic of the URI. REST just says that URI should be able to identify resource properly and does not impose an implementation requirement.

REST URL naming convention /users/{id}/cars/{carId} vs /cars/{carId}?

I have a simple model
Each Use can have multiple cars
Now when I decide to name the related REST URL naming for Cars service
Initially I suggest to be as the following
GET /cars/{carId}
But when I read about best practices in REST Resource Identifier (URI) Naming
I found that its better to put parent information in the URI as the following
GET /users/{userId}/cars/{carId}
Any one explain to us
Why the second one is the recommended naming
However, I need ONLY a carId to fetch the car
And no need to userId
REST does not care what spelling you use for your identifiers.
/a4e199c3-ea64-4249-96aa-abb71d860a55
Is a perfectly satisfactory REST identifier.
Guidelines such as the one that you linked should be understood a style guide; human readable identifiers that adhere to local spelling conventions are goodness for exactly the same reasons as human readable variable names that adhere to local spelling conventions.
Some URI guidelines advocate convention over configuration -- put broadly, you can simplify your implementations if you choose identifier spellings that allow your framework to deduce where things should live.
when I read about best practices in REST Resource Identifier (URI) Naming
I found that its better to put parent information in the URI
Maybe; part of the problem may be confusing resources with entities. It's an entirely normal thing for one single row in your database to contribute to the representation of many different resources, each of which has its own identifier
/users/:userId/cars/:carId
/cars/:carId
In HTTP, you might even send to the client information that the representation of one of these resources is equivalent to another (see RFC 7231).
The good news: hypermedia clients can deal this sort of thing automatically, because they have built into them awareness of the semantics of links; web aware hypermedia clients (for instance: browsers) will also be able to do the right thing with the meta data.
The bad news: you probably aren't using hypermedia types as your representations, so you won't see those benefits.
IMO, it depends more on the context. Consider the following example:
GET /users/user001/cars/car001
Response:
owner-name, car-license-no, purchase-date, first-owner
Here the response is - car details, specific to a user
GET /cars/car001
Response:
car-model-no, manufacturer, displacement, car-type
Here the response is - car details, specific to the car

RESTful POSTS, do you POST objects to the singular or plural Uri?

Which one of these URIs would be more 'fit' for receiving POSTs (adding product(s))? Are there any best practices available or is it just personal preference?
/product/ (singular)
or
/products/ (plural)
Currently we use /products/?query=blah for searching and /product/{productId}/ for GETs PUTs & DELETEs of a single product.
Since POST is an "append" operation, it might be more Englishy to POST to /products, as you'd be appending a new product to the existing list of products.
As long as you've standardized on something within your API, I think that's good enough.
Since REST APIs should be hypertext-driven, the URI is relatively inconsequential anyway. Clients should be pulling URIs from returned documents and using those in subsequent requests; typically applications and people aren't going to need to guess or visually interpret URIs, since the application will be explicitly instructing clients what resources and URIs are available.
Typically you use POST to create a resource when you don't know the identifier of the resource in advance, and PUT when you do. So you'd POST to /products, or PUT to /products/{new-id}.
With both of these you'll return 201 Created, and with the POST additionally return a Location header containing the URL of the newly created resource (assuming it was successfully created).
In RESTful design, there are a few patterns around creating new resources. The pattern that you choose largely depends on who is responsible for choosing the URL for the newly created resource.
If the client is responsible for choosing the URL, then the client should PUT to the URL for the resource. In contrast, if the server is responsible for the URL for the resource then the client should POST to a "factory" resource. Typically the factory resource is the parent resource of the resource being created and is usually a collection which is pluralized.
So, in your case I would recommend using /products
You POST or GET a single thing: a single PRODUCT.
Sometimes you GET with no specific product (or with query criteria). But you still say it in the singular.
You rarely work plural forms of names. If you have a collection (a Catalog of products), it's one Catalog.
I would only post to the singular /product. It's just too easy to mix up the two URL-s and get confused or make mistakes.
As many said, you can probably choose any style you like as long as you are consistent, however I'd like to point out some arguments on both sides; I'm personally biased towards singular
In favor of plural resource names:
simplicity of the URL scheme as you know the resource name is always at plural
many consider this convention similar to how databases tables are addressed and consider this an advantage
seems to be more widely adopted
In favor of singular resource names (this doesn't exclude plurals when working on multiple resources)
the URL scheme is more complex but you gain more expressivity
you always know when you are dealing with one or more resources based on the resource name, as opposed to check whether the resource has an additional Id path component
plural is sometimes harder for non-native speakers (when is not simply an "s")
the URL is longer
the "s" seems to be a redundant from a programmers' standpoint
is just awkward to consider the path parameter as a sub-resource of the collection as opposed to consider it for what it is: simply an ID of the resource it identifies
you can apply the filtering parameters only where they are needed (endpoint with plural resource name)
you could use the same url for all of them and use the MessageContext to determine what type of action the caller of the web service wanted to perform.
No language was specified but in Java you can do something like this.
WebServiceContext ws_ctx;
MessageContext ctx = ws_ctx.getMessageContext();
String action = (String)ctx.get(MessageContext.HTTP_REQUEST_METHOD);
if(action.equals("GET")
// do something
else if(action.equals("POST")
// do something
That way you can check the type of request that was sent to the web service and perform the appropriate action based upon the request method.