My boss asked me implement a RESTful web service on some of our products. We are a startup and I am the only one assigned to this task.
I don't know anything about web service, not mentioning RESTful web service.
So I want to get started.
Because I can't tell what service we provide, I can assume this following product:
User just type a url with parameter of x and y, and my service returns the result of x*y. I presume this is a very basic RESTful web service, right? Please ignore details like how many users will access it. I can assume lots of users will have our service.
How do I start and what do I need to learn?
Should I set up a Tomcat + a RESTful hosting software in front at server side?
Please give me some guidance and hints.
Thanks
I think Google Reader API / Facebook API / Twitter API is a kind of good example for the RESTful service I am going to implement. How did Google and other company achieve that?
You didn't specify a language, which makes it tough, but there are many frameworks that could help you with making a RESTful service.
For java a nice one is Jersey (http://jersey.java.net/), and since you mention Tomcat I am assuming you will use Java.
By following the tutorials you will build simple services and then you can start to add more complexity.
You may want to read this:
http://ajaxpatterns.org/RESTful_Service
to get an idea of REST
.
For example, when to use GET, POST or PUT, for example, and what response codes you should use when there are various errors.
Good news: whatever you do will be RESTful as long as you claim that it is.
Bad news: you are sort of on your own defining the service because there is no "standard" way of doing a RESTful service. Since item 1.
If your web service really is as simple as multiplcation operation, that it would be a web page living at a url yourcompany.com/service/multiply which can take 2 arguments, perhaps the old-fashioned GET way (GET yourcompany.com/service/multiply?x=7&y=6) or as two POST arguments, and then produce a response consisting of just one string "42".
Now, as your requests get more complicated, you will either make them be formatted as simple XML:
<multiply>
<arg value="6">
<arg value="7">
</multiply>
and response
<response value="42"/>
or whatever you feel like. Or perhaps JSON. You will also need to make sure to specify which HTTP method should be used for each method call and make sure that they make sense (e.g. PUT for uploads, DELETE for deletes).
You get the idea.
RESTful is not a specification, it's way of thinking about web services.
I would start with understanding what is a RESTful service because platforms won't help when you don't understand what the demands are.
you can start with reading this: http://www.ibm.com/developerworks/webservices/library/ws-restful/
and then just google RESTful service with the programming language you decided to implement your service
Simple example with WCF REST.
[ServiceContract]
public interface IService1
{
[WebGet(UriTemplate = "contact/{PID}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
Person GetContact(string PID);
//[WebInvoke(Method = "POST", UriTemplate = "person")]
[OperationContract]
[WebInvoke(UriTemplate = "/create", Method = "POST")]
void SaveContact(Person person);
[WebGet(UriTemplate = "/")]//RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)
[OperationContract]
List<Person> GetAllContacts();
[OperationContract]
[WebInvoke(UriTemplate = "/{id}", Method = "PUT")]
void UpdateProduct(string id, Person person);
[OperationContract]
[WebInvoke(UriTemplate = "/{id}", Method = "DELETE")]
void DeleteProduct(string id);
[OperationContract]
[WebInvoke(UriTemplate = "UploadFile")]
void UploadFile(Stream stream);
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract(Namespace = "")]
public class Person
{
[DataMember]
public string PersonId { get; set; }
[DataMember]
public string PersonName { get; set; }
}
Service Implementation :
public class Service1 : IService1
{
public Person GetContact(string PID)
{
return new Person(){PersonId=PID, PersonName=PID+".Name"};
}
public void SaveContact(Person person)
{
int a = 0;
}
public void UpdateProduct(string id, Person person)
{
int b = 0;
}
public List<Person> GetAllContacts()
{
List<Person> lstPerson = new List<Person>();
for (int i = 0; i < 10; i++)
{
Person p = new Person();
p.PersonId = i.ToString();
p.PersonName = i + "Person";
lstPerson.Add(p);
}
return lstPerson;
}
public void DeleteProduct(string id)
{
int c = 0;
}
public void UploadFile( System.IO.Stream stream)
{
object obj = stream;
}
}
Call Rest service using WebRequest :
class Program
{
static void Main(string[] args)
{
new Program().GetContacts();
//new Program().AddContacts();
//new Program().Update();
//new Program().Delete();
}
public void GetContacts()
{
WebRequest req = WebRequest.Create(@"http://localhost:60517/Service1.svc/");
req.Method = "GET";
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
if (resp.StatusCode == HttpStatusCode.OK)
{
using (Stream respStream = resp.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream, Encoding.UTF8);
Console.WriteLine(reader.ReadToEnd());
}
}
else
{
Console.WriteLine(string.Format("Status Code: {0}, Status Description: {1}", resp.StatusCode, resp.StatusDescription));
}
Console.Read();
}
public void AddContacts()
{
WebRequest req = WebRequest.Create(@"http://localhost:60517/Service1.svc/create");
req.Method = "POST";
req.ContentType = @"application/xml; charset=utf-8";
WriteProductXml(req, "11", "Asif");
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
Console.WriteLine(string.Format("Status Code: {0}, Status Description: {1}", resp.StatusCode, resp.StatusDescription));
Console.Read();
}
public static void WriteProductXml(WebRequest req, string name, string description)
{
StringBuilder builder = new StringBuilder();
builder.AppendLine("<Person>");
builder.AppendLine("<PersonId>" + description + "</PersonId>");
builder.AppendLine("<PersonName>" + name + "</PersonName>");
builder.AppendLine("</Person>");
req.ContentLength = Encoding.UTF8.GetByteCount(builder.ToString());
using (Stream stream = req.GetRequestStream())
{
stream.Write(Encoding.UTF8.GetBytes(builder.ToString()), 0, Encoding.UTF8.GetByteCount(builder.ToString()));
}
}
public void Update()
{
WebRequest req = WebRequest.Create(@"http://localhost:60517/Service1.svc/1");
req.Method = "PUT";
req.ContentType = @"application/xml; charset=utf-8";
WriteProductXmlUpdate(req, "11", "Asif");
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
Console.WriteLine(string.Format("Status Code: {0}, Status Description: {1}", resp.StatusCode, resp.StatusDescription));
Console.Read();
}
public static void WriteProductXmlUpdate(WebRequest req, string name, string description)
{
StringBuilder builder = new StringBuilder();
builder.AppendLine("<Person>");
builder.AppendLine("<PersonId>" + description + "</PersonId>");
builder.AppendLine("<PersonName>" + name + "</PersonName>");
builder.AppendLine("</Person>");
req.ContentLength = Encoding.UTF8.GetByteCount(builder.ToString());
using (Stream stream = req.GetRequestStream())
{
stream.Write(Encoding.UTF8.GetBytes(builder.ToString()), 0, Encoding.UTF8.GetByteCount(builder.ToString()));
}
}
public void Delete()
{
WebRequest req = WebRequest.Create(@"http://localhost:60517/Service1.svc/1");
req.Method = "DELETE";
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
Console.WriteLine(string.Format("Status Code: {0}, Status Description: {1}", resp.StatusCode, resp.StatusDescription));
Console.Read();
}
}