KEMBAR78
RESTful APIs in .NET
RESTful APIs
Presented by
Gregory M. Sohl
Designing APIs in the REST style with
examples in ASP.NET Web API
Assumptions
Basic understanding of HTTP
A little C#
A little ASP.NET
Background
Described in Roy Fielding dissertation in 2000
 Roots back to 1994
 Roy was a key contributor to HTTP and URI
Style of building APIs in distributed hypermedia systems
It is not
 Particular Framework or Technology
 Set of Standards
 Design Pattern
REST
REprestational State Transfer
 Transfer representations of resources in a particular State
Based on architectural style of WWW
Set of Constraints
Concepts
Resource
 Has a URI
 Conceptual mapping to one or more entities
URI
 Address to a resource, it’s primary key
Concepts
Representation
 Snapshot of a resource
 NOT the resource itself
Media Type
 A format for the representation
 Commonly JSON or XML – but no limits
Constraints
Client / Server
 Duh, it’s an interface from one thing to another
 Separation of Concerns
 Independent evolution
Stateless
 Each request is independent
 No stored context on the server
Constraints
Cache
 Responses must indicate
 Clients can choose to reuse
URIs
 Resources are identified by URIs
 Nouns instead of Verbs
 Multiple URIs can refer to the same resource
Constraints
Uniform Interface
 Resource based
HTTP verbs
POST, PUT, GET, DELETE, HEAD (for conditional GETs)
Generally ignore others, e.g. OPTIONS, PATCH and TRACE
 HTTP result codes
 Self-descriptive messages
 Generalized media types
Constraints
Layered System
 Client not necessarily talking directly to server
 Layers can only “see” each other
 Supports firewalls, proxies, etc.
Constraints
Code on Demand
 Server can download code – change client behavior
 Simplify client dev
 Optional constraint
URIs
URIs are resource based – nouns
 Verbs come from HTTP methods, GET, POST, PUT, DELETE
 Use slashes to indicate resource hierarchy
http://myapi.com/{resource}
http://myapi.com/{resource}/{id}/{document}
http://myapi.com/{resource}/{id}/{child resource}
URIs - Contrast to SOAP
SOAP methods
 GetCustomerList()
 AddNewCustomer()
 GetCustomerInfo()
 UpdateCustomer()
 DeleteCustomer()
URIs - Contrast to SOAP
REST Requests
/customers
GET - retrieve a list of customers
POST - create a new customer
/customers/{customer id}
GET - retrieve information about a customer
PUT - update a customer's information
DELETE - remove a customer
HTTP Verbs
HTTP Verbs
Verb Usage
GET read
HEAD like GET, but returns only headers
POST create and other uses
PUT update
DELETE remove
OPTIONS documentation
Building a RESTful API in .NET
ASP.NET - Great platform for REST style
Web API is specifically built for REST
 Many facilities and helpers built in
ASP.NET
Sites
MVC
Web
Forms
Web
Pages
SPA
Services
Web API SignalIR
HTTP Status Codes
1xx – Informational – seldom used
2xx – Success
3xx – Redirection, unchanged. Client should do
something different to complete the request.
4xx – Client action caused an error
5xx – Server error
Common HTTP Status Codes
200 OK – Request worked. Nothing to report
201 Created – Indicate new resource created
204 No Content – Used with conditional GETs
304 Not Modified – Used with
Common HTTP Status Codes
401 Unauthorized
404 Not found
500 Internal Server Error – Include details in body
503 Service Unavailable – Under maint, etc.
API Design
Art or Science?
Request Types
 Safe – No side effects
 Idempotent – Multiple requests have same effect
Method Safe Idempotent Cachable
GET Yes Yes Yes
POST No No No
PUT No Yes No
DELETE No Yes No
API Design
URIs
 Sensible names – using nouns
 Forward slashes for hierarchical relationships
 Use dashes in multi-word resource names for readability
 Consistent use of lowercase resource names
 Avoid file extensions
 Fine grained to support caching
API Design
Representation Formats
 Choose appropriate media types
JSON, XML, domain specific
Client indicates preference via Accept header
Caching
Responses indicate cachability of result
 Use Cache-Control header
 Use Expires header
 Generate ETag header
Unique for a resource version
 Using an Etag
 Use for GET & PUT
Caching – Why??
The internet caches
Some requests are expensive
Increase throughput
Related Info In Results
Favor links instead of related keys
User Group Demo
User groups and their city
API
 /usergroups
GET, POST
 /usergroups/{id}
GET, PUT, DELETE
 /usergroups/{id}/map
Documentation
Doc needs are not unlike for any API
 URIs
 Methods
 Parameters
 Data formats
 Response codes
 Samples
Why REST
HTTP is Ubiquitous
Lighter weight than SOAP
Caching Support
Acceptance
Scales well
Decoupled
Resources
Tutorial
 http://www.restapitutorial.com
Best Practices PDF
 http://www.restapitutorial.com/resources.html
Books
 Designing Evolvable Web APIs with ASP.NET
http://chimera.labs.oreilly.com/books/1234000001708/index.html
 RESTful Web Services Cookbook
http://www.amazon.com/RESTful-Web-Services-Cookbook-
Scalability/dp/0596801688
Resources
Courses
 http://www.pluralsight.com/courses/rest-fundamentals
Caching Management Library - Cache Cow
 http://www.hanselman.com/blog/NuGetPackageOfTheWeekAS
PNETWebAPICachingWithCacheCowAndCacheOutput.aspx

