Monday, July 6, 2015

WebApi Part1



WEBAPI ,
Is an HTTP service
Is designed for broader reach (different client , browsers, tablets,phones etc)
It uses HTTp as a protocol and not transport protocols
Lets see how we create one

Create New Projects->web ->WebAPi
You can see the structure is similar to your Web MVC Projects
Go to ->controllers->values controller
You can see the GET,POST,PUT,DELETE methods
Now run the solutions
You will end up in default home page .
See the WebApiConfig File

      config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }}
You see the url is similar to MVC but you don’t see the action here instead you see the api/controllers . actions are your GET,PUT,POST ,DELETE methods

Run the solutions navigate to api/Values

http://localhost:54725/api/Values

It will either return Json Doc or XML doc 


<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>value1</string>
<string>value2</string>
</ArrayOfstring>


You can also use fiddler to see results in different formats
Here is how I created new WEBApi .
Create a model class “team”

public class Team
    {
        [Key]
        public int TeamID { get; set; }
        [Required]
        public string TeamName { get; set; }
        public string CoachName { get; set; }
    }

Then create a controller with Entity framework scaffolding
You will see the controller has all the HTTp methods
Run the solution
Initially you will not get any results since its empty
Now either youu can make use of fiddler or what I have use is RestClient
Addon in firefox

Set method:post
content-type:application/json
body : {
"TeamName":"Team1","CoachName":"Tom"
}
Hit send you can see the result.
You can view in xml format also 


·  Status Code: 201 Created
·  Cache-Control: no-cache
·  Content-Length: 206
·  Content-Type: application/xml; charset=utf-8

1.  <Team xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WebApplication1.Models">
2.    <CoachName>Tom</CoachName>
3.    <TeamID>1</TeamID>
4.    <TeamName>Team1</TeamName>
5.  </Team>



No comments:

Post a Comment