How to create relationships in a RESTful API - api

I have 2 tables, User table and User_token table, they are one to one/none relatonship, not sure how to create this RESTful API.
i prefer to setup
# to get user attributes
GET /users/123
# to get user's token
GET /users/123/token
or should i create
# to get user attributes and token by JOIN the table
GET /users/123
the argument we have here, if we are doing the first setup, which i like it, it takes thousands of API requests compare to second one

that is depend you requirement.
for example if you need User Attributes and Token every time than
# to get user attributes and token by JOIN the table
GET /users/123
is better.
other wise another approach is good to get required data when needed.

REST has nothing to do with your database structure.
Your resources can contain properties or sub-resources. Every resource has at least one resource identifier (URL).
So in your case the GET /users/123 is a valid solution.

Related

How to structure REST resource hierarchy?

I'm new to server side web development and recently I've been reading a lot about implementing RESTful API's. One aspect of REST API's that I'm still stuck on is how to go about structuring the URI hierarchy that identifies resources that the client can interact with. Specifically I'm stuck on deciding how detailed to make the hierarchy and what to do in the case of resources being composed of other resource types.
Here's an example that hopefully will show what I mean. Imagine we have a web service that lets users buy products from other users. So in this simple case, there are two top level resources users and products. Here's how I began to structure the URI hierarchy,
For users:
/users
/{id}
/location
/about
/name
/seller_rating
/bought
/sold
For products:
/products
/{id}
/name
/category
/description
/keywords
/buyer
/seller
In both of these cases objects in each hierarchy reference a subset of the objects in the other hierarchy. For example /users/{id}/bought is a list of the products that some user has bought, which is a subset of /products. Also, /products/{id}/seller references the user that sold a specific product.
Since these URI's reference other objects, or subsets of other objects, should the API support things like this: /users/{id}/bought/id/description and /products/{id}/buyer/location? Because if those types of URI's are supported, what's to stop something like this /users/{id}/bought/{id}/buyer/bought/{id}/seller/name, or something equally convoluted? Also, in this case, how would you handle routing since the router in the server would have to interpret URI's of arbitrary length?
The goal is to build convenient resource identifiers, don't try to cross-reference everything. You don't have to repeat your database relations in URL representation :)
Links like /product/{id}/buyer should never exist, because there already is identifier for that resource: /user/{id}
Although it's ok to have /product/{id}/buyers-list because list of buyers is a property of product that does not exist in other contexts.
You should think of it in a CRUD fashion, where each entity supports Create, Read, Update, and Delete (typically using GET, POST, PUT, and DELETE HTTP verbs respectively).
This means that your endpoints will typically only go one level deep. For instance
Users
GET /users - Return a list of all users (you may not want to make this publically available)
GET /users/:id - Return the user with that id
POST /users - Create a new user. Return a 201 Status Code and the newly created id (if you want)
PUT /users/:id - Update the user with that id
DELETE /users/:id - Delete the user with that id
Going into more detail, such as /users/:id/about is likely not necessary. While it may work, it may be getting slightly overspecific.
Perhaps in your case you could add in:
GET /users/:id/bought - Array of products that the user bought
GET /users/:id/sold - Array of products that the user sold
where you could return a list of id's (which can be fetched through the products API), or you could populate the Products before sending them back if you wish. If you do choose to populate them, you probably should not then populate users referenced by each product. This will lead to circular includes and is wrong.
And for Products, in your sitation I would use:
GET /products- Return a list of all products
GET /products/:id - Return the products with that id
POST /products- Create a new product. Return a 201 Status Code and the newly created id (if you want)
PUT /products/:id - Update the product with that id
DELETE /products/:id - Delete the product with that id
GET /products/:id/buyers - Array of who bought the product
GET /products/:id/sellers - Array of everyone selling the product

How to design RESTful URL with many input parameters