RESTful APIs in .NET

  • 1.
    RESTful APIs Presented by GregoryM. Sohl Designing APIs in the REST style with examples in ASP.NET Web API
  • 2.
    Assumptions Basic understanding ofHTTP A little C# A little ASP.NET
  • 3.
    Background Described in RoyFielding dissertation in 2000  Roots back to 1994  Roy was a key contributor to HTTP and URI Style of building APIs in distributed hypermedia systems It is not  Particular Framework or Technology  Set of Standards  Design Pattern
  • 4.
    REST REprestational State Transfer Transfer representations of resources in a particular State Based on architectural style of WWW Set of Constraints
  • 5.
    Concepts Resource  Has aURI  Conceptual mapping to one or more entities URI  Address to a resource, it’s primary key
  • 6.
    Concepts Representation  Snapshot ofa resource  NOT the resource itself Media Type  A format for the representation  Commonly JSON or XML – but no limits
  • 7.
    Constraints Client / Server Duh, it’s an interface from one thing to another  Separation of Concerns  Independent evolution Stateless  Each request is independent  No stored context on the server
  • 8.
    Constraints Cache  Responses mustindicate  Clients can choose to reuse URIs  Resources are identified by URIs  Nouns instead of Verbs  Multiple URIs can refer to the same resource
  • 9.
    Constraints Uniform Interface  Resourcebased HTTP verbs POST, PUT, GET, DELETE, HEAD (for conditional GETs) Generally ignore others, e.g. OPTIONS, PATCH and TRACE  HTTP result codes  Self-descriptive messages  Generalized media types
  • 10.
    Constraints Layered System  Clientnot necessarily talking directly to server  Layers can only “see” each other  Supports firewalls, proxies, etc.
  • 11.
    Constraints Code on Demand Server can download code – change client behavior  Simplify client dev  Optional constraint
  • 12.
    URIs URIs are resourcebased – nouns  Verbs come from HTTP methods, GET, POST, PUT, DELETE  Use slashes to indicate resource hierarchy http://myapi.com/{resource} http://myapi.com/{resource}/{id}/{document} http://myapi.com/{resource}/{id}/{child resource}
  • 13.
    URIs - Contrastto SOAP SOAP methods  GetCustomerList()  AddNewCustomer()  GetCustomerInfo()  UpdateCustomer()  DeleteCustomer()
  • 14.
    URIs - Contrastto SOAP REST Requests /customers GET - retrieve a list of customers POST - create a new customer /customers/{customer id} GET - retrieve information about a customer PUT - update a customer's information DELETE - remove a customer
  • 15.
    HTTP Verbs HTTP Verbs VerbUsage GET read HEAD like GET, but returns only headers POST create and other uses PUT update DELETE remove OPTIONS documentation
  • 16.
    Building a RESTfulAPI in .NET ASP.NET - Great platform for REST style Web API is specifically built for REST  Many facilities and helpers built in ASP.NET Sites MVC Web Forms Web Pages SPA Services Web API SignalIR
  • 17.
    HTTP Status Codes 1xx– Informational – seldom used 2xx – Success 3xx – Redirection, unchanged. Client should do something different to complete the request. 4xx – Client action caused an error 5xx – Server error
  • 18.
    Common HTTP StatusCodes 200 OK – Request worked. Nothing to report 201 Created – Indicate new resource created 204 No Content – Used with conditional GETs 304 Not Modified – Used with
  • 19.
    Common HTTP StatusCodes 401 Unauthorized 404 Not found 500 Internal Server Error – Include details in body 503 Service Unavailable – Under maint, etc.
  • 20.
    API Design Art orScience? Request Types  Safe – No side effects  Idempotent – Multiple requests have same effect Method Safe Idempotent Cachable GET Yes Yes Yes POST No No No PUT No Yes No DELETE No Yes No
  • 21.
    API Design URIs  Sensiblenames – using nouns  Forward slashes for hierarchical relationships  Use dashes in multi-word resource names for readability  Consistent use of lowercase resource names  Avoid file extensions  Fine grained to support caching
  • 22.
    API Design Representation Formats Choose appropriate media types JSON, XML, domain specific Client indicates preference via Accept header
  • 23.
    Caching Responses indicate cachabilityof result  Use Cache-Control header  Use Expires header  Generate ETag header Unique for a resource version  Using an Etag  Use for GET & PUT
  • 24.
    Caching – Why?? Theinternet caches Some requests are expensive Increase throughput
  • 25.
    Related Info InResults Favor links instead of related keys
  • 26.
    User Group Demo Usergroups and their city API  /usergroups GET, POST  /usergroups/{id} GET, PUT, DELETE  /usergroups/{id}/map
  • 27.
    Documentation Doc needs arenot unlike for any API  URIs  Methods  Parameters  Data formats  Response codes  Samples
  • 28.
    Why REST HTTP isUbiquitous Lighter weight than SOAP Caching Support Acceptance Scales well Decoupled
  • 29.
    Resources Tutorial  http://www.restapitutorial.com Best PracticesPDF  http://www.restapitutorial.com/resources.html Books  Designing Evolvable Web APIs with ASP.NET http://chimera.labs.oreilly.com/books/1234000001708/index.html  RESTful Web Services Cookbook http://www.amazon.com/RESTful-Web-Services-Cookbook- Scalability/dp/0596801688
  • 30.
    Resources Courses  http://www.pluralsight.com/courses/rest-fundamentals Caching ManagementLibrary - Cache Cow  http://www.hanselman.com/blog/NuGetPackageOfTheWeekAS PNETWebAPICachingWithCacheCowAndCacheOutput.aspx