Download presentation
Presentation is loading. Please wait.
Published byDarrell Edwards Modified over 8 years ago
1
Keith Telle Lead Software Engineer Bit Wizards REST, WebAPI 2, and Best Practices
2
http://www.gulfcoastdotnet.org @GCDNUG Gulf Coast DOTNET User Group May 19, 2015
3
What is REST? RE presentational S tate T ransfer Originally described by Roy Thomas Fielding, circa 2000 Doctorial Dissertation “Architectural Styles and the Design of Network-based Software Architectures” https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm Chapter 5, “Representational State Transfer (REST)” https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
4
What is REST? Coordinated set of constraints applied to web service design Client/Server Stateless Cachable Layered system Code on demand (optional) Uniform interface Identification of resources Manipulation of resources through these representations Self-descriptive messages Hypermedia as the engine of application state (HATEOAS)
5
What is REST? For Network-based data transference Has widespread acceptance across the Web Simpler than SOAP and WSDL-based Web services
6
Why use REST? Performance User-perceived Caching, reducing the average latency of a series of interactions Most important information up front, retrieve additional details after rendering has begun Stateless, reduced consumption of physical resources Scalability Stateless Spread the interface across multiple servers Server doesn’t have to store state, allowing quick release of resources Easily cached using HTTP methods
7
Why use REST? Simplicity Clean separation of concerns Hides the underlying implementation of resources Hides the underlying communication mechanisms Modifiability Separation of concerns, components can evolve independently Visibility Monitoring system does not have to look beyond a single request in order to determine the full nature of the request Uniform interface
8
Why use REST? Portability Separation of concerns, platform independence HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications Reliability Eases the task of recovering from partial failures
9
How does REST work? Everything has an ID Allows you to map a URI to a resource Examples http://example.com/customers/1234 http://example.com/orders/2007/10/776654 http://example.com/products/4554 http://example.com/processes/salary-increase-234
10
How does REST work? Things are linked together HATEOAS “Hypermedia as the engine of application state” The idea of links in a document or resource Can point to resources that are provided by a different application, a different server Enables the client to move the application from one state to the next by following a link
11
How does REST work? Use standard HTTP methods simple, flexible, and ubiquitous GET : retrieve a resource POST : create a resource PUT : change the state of a resource or to update it DELETE : remove or delete a resource
12
How does REST work? GetCustomerDetails GET http://example.com/customers/123456/details
13
How does REST work? Uses HTTP Error Handling and Reporting Align errors with HTTP status codes Can provide body content to amplify Verbose Plain language descriptions As many hints as the API team can think of about what's causing an error
14
How does REST work? HTTP Status Codes 200Ok403Forbidden 201Created404Page / Resource Not Found 304Not Modified405Method Not Allowed 400Bad Request415Unsupported Media Type 401Not Authorized500Internal Server Error
15
How does REST work? Your API Key is Invalid, Generate a valid API Key at http://… A User ID is required for this action. Read more at http://… Your JSON was not properly formed. See example JSON here: http://…
16
How does REST work? Resources may have multiple representations Provide multiple representations of resources for different needs JSON or XML Also other formats such as iCalendar, vCard, etc.
17
How does REST work? Works statelessly Not stateless, communicates statelessly Turned into resource state or kept on the client Scalability Isolates the client from changes on the server Physical and logical
18
What does REST look like? ResourceGETPUTPOSTDELETE Collection URI, such ashttp://api.example.com/v1/re sources/ List the URIs and perhaps other details of the collection's members. Replace the entire collection with another collection. Create a new entry in the collection. The new entry's URI is assigned automatically and is usually returned by the operation. [9] [9] Delete the entire collection. Element URI, such ashttp://api.example.com/v1/re sources/item17 Retrieve a representation of the addressed member of the collection, expressed in an appropriate Internet media type. Replace the addressed member of the collection, or if it does not exist,create it. Not generally used. Treat the addressed member as a collection in its own right and create a new entry in it. [9] [9] Delete the addressed member of the collection. ref. Wikipedia, Representational state transfer
19
What is WebAPI 2? Microsoft framework for creating REST web services (alternative is ServiceStack framework, https://servicestack.net/) Based on the Model-View-Controller pattern, built on ASP.NET MVC 5 framework Model is an object that represents the data in your application View is the API Controller is an object that handles HTTP requests Caller-independent web services (Javascript/JQuery, Angular, etc.)
20
What are the features of Web API 2? Routing http://example.com/users/711856 http://example.com/orders/233546
21
What are the features of Web API 2? public class UsersController : ApiController { … // GET: api/Users/5 public string Get(int id) { var user = UserRepository.Get(id); return user; } … }
22
What are the features of Web API 2? Attribute Routing http://example.com/users/711856/orders http://example.com/users/711856/orders/233546 http://example.com/users/711856/orders/233546/details
23
What are the features of Web API 2? public class UsersController : ApiController { … [Route(“users/{userId}/orders”)] public IEnumerable GetOrdersByCustomer (int id) { var orders = UserRepository.GetOrders(id); return orders; } … }
24
What are the features of Web API 2? Serialization XML Media-Type Formatter JSON Media-Type Formatter Selected via provided media type (HTTP headers)
25
What are the features of Web API 2? JSON Media-Type Formatter public class Product { public string Name { get; set; } public decimal Price { get; set; } [JsonIgnore] public int ProductCode { get; set; } }
26
What are the features of Web API 2? JSON Media-Type Formatter [DataContract] public class Product { [DataMember] public string Name { get; set; } [DataMember] public decimal Price { get; set; } public int ProductCode { get; set; } }
27
What are the features of Web API 2? Configuration var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; json.UseDataContractJsonSerializer = true; json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); json.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat; json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc; json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
28
What are the features of Web API 2? Dynamic Objects public object Get() { return new { Name = "Alice", Age = 23, Pets = new List { "Fido", "Polly", "Spot" } }; }
29
What are the features of Web API 2? Security, Authentication, and Authorization ASP.NET Identity Individual The app uses a membership database Organizational Azure Active Directory, Office 365, or on-premise Active Directory credentials Windows authentication Intended for Intranet applications, and uses the Windows Authentication IIS module
30
What are the features of Web API 2? Security, Authentication, and Authorization JSON Web Token (JWT) http://jwt.io/ http://jwt.io/ Using JSON Web Tokens with Katana and WebAPI by K. Scott Allen http://odetocode.com/blogs/scott/archive/2015/01/15/using-json-web- tokens-with-katana-and-webapi.aspx http://odetocode.com/blogs/scott/archive/2015/01/15/using-json-web- tokens-with-katana-and-webapi.aspx
31
What are the features of Web API 2? Error Handling HttpResponseException HttpError
32
What are the features of Web API 2? HttpResponseException Returns any HTTP status code that you specify in the exception constructor public Product Get(int id) { Product item = repository.Get(id); if (item == null) { var resp = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(string.Format("No product with ID = {0}", id)), ReasonPhrase = "Product ID Not Found" }; throw new HttpResponseException(resp); } return item; }
33
What are the features of Web API 2? HttpError Provides a consistent way to return error information in the response body public HttpResponseMessage Get(int id) { Product item = repository.Get(id); if (item == null) { var message = string.Format("Product with id = {0} not found", id); return Request.CreateErrorResponse(HttpStatusCode.NotFound, message); } return Request.CreateResponse(HttpStatusCode.OK, item); }
34
What are the features of Web API 2? API Reference Creating Help Pages for ASP.NET Web API by Mike Wasson http://www.asp.net/web-api/overview/getting-started-with-aspnet-web- api/creating-api-help-pages http://www.asp.net/web-api/overview/getting-started-with-aspnet-web- api/creating-api-help-pages Cross origin resource sharing (CORS) OWIN (Open Web Interface for.NET) self hosting, http://owin.org/http://owin.org/ Defines a standard interface between.NET web servers and web applications Katana - OWIN implementations for Microsoft servers and frameworks
35
What are the features of Web API 2? IHttpActionResult public IHttpActionResult Get (int id) { Product product = _repository.Get (id); if (product == null) { return NotFound(); // Returns a NotFoundResult } return Ok(product); // Returns an OkNegotiatedContentResult }
36
Best Practices Use nouns but no verbs GET method and query parameters should not alter the state Use plural nouns Use sub-resources for relations Use HTTP headers for serialization formats Use HATEOAS Provide filtering, sorting, field selection and paging for collections Version your API Handle Errors with HTTP status codes Allow overriding HTTP method
37
Best Practices Don’t think in terms of endpoints Don’t expose your domain model in the API Design your API after intent Don’t overuse GET and POST Don’t limit your choice of error codes to 200 and 500 Don’t ignore caching Don’t require versioning
38
Best Practices ASP.NET WEB API : Do's/Dont's and Best Practices https://curah.microsoft.com/204714/dosdonts-and-best-practices-of- aspnet-web-api https://curah.microsoft.com/204714/dosdonts-and-best-practices-of- aspnet-web-api Best Practices for Designing a Pragmatic RESTful API http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api ASP.NET Web API: A REST perspective http://devproconnections.com/aspnet/aspnet-web-api-rest-perspective http://devproconnections.com/aspnet/aspnet-web-api-rest-perspective 10 Best Practices for Better RESTful API http://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better- restful-api/ http://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better- restful-api/
39
Can I see it all in action? Part 1: Building a simple REST service using WebAPI 2
40
Can I see it all in action? Part 2 : Testing a REST service using POSTman POSTman (Chrome application/extension) https://www.getpostman.com/ https://www.getpostman.com/docs https://www.getpostman.com/ https://www.getpostman.com/docs Interceptor (Chrome extension) https://www.getpostman.com/docs/capture https://www.getpostman.com/docs/capture
41
Questions?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.