I am working to create a Java based RESTful API that uses Spring MVC.
Now for some of the API endpoints-- multiple different parameters are required... I am not talking about a list of values-- more like parameter1, parameter2, parameter3, parameter4 and so on-- where all the 4 (or more) parameters are of different data types as well.
How do I design the API endpoint URL for the above scenario, eg for 4 separate input parameters? Is there any recommended way/best practice for doing this? Or do I simply concatenate the 4 values, with ach pair of values separated by a delimiter like "/"?
EDIT from user comment:
Example: I have to retrieve a custom object(a 'file') based on 4 input parameters--(Integer) userid, (Integer) fileid, (String) type, and (String) usertype. Should I simply create a REST Endpoint like "getfile/{userid}/{fileid}/{type}/{usertype}-- or is there a better (or recommended way) to construct such REST endpoints?
In REST start by thinking about the resource and coming up with immutable permalinks (doesn't change)to identify that resource.
So, in your example (in comment), you said you want to retrieve a file resource for a user and type (file type or user type?)
So, start with just enough information to identify the resource. If the id is unique, then this is enough to identify the resource regardless of the user who owns the file:
/files/{fileId}
That's also important as the url if a file could change owners - remember we want to identify the resource with just the components needed so it can be a permalink.
You could also list the files for a specific user:
/users/{userId}/files/
The response would contain a list of files and each of those items in the list would contain links to the files (/files/{fileId})
If for some reason the file id is not unique but is unique only in the context of a user (files don't change owners and id increments within a user - wierd) then you would need these components to identify the resource:
/users/{userId}/files/{fileId}
Also note the order based on the description. In that wierd case, we said the files are logically contained and IDed by the user and that's also the containment in the url structure.
Hope that helps.
A GET request to file/{usertype}/{user}/{type}/{fileid} sounds good

What exactly is the session_hash?

I have a question regarding one of the shopify data elements.
During the web hook stage, I receive the orders data.
Inside this data, under the "client_details" section, there is a field called "session_hash".
I was wondering what kind of data is it (e.g. the session_id), and which hash function you use to generate it.
The session_hash variable is a secure hash of the session id we use to identify individual customers (as you correctly surmise).
You can use it to identify a particular user session, but that's about it. You can't deconstruct the hash to obtain the original session id for obvious security reasons.

Suborganizations and Unique id

I can succesfully authenticate my application with ApacheDS
But now i use only one domain.
I want to add subdomains or sub organizations under root domain.
For example a root organization as
dc=example,dc=com
and sub organizations dc=x
another sub organization dc=y
Now i can authenticate users using uid attribute
like:
user-search-filter="(uid={0})"
i use login name like user1, without an # extension
But i want to have suborganizations and i want to use user1#x.example.com
Is it possible and how?
My application is a spring application but i think subject is independent from my application side.
The attribute defined in the LDAP standards track for email addresses is mail, rfc822mailbox, or 0.9.2342.19200300.100.1.3 as defined in RFC4524. Perhaps your filter should be an attribute assertion using one of those types, for example, user-search-filter="mail={0}".
I am not sure what is meant by "manually". LDAP does not have a concept of organizations, only entries that might belong to an organization. These entries might have a mail attribute if the entry belongs to an objectClass that allows or requires the mail attribute. In other words, if your filter is mail={0} (which might become mail=user1#x.example.com), then a search using that filter (given the appropriate base object and scope) will return all entries that have a mail attribute with the value user1#x.example.com irrespective of where that user is located and irrespective of the value of the uid attribute.
If the users in an organization can identified some other way, perhaps by organization or other attribute, then the filter could be:
(&(uid={0})(o=x))
or
(&(uid={0})(o=y))
One way or another, the users' entry must be identifiable by the contents of the entry. The primary key in an LDAP database is the distinguished name (uid=abc,dc=x,dc=example,dc=com) but attributes in the entry can be used to tighten the filter. Some alternatives are:
use unique identifiers (all uid or mail values are unique in the database, therefore, only one is ever returned to a search request)
use an attribute to identify users in an organization (like o in the example filters above)
use a dynamic group to generate a list of users in an organization.
consider using an extensible match filter to make values in the distinguished names be part of the filtering process
see also
using ldapsearch - the article is about the ldapsearch command line tool, but the concepts are useful when constructing search requests
mastering search filters

Organising resource (URI) in REST API

Scenario 1
In my web application say for there is a screen for adding an employee to system. As soon as user tabs after entering name of the employee, it generates the employee code automatically (which is the next field) based on some logic and already present records in the database.
Now I want to expose rest API for this application so that third party devs can build on top of it. So, I will have a resource called as /Employee which will respond for GET, PUT and DELETE verbs. But when a client needs to autofill the code, which is a GET operation, it will be on what resource? Should I make a new resource /EmployeeCodeFor/{Name} or I should get it on /Employee/{Name}/GenerateCode? If I go with /Employee/{Name}/GenerateCode then what about my resource to GET, PUT and DELETE for Employee i.e. actually /Employee/{Id}?
Scenario 2
Here lets take the case of a stackoverflow post. So lets say the resource would be /Post/{Id}. In the same way as in the previous example it lists me possible duplicate question as soon as I tab out of the Title field.
Again on what URL I should get those possible duplicates?
I can't think of more scenarios just now. But many such kind of scenarios may come up in real life application development. How to implement them in RESTful way?
Update on scenario 1
Code and Id are two different fields. Id is primary key, code can be duplicate across departments just to illustrate. Also to generate a code, name should be provided first. So, if user types a name "FirstName LastName" then server might generate FL003 as code assuming that there are already two more employees with firstname starting from F and lastname starting from L in the said department. Department can be identified based on the logged in user.
One way to allow the server an opportunity to pre-fill a bunch of elements in a new resource is to do
POST /Employees
{with empty body}
=>
201 Created
Location: http://example.org/employee/3443
<Employee Id="3443">
<Code>E1001</Code>
<FirstName></FirstName>
<LastName></LastName>
</Employee>
This gives the server one chance to provide default values. If you are looking for a more interactive way for the server to provide feedback during the input, I have another approach but it will take quite a bit more explaining.
Scenario 1
Let say your employee code is a unique identifier. In this case, to get it, you would allow the user to complete any field for the new employee and then make a POST. The server would generate the code and respond to the POST with a link to /Employee/{generated_code} which is the record for your newly created employee.
A GET on /Employee would return a list of all employees. A GET on /Employee/{a_code} will give you the employee detail.
Scenario 2
You could have some kind of query on the /Post collection like /Post?title_like={question_title}. A GET /Post?title_like=REST How to would return you a list of all questions containing "REST How to".