How to Get Lists for Uri Templates based on other Ids - rest

Lets say I have a couple URI template endpoint for a REST API as such:
"/events" - gives me all events
"/events/{eventId}"
"/events/2234" - gives me the event specified by the eventId
What if I wanted all events by a specific broker. I was thinking maybe this:
"/events/{brokerId}"
e.g.
"events/2345" - gives me all the events for the specific BrokerId
problem is how would the service know if the incoming url is sending in a broker vs. eventId? the /2234 and /2345 are indistinguishable.
I'm wondering how this is handled in REST. Do most people typically do something like:
"events/broker/{brokerId}"
or do they somehow specify what type of Id it is some other way?

I'm not sure about others, but I would probably do something like:
/brokers/{brokerId}/events
For example:
/brokers/2345/events
Of course, you could always do something less rest-ful, such as:
/events?brokerId=2345

Related

Generate unpredictable/unforgeable URL from predictable ID

I have a simple API that return Something for a given ID and it must be used without any kind of authentication, the URL should be permanent and yet I want to avoid as much as possible it to be botted.
The Url is something like this:
https://url/{SomeId}/doSomething
The problem is that this is very predicable and a bot could easily try all the ID and get everything associated to it.
I'm looking for a way to make the URL non predictable like for example:
https://url/{SomeId}/doSomething?Key=SomeVeryLongCryptographicKey
In this way except if you run a supercalculator you shouldn't be able to deduce all the URLs
I know that there is probably a lot of ways to do that, like using a DB which I want to avoid.
I guess I'm looking for a kind a JWT associated to the ID without expiration but maybe there is better solution.
Edit: to give a better example i'm looking to do a bit like did Zoom for permanent invitation Links. They had predictable room Ids and they added a password making it unpredictable lie so:
https://us05web.zoom.us/j/132465789?pwd=SUxIU0pLankyhTRtWmlGbFlNZ21Ndz08
What would be the best/light/"secure" way to achieve that ?
Also I'm using .Net if there is a library doing that, it would be great.
I think your idea of using a JWT makes the most sense. Better to use something standard from a cryptographic point of view, and the JSON format allows for encoding whatever you need to provide to the receiving endpoint (user names, entity names, entity IDs, other things).
There are standard Microsoft libraries for building and validating JWTs, but I prefer the library Jwt.Net (https://www.nuget.org/packages/JWT). It lets you do something like this quite easily:
var token = JwtBuilder()
.WithAlgorithm(new RS256Algorithm(publicKey,privateKey))
.AddClaim("uri", String.Format("https://example.com/api/{0}/{1}", entityName, entityId))
.Encode();
Just add whatever claims you like, and the JWT will then contain what you want to transfer (I've used an example of the URI that you want to give to the entity) and a signature with your private key. You could even just give a URL like https://example.com/from_token/eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1cmkiOiJodHRwczovL2V4YW1wbGUuY29tL2FwaS90ZXN0RW50aXR5LzEyMzQifQ.K2P4wSF6g1Kt-IHMzlklWTV09_MIkoiNHQztSIYOohmOWe7aBfFSQLIKSbdTECj9XPjNNG_AjH9fdjFglkPuYfr2G9rtl2eh5vTjwdM-Uc0X6RkBu0Z2j7KyMKjkaI3zfkIwhtL1mH873xEBtNOGOW18fuBpgnm8zhMAj1oD3PlDW8-fYBrfLb6VK97DGh_DyxapbksgUeHst7cAGg3Nz97InDPtYcWDi6lDuVQsj3t4iaJBRL8IM785Q8xjlHHhzdfcX3xU4IhflyNHHXxP56_8ahNNMOZKWdwgbTSIxEEB98b3naY3XknC-ea7Nc1y4_5fszrYdy3LaQWV43jpaA
and have the handler decode the entity name and ID you want to retrieve directly from the URI while verifying the signature. Decoding with the library is just as easy:
var json = JwtBuilder.Create()
.WithAlgorithm(new RS256Algorithm(_key))
.MustVerifySignature()
.Decode(token);

REST API designing for resource with aggregated property

We are currently trying to come up with a set of REST API that would fit our resource models.
A simplified example of the resource is:
CompanyInfo: {
totalNumberOfEmployees: Number,
employees: [...employees],
}
Employee: {
name: String,
}
In this case, "CompanyInfo" is like a virtual resource that does not exist in DB. It is a short cut for getting all the data related to the Company resource. The idea was to reduce the amount of logic on FE and create more convenient endpoint instead.
Our current endpoint design is:
GET /api/companyInfos/{companyId}/employees
GET,POST,PUT,DELETE /api/companyInfos/{companyId}/employees/{employeeId}
The reason for the extra {companyId} is because these endpoint does not return "Employees", it instead return a "CompanyInfo" that contains "Employees" embedded in the payload.
This is to avoid the aggregated property "totalNumberOfEmployees" not being updated in case sync when we call POST to create a new "Employee"
So my questions are:
Is this the correct approach to the problem of "too many requests" or "too much logic in FE"?
Is it acceptable for the endpoint to return a completely different resource than what its url describe?
Thanks a lot :)
For your Fist question
Is this the correct approach to the problem of "too many requests" or "too much logic in FE"?
yes Sometimes this is how it is suppose to be done. when data sent is small in each request. to many request does not affect the performance so This is how it is suppose to be done .
And Generally it is recommended to write one monolithic Ajax call in front end which will be capable of making any kind of call , By taking callback as parameter, and method , arguments as parameters .
So it will not be to much of logic if you follow this approach . All you have to write is callback for each of Ajax call . How ever sometimes situation may not allow for this Example:if you are using content-type like 'multipart/mixed'
there you have to write another ajax call code
However nowdays most front end has too much of logic based on how interactive website is . So your primary concern should be about look of web site .
For you second question
Is it acceptable for the endpoint to return a completely different resource than what its url describe?
yes . It is acceptable . but it is recommended that client mention all the MIME types which it expects in Accept header and Only those MIME types should be returned by Api.

REST Resource route naming for get and ResourceByID and ResourceByName

I am trying to write 2 Rest GET methods.
Get user by Id
Get user by userName.
I need to know if there is any resource naming convention for this. Both my id and username are strings.
I came up with:
/api/{v}/users/{userid}
/api/{v}/users/username/{username}
However, 2) doesn't seem correct and if I change 2) to /api/{v}/users/{username}, I am mapping to 1) as both id and username are strings. Or is it considered acceptable to use /api/{v}/userbyName/{username}?
How should I name my resource route in case 2) ?
First of all: https://vimeo.com/17785736 (15 minutes which will solve all your questions)
And what is unique? Is the username unique or only the id or both are unique?
There is a simple rule for all that:
/collection/item
However, 2) doesn't seem correct and if I change 2) to /api/{v}/users/{username}, I am mapping to 1) as both id and username are strings.
If your item can be identified with an id and also with an unique username - it doesn't matter if it's the username or the id - simply look for both (of course your backend needs to handle that) and retrieve it.
According to your needs this would be correct:
/api/{v}/users/{userid}
/api/{v}/users/{username}
but I would choose only to use: /api/{v}/users/{userid} and filter by username only with a query parameter (description for that down there below)
Also will I break any rules if I come up with
/api/{v}/userbyName/{username}
Yes - /api/{v}/userbyName/{username} will break the rule about /collection/item because userByName is clearly not a collection it would be a function - but with a real restful thinking api there is no function in the path.
Another way to get the user by name would be using a filter/query paramter - so the ID will be available for the PathParameter and the username only as filter. which than would look like this:
/api/{v}/users/?username={username}
This also don't break any rules - because the query parameter simply filters the whole collection and retrieves only the one where username = username.
How should I name my resource route in case 2) ?
Your 2) will break a rule - so I can't/won't suggest you a way to do it like this.
Have a look at this: https://vimeo.com/17785736 this simple presentation will help you a lot about understanding rest.
Why would you go this way?
Ever had a look at a javascript framework like - let's say ember. (Ember Rest-Adapter). If you follow the idea described up there and maybe also have a look at the json format used by ember and their rest adapter - you can make your frontend developer speed up their process and save a lot of money + time.
By REST you send back links, which can contain URI templates. For example: /api/{v}/users/{userid} in your case, where v and userid are template variables. Since the URI structure does not matter from a client perspective you can use whatever structure you want. Ofc. it is more convenient to use nice and short URIs, because it is easier to write the routing with them.
According to the URI standard the path contains the hierarchical while the query contains the non-hierarchical part of the URI, but this is just a loose constraint, in practice ppl use both one.
/api/{v}/users/name/{username}
/api/{v}/users/name:{username}
/api/{v}/users?name="{username}"
Ofc. you can use a custom convention, for example I use the following:
I don't use plural resource name by collections
I end collection path with slash
I use slash by reducing a collection to sub-collections or individual items
I don't use slash to give the value of a variable in the path, I use colon instead
I use as few variables and as short URI as I can
I use query by reducing a collection to sub-collections especially by defining complex filters with logical operators
So in you case my solution would be
/api/{v}/user/
/api/{v}/user/name:{username}
/api/{v}/user/{userid}
and
/api/{v}/user/?firstName="John"
/api/{v}/user/?firstName="John|Susan"&birthYear="1980-2005"
or
/api/{v}/user/firstName:John/
/api/{v}/user/firstName:John|Susan/birthYear:1980-2005/
etc...
But that's just my own set of constraints.
Each resource should have a unique URI.
GET /users/7
{
"id": 7,
"username": "jsmith",
"country": "USA"
}
Finding the user(s) that satisfy a certain predicate should be done with query parameters.
GET /users?username=jsmith
[
"/users/7"
]

