Search This Blog

Sunday, February 7, 2016

SharePoint 2013 REST Services Architecture

Developers can interact remotely with SharePoint 2013 by way of REST services introduced in SharePoint 2013. SharePoint data and objects can be accessed using any technology that supports REST web requests like the ones shown in the picture below. This ability of SharePoint 2013 opens the boundaries of integration and collaboration with other REST based platforms and devices.

REST service architecture

As the REST service architecture in the preceding figure shows, a HTTP request using the OData protocol is sent to SharePoint and your application will receive the response in JSON or ATOM format that your client application needs to parse and utilize. The HTTP request is handled by the "client.svc" web service in SharePoint 2013. The "client.svc" web service internally calls the server object model that retrieves data from the SharePoint content database as shown below. SharePoint Apps are built using these architectural concepts.

server object model call

For example: If you want to retrieve a SharePoint List by its Title then you can create a request as follows:
http://server/site/_api/lists/getbytitle('ListName')

A concrete example:
http://win-4f44sec6iug:34480/sites/ts/_api/lists/getbytitle('ProductList')

In my case the response I receive is as follows:

display feed in IE

Oops!! So IE cannot display the feed;  but I have received the feed from SharePoint. So I right-click and do a view source. I see the entire XML is being sent by SharePoint. To see the XML in IE 10 you need to use the following procedure:
  • "Tools" > "Internet Options"
  • Select the "Content" Tab
  • Under Feeds and Web Slices, select "Settings"

    Feeds and Web Slices
  • Under Advanced section untick "Turn on Feed reading view". Refresh the request; you will see the details in XML format, something as in the following:

    XML format
