SOCIAL MARKETING

Download Report

Transcript SOCIAL MARKETING

REST, WebAPI 2,
and Best Practices
Keith Telle
Lead Software Engineer
Bit Wizards
Gulf Coast DOTNET User Group
May 19, 2015
http://www.gulfcoastdotnet.org
@GCDNUG
What is REST?
• REpresentational State Transfer
• 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
• Chapter 5, “Representational State Transfer (REST)”
https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
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)
What is REST?
• For Network-based data transference
• Has widespread acceptance across the Web
• Simpler than SOAP and WSDL-based Web services
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
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
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
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
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
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
How does REST work?
GetCustomerDetails
GET http://example.com/customers/123456/details
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
How does REST work?
• HTTP Status Codes
200
201
304
400
401
Ok
Created
Not Modified
Bad Request
Not Authorized
403
404
405
415
500
Forbidden
Page / Resource Not Found
Method Not Allowed
Unsupported Media Type
Internal Server Error
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://…
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.
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
What does REST look like?
Resource
GET
Collection URI, such
ashttp://api.example.com/v1/re
sources/
List the URIs and perhaps other
details of the collection's
members.
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.
PUT
POST
Replace the entire collection with
Create a new entry in the
another collection.
collection. The new entry's URI is
assigned automatically and is
usually returned by the
operation.[9]
Replace the addressed member
of the collection, or if it does not
exist,create it.
ref. Wikipedia, Representational state transfer
Not generally used. Treat the
addressed member as a
collection in its own right and
create a new entry in it.[9]
DELETE
Delete the entire collection.
Delete the addressed member of
the collection.
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.)
What are the features
of Web API 2?
• Routing
http://example.com/users/711856
http://example.com/orders/233546
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;
}
…
}
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
What are the features
of Web API 2?
public class UsersController : ApiController
{
…
[Route(“users/{userId}/orders”)]
public IEnumerable<Order> GetOrdersByCustomer (int id)
{
var orders = UserRepository.GetOrders(id);
return orders;
}
…
}
What are the features
of Web API 2?
• Serialization
• XML Media-Type Formatter
• JSON Media-Type Formatter
• Selected via provided media type (HTTP headers)
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; }
}
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; }
}
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;
What are the features
of Web API 2?
• Dynamic Objects
public object Get()
{
return new {
Name = "Alice",
Age = 23,
Pets = new List<string> { "Fido", "Polly", "Spot" }
};
}
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
What are the features
of Web API 2?
• Security, Authentication, and Authorization
• JSON Web Token (JWT)
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-webtokens-with-katana-and-webapi.aspx
What are the features
of Web API 2?
• Error Handling
• HttpResponseException
• HttpError
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;
}
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);
}
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-webapi/creating-api-help-pages
• Cross origin resource sharing (CORS)
• OWIN (Open Web Interface for .NET) self hosting, http://owin.org/
• Defines a standard interface between .NET web servers and web applications
• Katana - OWIN implementations for Microsoft servers and frameworks
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
}
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
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
Best Practices
• ASP.NET WEB API : Do's/Dont's and Best Practices
https://curah.microsoft.com/204714/dosdonts-and-best-practices-ofaspnet-web-api
• Best Practices for Designing 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
• 10 Best Practices for Better RESTful API
http://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-betterrestful-api/
Can I see it all in action?
• Part 1: Building a simple REST service using WebAPI 2
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
• Interceptor (Chrome extension)
https://www.getpostman.com/docs/capture
Questions?