Why use selectors and not a new URI?

I have a doubt, I have a URI that will bring me all user's account from another rest service. Example:
GET /users/21212/account
Now I have the need to bring 3 kinds of different groups of user's account, something like: "low-account", "medium-account" and "high-account".
But the discussion is, how should I enable this on my endpoint ?
GET /users/21212/accounts/low-account
GET /users/21212/accounts/medium-account
GET /users/21212/accounts/high-account
or
GET /users/21212/accounts/1?selector=low-account
GET /users/21212/accounts/1?selector=medium-account
GET /users/21212/accounts/1?selector=high-account
I'm inclinated to follow the first approach, I think is more intuitive and the manutenability of the code will be easily preserved... What do you think is conceptual right/better and why ?
I would choose the following option:
GET /users/12345/accounts?group=low-account
It will return you all accounts that belong to 'low-account' group for user 12345.
I tend to use query params if they represent something like filtering. Also I would recommend you to take a look at HATEOAS principle. Then you will be more flexible with your URIs.

RESTful approach to updating time-related data on resource

So I have the following resource (expressed as a Grails domain class):
class WorkRecord {
...
Date logInTime
Date logOutTime
...
}
Now, I'm trying to create a RESTful approach to log into, or out of work through WorkRecord. What I'm thinking of is by calling something like,
PUT /workrecords/2
sending something like (JSON request)
{... logInTime: <date> ...}
to log in, or change property name to logOutTime to log out. This follows the resource oriented approach (I think). However, I really can't trust the client to send the server correct date every time, so I'd like the server to set the log in/out time itself. But then, I can't figure out how the request body should be like. The alternative I can think of right now is do the same PUT /workrecords/2 to the server with some request like,
{... action: 'logIn' ...}
which doesn't look very RESTful. How do I go about this?