The following figure (from the MSDN documentation) shows the general syntax structure of SharePoint REST URIs. (Please refer to http://msdn.microsoft.com/en-US/library/office/dn292556.aspx for more details.) The following is the SharePoint REST URI syntax structure.

REST URI syntax structure

The following are some special cases that deviate from this syntax structure:
  • Methods that require complex types as parameters.
  • If the corresponding client object model method requires that complex types be passed as parameters.
  • Static methods and properties.

Understanding Rest API


I don’t want to be negative, but you can do much more with CSOM, which remains my first option in any SharePoint 2013 project; in my opinion, the REST implementation of SharePoint 2013 is only interesting for CRUD operation from LAMP /IOS/Android platforms.
BCS & managed taxonomy data cannot be consumed from REST, we can use the CAML syntax in CSOM (join manipulation is more flexible), and we can batch commands in CSOM.
Step2.Installing the prerequisites.
Install the site template provided here, create a web site based on it and take a look at the generated lists: we have a list Suppliers, Products and Countries; a Product can be provided by a supplier, a supplier is from one country: this logic is provided by lookup field between the 3 lists.
Step3.Fetching list information
We can fetch list items in SharePoint by referencing a list via its Id or its name. Of course the id is not subject to changes, so we recommend the id; however do never forget that url have a limitation of 256 characters in http and this alone can force you to move to CSOM instead of staying with REST.
Now type following url in the browser (replace ‘litware’ with your web site name)
Check the returned information: here you only get information about the list itself, not its data; one of the information you will get is the list id:
clip_image002
So grab the id and, in the browser, type
and you will get exactly the same information. However, for the sake of clarity we will stick to the list name.
Step4.Fetching list items
To fetch list items, just append /items() to the previous url :
Type
and you get:
clip_image001
Where each <enty> is a list item (here a Product). Each item features an entry element (in our case a Product) where you will find a <m:properties> element where most column value are stored  and associated with their type (an EntitydataModel type, like Edm.Double, Edm.Int32, etc… It looks like when the column type is a line of text, the type is not provided).Actually the REST models the data exposed through the data service using a model called the Entity Data Model (EDM), an Entity-Relationship derivative.The ADO.NET Entity Framework is used to expose it. This is an opportunity for third party tooling.
In figure, we can clearly find the product BMW 320 (column title) and its associated Price (30000) defined with the Edm.Double type.
clip_image002
However columns like Created By and Modified By are represented by <d:AuthorId> and <d:EditorId> and unfortunately the corresponding people cannot be retrieved. This is a first limitation to take into account with the REST api.
You will notice that the returned Xml fragment provides useful information regarding which url to use to reach each field, or list item, etc…and moreover  the list guid is referenced almost everywhere as illustrated in the next picture : for instance the first item is referenced as
Web/Lists(guid’9e7934bd-65ec-482c-8d68-b8decc431177′)/Items(1)
But the html representation of the field can also be returned (this can be extrêmely usefull in html clients)
Web/Lists(guid’9e7934bd-65ec-482c-8d68-b8decc431177′)/Items(1)/FieldValuesAsHtml
clip_image004
Step 5.Retrieving specific column values
Use $select : for instance For instance, if we just want to get the Title and the price from the products list
clip_image002[6]
You will notice that even if oData is not case sensitive, the fields names are case sensitive.
Also, the column name you have to specify are internal names, not display name even if you rename them with the SharePoint GUI, your query will still work.
If you don’t specify $select, you will get all columns but there are a few exception like when you try to fetch resource intensive columns: ex effectivebasepermission column is not returned by default, but you will get it if you type
Step 6.Filtering
To filter items, we have to use the $filter operator
For instance, to retrieve Products where Price is > 30000
Step 7. Joins
We can easily fetch data from 2 lists linked together by a lookup field; for instance each product has  a supplier and there is a lookup from the Products list pointing to the Suppliers product.
If we type this:
we can notice in the next picture, that the supplier_id is returned :
image
For instance to retrieve the supplier title (from the Products list) of each product (defined in the Products lists) we have to provide the Supplier column name (in my case the column name is ‘Supplier_’) and use the $expand operator like this : (this was first described by Andrew Connel in this post)
To filter on the supplier title:
At the time of this writing I cannot see how to grab another field like ‘CompanyType’ in the Suppliers list; or even do a second lookup to the country list.
Step8. Sorting
Just use Orderby:
We can also sort on multiple columns:
returns Acura before BMW (same price).
Step9.Join and taxonomy
I haven’t be able to retriev taxonmy datadoesn’t work even if we try to have a join with  the taxonomyhiddenlist (the metadata are cached in this hidden list, at the site collection level).

Step10.Using the Search API
image
Step 11. Using the User Profile REST API
image

 Example Of Rest Api


http://ngo.com/_api/lists/getByTitle(?''?)/items?$skip=2&$top=2
http://ngo.com/_api/lists/getByTitle('lst_BreatheIn_Desc')/items/?$skip=2&$top=2&$select=Title

http://ngo.com/_api/lists/getByTitle('lst_BreatheIn_Desc')/items?$skiptoken=Paged=TRUE&p_ID=8&$skip=2&$top=2&$select=Title

http://ngo.com/_api/lists/getByTitle('smgDBMakePost')/items?$skiptoken=Paged=TRUE&p_ID=8&$top=2&$select=ParentItemID

http://ngo.com/_api/lists/getByTitle('lst_BreatheIn_Desc')/items?$skiptoken=Paged=TRUE&p_ID=8&$top=2&$select=Title

http://ngo.com/_api/lists/getByTitle('lst_BreatheIn_Desc')/items?$skiptoken=Paged=TRUE&p_ID=8&$skip=2&$top=2&$select=Title

http://ngo.com/_api/web/Lists/GetByTitle('lst_BreatheIn_Desc')/items?$filter=Id gt 4&$top=3&$select=Title

http://ngo.com/_api/lists/getByTitle('lst_BreatheIn_Desc')/items/?$skip=2&$top=2&$select=Title
http://ngo.com/_api/web/lists/GetByTitle('smgDBMakePost')/Items?
$select=Title,Author/Title&$expand=Author

http://ngo.com/_api/web/Lists/GetByTitle('lst_BreatheIn_Desc')/items?$filter=Id gt 4&$top=3&$select=Author/Title,Author/ID,Author/FirstName&$expand=Author/Title,Author/ID

http://ngo.com/_api/web/GetUserById(1)

http://ngo.com/_api/web/lists/GetByTitle('smgDBMakePost')/items?$filter=ParentItemID eq 699&$select=ID,Title,ParentItemID  (get all replies);

http://ngo.com/_api/web/Lists/GetByTitle('smgDBMakePost')/items?$filter=Id eq 695&$select=Title,LikesCount,Author/Title,Author/ID&$expand=Author/Title



http://ngo.com/_api/web/lists/GetByTitle('smgDBMakePost')?$select=ListItemEntityTypeFullName
  
http://ngo.com/_api/web/lists/GetByTitle('smgDBMakePost')/items?$filter=Id eq 20&$select=Title,LikesCount,Title&$expand=LikedBy/Title
  
http://ngo.com/_api/lists/getByTitle('smgDBMakePost')/items?$filter=(substringof('test123',Title) or substringof('asas',PostCategory) or substringof('MIND',Company))

http://ngo.com/_api/web/lists/GetByTitle('smgDBMakePost')/items?$select=Title,LikesCount,LikedBy/Title&$expand=LikedBy

http://ngo.com/_api/web/lists/GetByTitle('smgDBMakePost')/items?$filter=id eq 695&$select=Title,LikesCount,LikedBy/Title&$expand=LikedBy

http://ngo.com/_api/web/Lists/GetByTitle('smgDBMakePost')/items?$filter=Id eq 695&$select=Title,LikesCount,LikedBy/Title&$expand=LikedBy
  
https://stagetest.motherson.com/_api/web/lists/GetByTitle('lst_WeatherLocationsUserPreference')?$select=ListItemEntityTypeFullName

https://stagetest.motherson.com/_api/Web/Lists/GetByTitle('lst_WeatherLocationsUserPreference')/Items

http://ngo.com/_api/web/Lists/GetByTitle('lst_BreatheIn_Desc')/items?$filter=Id gt 4&$top=3&$select=Title,ID&$orderby=Id desc

http://ngo.com/_api/web/sitegroups/getbyname('GRP_MSSL_RPM_Admin_User')/users

(https://simonovens.wordpress.com/2014/08/13/sp2013-rest-api-find-if-user-is-member-of-sharepoint-group/)

http://0179nitiv002tvs:29118/cdr/_api/web/GetFolderByServerRelativeUrl('CDRDocument/MIND')/Files?$expand=ListItemAllFields,ListItemAllFields/ParentList&$filter=substringof('IT',Title)

http://0179nitiv002tvs:29118/cdr/_api/web/GetFolderByServerRelativeUrl('CDRDocument/MIND')/Folders?$expand=ListItemAllFields,ListItemAllFields/ParentList&$filter=substringof('QQQQ',Name)

best url of rest api

http://spshell.blogspot.in/2015/01/sharepoint-2013-rest-api-reference.html

WCF Rest Service


REST stands for Representational State Transfer. It is an Architectural pattern more inclined towards a web. Web of Services should work in the same way as Web Of Pages works - each resource is identified by a unique id in the form of an URI. Resource can be anything; a Website, HTML page, xml document etc. Services can be built on top of REST architecture. It is a structured way of uniquely identifying resources and accessing them. Uses only standard verbs POST, GET, PUT and DELETE. REST is not a standard as such but just an architectural pattern.

Rest Principles :
  • Identify each resource uniquely. Resource can be anything; a website, HTML page, xml document etc.
  • Simple and Open - It is an architecture pattern and can be applied to any system. Uses only standard Http Verbs.
  • Use Universal API - Http - It can be used by any client or can be called from any programming language. It is technology independent.
  • Linked Resources - resources can contain link to other resources.

Rest usage examples :

REST - Yahoo web services use REST, including Flickr, del.icio.us API uses it
SOAP and REST both - EBay and Amazon
Google Web Services - SOAP

High REST and Low REST:

High REST - Uses all 4 verbs and uses well-constructed URIs.
LOW REST - Uses mostly Get and POST verbs only. More suited for Ajax services.

NOTE :

PUT and DELETE verbs are not supported by all browsers. Also, PUT and DELETE can be handled using POST verb itself.

HTTP Verbs

HTTP defines nine methods (sometimes referred to as "verbs") indicating the desired action to be performed on the identified resource.

Verb
Action
GET
Fetch a resource
PUT
Update resource
DELETE
Delete a resource
POST
Append to resource


Advantages of REST:

  • LightWeight - uses POX or JSON or ATOMPub for data transmission
  • REST does not support WS-* standard.
  • Message transmission can be controlled and supports different formats such as JSON, POX, AtomPub. Developers need not understand SOAP message structure as in case of SOAP.
  • Browsers can talk to rest services directly because REST works using URIs, QueryStrings, SSL.
  • WADL (Web Application Description Language) is a new standard available to support metadata for REST services.
  • Uses only standard Http Verbs and is technology independent.

Limitations :
  • Less secular has they do not obey WS-* specifications.
  • No metadata - WSDL. WADL is available but still its not universally accepted.

WCF REST basics
  • Is supported since .Net 3.5. There are readily available templates for REST projects. The .Net 3.5 has REST starter kit as well.
  • REST in .NET 4 is greatly simplified and leverages the Web Routing capabilities used in ASP.Net MVC and other parts of the web frameworks
  • Special binding available for REST support

    WebHttpBinding - A binding used to configure endpoints for Web services that are exposed through HTTP requests instead of SOAP messages.
  • WebGet and WebInvoke (all other verbs apart from GET) attributes were added to WCF. Message transmission format is POX or JSON.
  • UriTemplate : 
    o String that allows to define the structure of the URL. It is similar to ASP.Net Routing. 
    o UriTemplate only supports string parameters.
    o The segments in curly braces describe variables or holes. The segments not in curly braces describe literal strings. Template is bound with parameters to fill the holes.
    o UriTemplate can have a single wildcard character and also default values for variables. UriTemplate also includes wildcard capabilities. UriTemplate="*"will route all URIs to one method

    Example : 

    URI Template

    /weather/wa/seattle/cycling /weather/{state}/{city}/{activity}
    /weather/wa seattle /weather/{state}{city}
    /weather/USA/wa/Climate /weather/{country=USA}/{state}/Climate
    /weather/A /weather/B /weather/*
     
  • Global.asax is used to set the route to your service using the new ServiceRoute class
  • SOAP and REST based endpoints can co-exist side by side.

http://www.servicestack.net/ framework does it for you can you can as well do it yourself by defining multiple endpoints.

Sample Soure Code :

I am assuming that you have added an ADO.Net Entity Model object in your project file which maps to an Area table having the following fields
ID - Primary Key, varchar
Name - varchar
Code - varchar

This entity is available under SampleEntities Object context.

My code looks as below:
using System.Collections.Generic;using System.Linq;using System.ServiceModel;using System.ServiceModel.Activation;using System.ServiceModel.Web;
namespace WcfRestService1
{
    // Start the service and browse to http://:/Service1/help to view the service's generated help page    // NOTE: By default, a new instance of the service is created for each call; change the InstanceContextMode to Single if you want    // a single instance of the service to process all calls.     [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    // NOTE: If the service is renamed, remember to update the global.asax.cs file    public class AreaService    {
        [WebGet(UriTemplate = "/GetAllAreas", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        public List<area> GetAllAreas()
        {
            SampleEntities1 ctx = new SampleEntities1();
            var allAreas = (from p in ctx.Areas select p).ToList<area>();
            return allAreas;
        }
 
        [WebGet(UriTemplate = "/GetArea/{id}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        public Area GetAreaWithID(string id)
        {
            SampleEntities1 ctx = new SampleEntities1();
            var area = (from p in ctx.Areas where p.ID == id select p).Single();
            return area;
        }
        [WebInvoke(UriTemplate = "/AddArea/{id} {name} {code}", Method = "POST")]
        public void AddArea(string id, string name, string code)
        {
            SampleEntities1 ctx = new SampleEntities1();
            Area a1 = new Area { ID = id, Name = name, Code = code };
            ctx.Areas.AddObject(a1);
            ctx.SaveChanges();
        }
        [WebInvoke(UriTemplate = "/Delete/{id}", Method = "DELETE", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        public void DeleteArea(string id)
{
SampleEntities1 ctx = new SampleEntities1();
Area a1 = ctx.Areas.Where(p =&gt; p.ID == id).SingleOrDefault();
ctx.Areas.DeleteObject(a1);
ctx.SaveChanges();
}
 
    }
}


I am using the default web.config which uses standard endpoints. WebHttpBinding is used for REST services as it does not Soap message format for data tranmission. You can customize the message transmission format and choose either POX, JSON,AtomPub to name a few.

I am using C# Rest WCF Template available for .Net 4.0. It uses Routing and WebHttpBinding internally. So, there won't be any manual changes to the default web.config provided by the template . However, an entry for ADO.Net Entity object will be added too once you configure the ADO.Net Entity.





RESTFul Web Services Interview Questions and Answers

REST Web Service interview questions and Answers J2EEHere are list of my REST Interview questions, helpful for quick review before going for any web services interview on Java J2EE.

1) What is REST and RESTful web services ?
this is the first REST interview question on most of interviews as not everybody familiar with REST and also
start discussion based on candidates response. Anyway REST stands for REpresentational State Transfer (REST) its a relatively new concept of writing web services which enforces a stateless client server design where web services are treated as resource and can be accessed and identified by there URL unlike SOAP web services which were defined by WSDL.

Web services written by apply REST Architectural concept are called RESTful web services which focus on System resources and how state of Resource should be transferred over http protocol to a different clients written in different languages. In RESTful web services http methods like GET, PUT, POST and DELETE can can be used to perform CRUD operations.

2) What is differences between RESTful web services and SOAP web services ?
Though both RESTful web series and SOAP web service can operate cross platform they are architecturally different to each other, here is some of differences between REST and SOAP:

1) REST is more simple and easy to use than SOAP
2) REST uses HTTP protocol for producing or consuming web services while SOAP uses XML.
3) REST is lightweight as compared to SOAP and preferred choice in mobile devices and PDA's.
4) REST supports different format like text, JSON and XML while SOAP only support XML.
5) REST web services call can be cached to improve performance.

3) What is Restlet framework ?
Restlet is leading RESTful web framework for Java applications is used to build RESTFul web services it has two part Restlet API and a Restlet implementation much like Servlet specification. There are many implementation of Restlet framework available you just need to add there jar in your classpath to use them. By using Restlet web framework you can write client and server.

4) What is Resource in REST framework ?
it represent a "resource" in REST architecture. on RESTLET API it has life cycle methods like init(), handle() and release() and contains a Context, Request and Response corresponding to specific target resource. This is now deprecated over ServerResource class and you should use that. see Restlet documentation for more details.

5) Can you use Restlet without any web-container ?
Yes, Restlet framework provide default server which can be used to handle service request in web container is not available.

6) What is difference between Restlets and Jersey ?
This REST web service interview questions is open for you all, post you answer in comment section.

7) What is RESTEasy ?
RESTEasy is another REST framework introduced in JBoss Application Server. This was rather easy REST interview questions. you can answer in detail only if you have used this or working in JBoss.

8) What are the tools used for creating RESTFull web services ?
You can use AJAX(Asynchronous JavaScript with XAML) and Direct Web Removing to consume web serives in web application. Both Eclipse and NetBeans also supported development of RESTFul services.

9) How to display custom error pages using RestFull web services ?
In order to customize error you need to extend StatusService and implement getRepresentation(Status, Request, Response) method with your custom code now assign instance of your CustomStatusService to appropriate "statusService property".

10) Which HTTP methods are supported by RestFull web services ?
Another common REST interview questioning RESTFul web service each Resource supports GET, POST, PUT and DELETE http methods.GET is mapped to represent(), POST - acceptRepresentation(), PUT- storeRepresentation and DELET for rmeoveRepresentation.

11) What is difference between top-down and bottom-up approach of developing web services ?
In top-down approach first WSDL document is created and than Java classes are developed based on WSDL contract, so if WSDL contract changes you got to change your Java classes while in case of bottom up approach of web service development you first create Java code and then use annotations like @WebService to specify contract or interface and WSDL field will be automatically generated from your build.

12) What happens if RestFull resources are accessed by multiple clients ? do you need to make it thread-safe?
Since a new Resource instance is created for every incoming Request there is no need to make it thread-safe or add synchronization. multiple client can safely access RestFull resources concurrently.


Read more: http://javarevisited.blogspot.com/2012/01/rest-web-services-framework-interview.html#ixzz3zVHZ6J7R

No comments:

Post a Comment