SlideShare une entreprise Scribd logo
1  sur  50
Embrace HTTP
with ASP.NET Web API

                       @filip_woj
@filip_woj
 www.strathweb.com
www.climaxmedia.com




                      @filip_woj
What is ASP.NET Web API?
●
    New Microsoft framework (RTM August 2012) for building
    HTTP services & applications
●
    Aimed at simplyfing and standardizing HTTP area on the
    MS stack (see: WCF / ASMX / MVC / HttpHandlers)
●
    Supports both REST and RPC style services
●
    Open source!




                                                     @filip_woj
But it's Microsoft!




From: Scott Hanselman's “ONE ASP.NET” talk at aspconf 2012




                                                             @filip_woj
Web API origins
●
    HTTP in WCF
●
    WCF REST starter kit
●
    WCF Web API
●
    finally adopted some concepts from ASP.NET MVC




                                                     @filip_woj
@filip_woj
A mix of WCF Web API & MVC
●
    from WCF Web API:
    - content negotiation
    - message handlers
    - REST & dispatching based on HTTP verbs
    – code based configuration




                                               @filip_woj
A mix of WCF & MVC
●
    from MVC:
    - model binding concept
    - controller based approach & RPC
    - routing
    - filters




                                        @filip_woj
@filip_woj
“ASP.NET” “Web API”
●
    The name creates lots of misconceptions
●
    “ASP.NET”:
      it doesn't require neither ASP.NET, nor IIS to run
●
    “Web API”:
      it's an HTTP framework, that can do much more than "just" API




                                                              @filip_woj
How can it work without ASP.NET/IIS?
●
    Web hosting:
      ASP.NET & IIS
      OWIN (i.e. Katana)
●
    Self hosting: (using WCF hardened core)
      WPF
      Windows service
      console app, any other .NET app
●
    Memory hosting: whole pipeline running in memory
                                                       @filip_woj
@filip_woj
OK, but why would I need it?
●
    New HTTP object model
●
    Work with HTTP concepts
●
    HTTP as a fully fledged *application* protocol
●
    Facilitates both REST & RPC
●
    Async from top-to-bottom




                                                     @filip_woj
@filip_woj
Async examples
●
    Handlers:
Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken
cancellationToken);

●
    Filters:
Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext
actionContext, CancellationToken cancellationToken,
Func<Task<HttpResponseMessage>> continuation);

●
    Formatters:
Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent
content, TransportContext transportContext);
Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent
content, IFormatterLogger formatterLogger);


                                                                         @filip_woj
New HTTP object model
●
    Strongly typed HttpResponseMessage
●
    Strongly typed HttpRequestMessage
●
    Strongly typed Headers
●
    Strongly typed HttpContent
●
    No more “angle brackets coding” & magic strings
●
    Asynchronous API
●
    Client-server symmetry

                                                      @filip_woj
HTTP status codes
●
    1xx – Informational
●
    2xx – Successful
●
    3xx – Redirection
●
    4xx – Error on the client side
●
    5xx – Error on the server side




                                     @filip_woj
HTTP headers – request
●
    Request headers (selected)
       –   Accept, Accept-Language, Accept-Encoding
       –   Authorization, Cache-Control, Range
       –   If-Match, If-Modified-Since, If-Range
●
    Content headers (selected)
       –   Allow, Content-Encoding, Content-Language
       –   Content-Length, Content-Type, Expires
       –   Last-Modified


                                                       @filip_woj
HTTP headers – response
●
    Response headers (selected)
       –   Accept-Ranges, Connection
       –   Cache-control, Date, Etag
       –   RetryAfter, Warning, Location
●
    Content headers (selected)
       –   Allow, Content-Encoding, Content-Language
       –   Content-Length, Content-Type, Expires
       –   Last-Modified


                                                       @filip_woj
@filip_woj
RPC
●
    /api/GetTeams
●
    /api/GetTeam?id=1
●
    /api/GetPlayersByTeam?id=1
●
    /api/AddTeam
●
    /api/UpdateTeam
●
    /api/UpdateTeam?id=1&name=”Leafs”
●
    /api/DeleteTeam?id=1

                                        @filip_woj
@filip_woj
REST
●
    representational state transfer
●
    architecture for building systems by Roy Fielding
●
    advantages:
       stateless
       cachability
       hypermedia driven (client needs to know one link, usually)
       scalability
       everything addressable with URI

                                                                    @filip_woj
From: presentation by @alexbeletsky




                                      @filip_woj
HTTP verbs
●
    Represent CRUD on a resource:
    - GET: read, cachable, retreives a resource
    - POST: non-cacheable, creates a resource
    - PUT: updates a resource, safe to call multiple times
    - DELETE: deletes a resource, safe to call multiple times
●
    Can also use others i.e. PATCH (partial update of a
    resource)


                                                             @filip_woj
RESTful
●
    GET /api/teams
●
    GET /api/teams/1
●
    GET /api/teams/1/players
●
    POST /api/teams
●
    PUT /api/teams/1
●
    DELETE /api/teams/1



                                    @filip_woj
First API – GET
public class TeamsController : ApiController
{
        private readonly IUnitOfWork _uow;

        public TeamsController(IUnitOfWork uow){
            _uow = uow;
        }

        public IEnumerable<Team> Get()
        {
            return _uow.Teams;
        }

        public Team Get(int id)
        {
            var team = _uow.Teams.FirstOrDefault(i => i.Id == id);
            if (team == null) throw new
HttpResponseException(HttpStatusCode.NotFound);
            return team;
        }

                                                                     @filip_woj
First API – POST
        public void Post(Team value)
        {
            if (!ModelState.IsValid) throw new
HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest,
ModelState));

            _uow.Teams.Add(value);
            _uow.SaveChanges();
        }




                                                                         @filip_woj
First API – PUT
        public void Put(int id, Team value)
        {
            if (!ModelState.IsValid) throw new
HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest,
ModelState));

            var team = _uow.Teams.FirstOrDefault(i => i.Id == id);
            if (team == null) throw new
HttpResponseException(HttpStatusCode.NotFound);

            team.League = value.League;
            team.Name = value.Name;

            _uow.SaveChanges();
        }




                                                                         @filip_woj
First API – DELETE
        public void Delete(int id)
        {
            var team = _uow.Teams.FirstOrDefault(i => i.Id == id);
            if (team == null) throw new
HttpResponseException(HttpStatusCode.NotFound);

            _uow.Teams.Remove(team);
            _uow.SaveChanges();

        }
   }




                                                                     @filip_woj
Demo: first API




                  @filip_woj
Content negotiation
●
    Dynamically deciding the media type
●
    Same data can be represented in various formats:
      - JSON
      – XML
      – CSV
      – binary
      – anything to what your data can be serialized/deserialized from
●
    In Web API done with MediaTypeFormatters
                                                               @filip_woj
Content negotiation in Web API
●
    Web API uses the following precedence:
      1. MediaTypeMapping
          ●
              /api/resource.json, /api/resource?format=json
      2. Accept headers
          ●
              Accept: application/json
      3. Content type header
          ●
              Content-Type: text/xml
      4. MediaTypeFormatter order & check whether a formatter can
      serialize/deserialize a given type

                                                              @filip_woj
So how my model gets serialized?
●
    Out of the box supports:
    - XML (DataContractSerializer / XmlSerializer)
    - JSON (DataContractSerializer / JSON.NET)
    - Form values (from client only, one-way)




                                                     @filip_woj
Extending content negotiation
●
    Very easy, some examples:
    - BSON (binary JSON)
    - ServiceStack.Text (instead of JSON.NET)
    - MessagePack
    - Mobi (returning ebook!)
    - RSS/Atom
    - Supporting Razor views (text/html)

                                                @filip_woj
@filip_woj
@filip_woj
Message Handlers
●
    “Russian doll model”
●
    run first and last
●
    process raw HttpRequestMessage &
    HttpResponseMessage
●
    Ideal for generic tasks such as authentication or API usage
    logging
●
    Can be global or route-specific


                                                         @filip_woj
Client-server symmetry




    By: Henrik Frystyk Nielsen




●
      Message handlers can run on server and on the client
●
      HttpServer is a message handler itself

                                                        @filip_woj
Filters
●
    Conceptually same as in MVC
●
    Cached for performance (unlike MVC)
●
    Pre-action processing of raw HttpRequestMesage
●
    Post-action processing of raw HttpResponseMessage




                                                     @filip_woj
Controllers
●
    Represent your API resources
●
    Similar as in MVC
●
    Routing engine determines which controller to use
●
    Supports nested resources




                                                        @filip_woj
Dispatching actions
●
    By default HTTP verb based (RESTful)
●
    Actions matched:
    ●
        by prefix (i.e. GetAll, GetById) or
    ●
        by action attribute (i.e. [HttpPost])
●
    Can be changed to action based (RPC style)




                                                 @filip_woj
@filip_woj
Anything else?
●
    TDD, BDD – whole pipeline can run in memory
●
    Async from top-to-bottom – scales well
●
    Simple: figure out your resources, and build around them
●
    Next release (Feb 2013) will have OData support
●
    Integrates with SignalR




                                                       @filip_woj
Demo: first API – self hosted




                                @filip_woj
Demo: first API – memory hosted




                              @filip_woj
Demo: adding BSON formatter




                              @filip_woj
Demo: P2P in WPF




                   @filip_woj
Follow these guys
      @frystyk
    @glennblock
   @tourismgeek
    @darrel_miller
      @aliostad
   @benfosterdev
      @pwalat
     @pmhsfelix
                     @filip_woj
@filip_woj

Contenu connexe

Tendances

Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and DjangoMichael Pirnat
 
Kicking off with Zend Expressive and Doctrine ORM (ZendCon 2016)
Kicking off with Zend Expressive and Doctrine ORM (ZendCon 2016)Kicking off with Zend Expressive and Doctrine ORM (ZendCon 2016)
Kicking off with Zend Expressive and Doctrine ORM (ZendCon 2016)James Titcumb
 
Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Michael Girouard
 
The Parenscript Common Lisp to JavaScript compiler
The Parenscript Common Lisp to JavaScript compilerThe Parenscript Common Lisp to JavaScript compiler
The Parenscript Common Lisp to JavaScript compilerVladimir Sedach
 
Ancient To Modern: Upgrading nearly a decade of Plone in public radio
Ancient To Modern: Upgrading nearly a decade of Plone in public radioAncient To Modern: Upgrading nearly a decade of Plone in public radio
Ancient To Modern: Upgrading nearly a decade of Plone in public radioCristopher Ewing
 
Cwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey IntroductionseyCwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey Introductionseyelliando dias
 
Deepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jspDeepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jspDEEPAK KHETAWAT
 
parenscript-tutorial
parenscript-tutorialparenscript-tutorial
parenscript-tutorialtutorialsruby
 
OpenNTF Domino API - Overview Introduction
OpenNTF Domino API - Overview IntroductionOpenNTF Domino API - Overview Introduction
OpenNTF Domino API - Overview IntroductionPaul Withers
 
An Introduction to Websphere sMash for PHP Programmers
An Introduction to Websphere sMash for PHP ProgrammersAn Introduction to Websphere sMash for PHP Programmers
An Introduction to Websphere sMash for PHP Programmersjphl
 
30 Minutes To CPAN
30 Minutes To CPAN30 Minutes To CPAN
30 Minutes To CPANdaoswald
 
Mashups with Drupal and QueryPath
Mashups with Drupal and QueryPathMashups with Drupal and QueryPath
Mashups with Drupal and QueryPathMatt Butcher
 
Deploying Perl apps on dotCloud
Deploying Perl apps on dotCloudDeploying Perl apps on dotCloud
Deploying Perl apps on dotClouddaoswald
 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...Guillaume Laforge
 
XML-Free Programming : Java Server and Client Development without &lt;>
XML-Free Programming : Java Server and Client Development without &lt;>XML-Free Programming : Java Server and Client Development without &lt;>
XML-Free Programming : Java Server and Client Development without &lt;>Arun Gupta
 
Getting started with Catalyst and extjs
Getting started with Catalyst and extjsGetting started with Catalyst and extjs
Getting started with Catalyst and extjsPeter Edwards
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Anton Arhipov
 

Tendances (20)

Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
Kicking off with Zend Expressive and Doctrine ORM (ZendCon 2016)
Kicking off with Zend Expressive and Doctrine ORM (ZendCon 2016)Kicking off with Zend Expressive and Doctrine ORM (ZendCon 2016)
Kicking off with Zend Expressive and Doctrine ORM (ZendCon 2016)
 
Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5
 
The Parenscript Common Lisp to JavaScript compiler
The Parenscript Common Lisp to JavaScript compilerThe Parenscript Common Lisp to JavaScript compiler
The Parenscript Common Lisp to JavaScript compiler
 
Ancient To Modern: Upgrading nearly a decade of Plone in public radio
Ancient To Modern: Upgrading nearly a decade of Plone in public radioAncient To Modern: Upgrading nearly a decade of Plone in public radio
Ancient To Modern: Upgrading nearly a decade of Plone in public radio
 
Cwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey IntroductionseyCwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey Introductionsey
 
Develop webservice in PHP
Develop webservice in PHPDevelop webservice in PHP
Develop webservice in PHP
 
Deepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jspDeepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jsp
 
REST API Laravel
REST API LaravelREST API Laravel
REST API Laravel
 
parenscript-tutorial
parenscript-tutorialparenscript-tutorial
parenscript-tutorial
 
OpenNTF Domino API - Overview Introduction
OpenNTF Domino API - Overview IntroductionOpenNTF Domino API - Overview Introduction
OpenNTF Domino API - Overview Introduction
 
An Introduction to Websphere sMash for PHP Programmers
An Introduction to Websphere sMash for PHP ProgrammersAn Introduction to Websphere sMash for PHP Programmers
An Introduction to Websphere sMash for PHP Programmers
 
30 Minutes To CPAN
30 Minutes To CPAN30 Minutes To CPAN
30 Minutes To CPAN
 
Mashups with Drupal and QueryPath
Mashups with Drupal and QueryPathMashups with Drupal and QueryPath
Mashups with Drupal and QueryPath
 
Deploying Perl apps on dotCloud
Deploying Perl apps on dotCloudDeploying Perl apps on dotCloud
Deploying Perl apps on dotCloud
 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
 
XML-Free Programming : Java Server and Client Development without &lt;>
XML-Free Programming : Java Server and Client Development without &lt;>XML-Free Programming : Java Server and Client Development without &lt;>
XML-Free Programming : Java Server and Client Development without &lt;>
 
Getting started with Catalyst and extjs
Getting started with Catalyst and extjsGetting started with Catalyst and extjs
Getting started with Catalyst and extjs
 
Workin On The Rails Road
Workin On The Rails RoadWorkin On The Rails Road
Workin On The Rails Road
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012
 

Similaire à Embrace HTTP with ASP.NET Web API

Unleash the power of HTTP with ASP.NET Web API
Unleash the power of HTTP with ASP.NET Web APIUnleash the power of HTTP with ASP.NET Web API
Unleash the power of HTTP with ASP.NET Web APIFilip W
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiTiago Knoch
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST APICaldera Labs
 
REST & RESTful Web Service
REST & RESTful Web ServiceREST & RESTful Web Service
REST & RESTful Web ServiceHoan Vu Tran
 
RESTful API-centric Universe
RESTful API-centric UniverseRESTful API-centric Universe
RESTful API-centric UniverseTihomir Opačić
 
Intro to Hypermedia APIs
Intro to Hypermedia APIsIntro to Hypermedia APIs
Intro to Hypermedia APIsSmartLogic
 
Motion Django Meetup
Motion Django MeetupMotion Django Meetup
Motion Django MeetupMike Malone
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckrICh morrow
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswanivvaswani
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHPZoran Jeremic
 
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...
Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...François-Guillaume Ribreau
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIRasan Samarasinghe
 
Getting started with DSpace 7 REST API
Getting started with DSpace 7 REST APIGetting started with DSpace 7 REST API
Getting started with DSpace 7 REST API4Science
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna Mitchell
 

Similaire à Embrace HTTP with ASP.NET Web API (20)

Unleash the power of HTTP with ASP.NET Web API
Unleash the power of HTTP with ASP.NET Web APIUnleash the power of HTTP with ASP.NET Web API
Unleash the power of HTTP with ASP.NET Web API
 
Rest with Spring
Rest with SpringRest with Spring
Rest with Spring
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST API
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
REST & RESTful Web Service
REST & RESTful Web ServiceREST & RESTful Web Service
REST & RESTful Web Service
 
RESTful API-centric Universe
RESTful API-centric UniverseRESTful API-centric Universe
RESTful API-centric Universe
 
Intro to Hypermedia APIs
Intro to Hypermedia APIsIntro to Hypermedia APIs
Intro to Hypermedia APIs
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Motion Django Meetup
Motion Django MeetupMotion Django Meetup
Motion Django Meetup
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
 
RESTing with JAX-RS
RESTing with JAX-RSRESTing with JAX-RS
RESTing with JAX-RS
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHP
 
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...
Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST API
 
ASP.NET WEB API Training
ASP.NET WEB API TrainingASP.NET WEB API Training
ASP.NET WEB API Training
 
Getting started with DSpace 7 REST API
Getting started with DSpace 7 REST APIGetting started with DSpace 7 REST API
Getting started with DSpace 7 REST API
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 

Embrace HTTP with ASP.NET Web API

  • 1. Embrace HTTP with ASP.NET Web API @filip_woj
  • 3. What is ASP.NET Web API? ● New Microsoft framework (RTM August 2012) for building HTTP services & applications ● Aimed at simplyfing and standardizing HTTP area on the MS stack (see: WCF / ASMX / MVC / HttpHandlers) ● Supports both REST and RPC style services ● Open source! @filip_woj
  • 4. But it's Microsoft! From: Scott Hanselman's “ONE ASP.NET” talk at aspconf 2012 @filip_woj
  • 5. Web API origins ● HTTP in WCF ● WCF REST starter kit ● WCF Web API ● finally adopted some concepts from ASP.NET MVC @filip_woj
  • 7. A mix of WCF Web API & MVC ● from WCF Web API: - content negotiation - message handlers - REST & dispatching based on HTTP verbs – code based configuration @filip_woj
  • 8. A mix of WCF & MVC ● from MVC: - model binding concept - controller based approach & RPC - routing - filters @filip_woj
  • 10. “ASP.NET” “Web API” ● The name creates lots of misconceptions ● “ASP.NET”: it doesn't require neither ASP.NET, nor IIS to run ● “Web API”: it's an HTTP framework, that can do much more than "just" API @filip_woj
  • 11. How can it work without ASP.NET/IIS? ● Web hosting: ASP.NET & IIS OWIN (i.e. Katana) ● Self hosting: (using WCF hardened core) WPF Windows service console app, any other .NET app ● Memory hosting: whole pipeline running in memory @filip_woj
  • 13. OK, but why would I need it? ● New HTTP object model ● Work with HTTP concepts ● HTTP as a fully fledged *application* protocol ● Facilitates both REST & RPC ● Async from top-to-bottom @filip_woj
  • 15. Async examples ● Handlers: Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken); ● Filters: Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation); ● Formatters: Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext); Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger); @filip_woj
  • 16. New HTTP object model ● Strongly typed HttpResponseMessage ● Strongly typed HttpRequestMessage ● Strongly typed Headers ● Strongly typed HttpContent ● No more “angle brackets coding” & magic strings ● Asynchronous API ● Client-server symmetry @filip_woj
  • 17. HTTP status codes ● 1xx – Informational ● 2xx – Successful ● 3xx – Redirection ● 4xx – Error on the client side ● 5xx – Error on the server side @filip_woj
  • 18. HTTP headers – request ● Request headers (selected) – Accept, Accept-Language, Accept-Encoding – Authorization, Cache-Control, Range – If-Match, If-Modified-Since, If-Range ● Content headers (selected) – Allow, Content-Encoding, Content-Language – Content-Length, Content-Type, Expires – Last-Modified @filip_woj
  • 19. HTTP headers – response ● Response headers (selected) – Accept-Ranges, Connection – Cache-control, Date, Etag – RetryAfter, Warning, Location ● Content headers (selected) – Allow, Content-Encoding, Content-Language – Content-Length, Content-Type, Expires – Last-Modified @filip_woj
  • 21. RPC ● /api/GetTeams ● /api/GetTeam?id=1 ● /api/GetPlayersByTeam?id=1 ● /api/AddTeam ● /api/UpdateTeam ● /api/UpdateTeam?id=1&name=”Leafs” ● /api/DeleteTeam?id=1 @filip_woj
  • 23. REST ● representational state transfer ● architecture for building systems by Roy Fielding ● advantages: stateless cachability hypermedia driven (client needs to know one link, usually) scalability everything addressable with URI @filip_woj
  • 24. From: presentation by @alexbeletsky @filip_woj
  • 25. HTTP verbs ● Represent CRUD on a resource: - GET: read, cachable, retreives a resource - POST: non-cacheable, creates a resource - PUT: updates a resource, safe to call multiple times - DELETE: deletes a resource, safe to call multiple times ● Can also use others i.e. PATCH (partial update of a resource) @filip_woj
  • 26. RESTful ● GET /api/teams ● GET /api/teams/1 ● GET /api/teams/1/players ● POST /api/teams ● PUT /api/teams/1 ● DELETE /api/teams/1 @filip_woj
  • 27. First API – GET public class TeamsController : ApiController { private readonly IUnitOfWork _uow; public TeamsController(IUnitOfWork uow){ _uow = uow; } public IEnumerable<Team> Get() { return _uow.Teams; } public Team Get(int id) { var team = _uow.Teams.FirstOrDefault(i => i.Id == id); if (team == null) throw new HttpResponseException(HttpStatusCode.NotFound); return team; } @filip_woj
  • 28. First API – POST public void Post(Team value) { if (!ModelState.IsValid) throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); _uow.Teams.Add(value); _uow.SaveChanges(); } @filip_woj
  • 29. First API – PUT public void Put(int id, Team value) { if (!ModelState.IsValid) throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); var team = _uow.Teams.FirstOrDefault(i => i.Id == id); if (team == null) throw new HttpResponseException(HttpStatusCode.NotFound); team.League = value.League; team.Name = value.Name; _uow.SaveChanges(); } @filip_woj
  • 30. First API – DELETE public void Delete(int id) { var team = _uow.Teams.FirstOrDefault(i => i.Id == id); if (team == null) throw new HttpResponseException(HttpStatusCode.NotFound); _uow.Teams.Remove(team); _uow.SaveChanges(); } } @filip_woj
  • 31. Demo: first API @filip_woj
  • 32. Content negotiation ● Dynamically deciding the media type ● Same data can be represented in various formats: - JSON – XML – CSV – binary – anything to what your data can be serialized/deserialized from ● In Web API done with MediaTypeFormatters @filip_woj
  • 33. Content negotiation in Web API ● Web API uses the following precedence: 1. MediaTypeMapping ● /api/resource.json, /api/resource?format=json 2. Accept headers ● Accept: application/json 3. Content type header ● Content-Type: text/xml 4. MediaTypeFormatter order & check whether a formatter can serialize/deserialize a given type @filip_woj
  • 34. So how my model gets serialized? ● Out of the box supports: - XML (DataContractSerializer / XmlSerializer) - JSON (DataContractSerializer / JSON.NET) - Form values (from client only, one-way) @filip_woj
  • 35. Extending content negotiation ● Very easy, some examples: - BSON (binary JSON) - ServiceStack.Text (instead of JSON.NET) - MessagePack - Mobi (returning ebook!) - RSS/Atom - Supporting Razor views (text/html) @filip_woj
  • 38. Message Handlers ● “Russian doll model” ● run first and last ● process raw HttpRequestMessage & HttpResponseMessage ● Ideal for generic tasks such as authentication or API usage logging ● Can be global or route-specific @filip_woj
  • 39. Client-server symmetry By: Henrik Frystyk Nielsen ● Message handlers can run on server and on the client ● HttpServer is a message handler itself @filip_woj
  • 40. Filters ● Conceptually same as in MVC ● Cached for performance (unlike MVC) ● Pre-action processing of raw HttpRequestMesage ● Post-action processing of raw HttpResponseMessage @filip_woj
  • 41. Controllers ● Represent your API resources ● Similar as in MVC ● Routing engine determines which controller to use ● Supports nested resources @filip_woj
  • 42. Dispatching actions ● By default HTTP verb based (RESTful) ● Actions matched: ● by prefix (i.e. GetAll, GetById) or ● by action attribute (i.e. [HttpPost]) ● Can be changed to action based (RPC style) @filip_woj
  • 44. Anything else? ● TDD, BDD – whole pipeline can run in memory ● Async from top-to-bottom – scales well ● Simple: figure out your resources, and build around them ● Next release (Feb 2013) will have OData support ● Integrates with SignalR @filip_woj
  • 45. Demo: first API – self hosted @filip_woj
  • 46. Demo: first API – memory hosted @filip_woj
  • 47. Demo: adding BSON formatter @filip_woj
  • 48. Demo: P2P in WPF @filip_woj
  • 49. Follow these guys @frystyk @glennblock @tourismgeek @darrel_miller @aliostad @benfosterdev @pwalat @pmhsfelix @filip_woj

Notes de l'éditeur

  1. – beta in Feb 2012, RC in June 202 – open source, just like Mvc, Entity Framework, part of azure – i&apos;m part of web api advisory board, assembled by Dan Roth from Microsoft, we meet every 2 weeks and discuss the new development ideas &amp; general direction of the product, – chief architect on the project is Henrik Nielsen, who in the early 1990s at CERN in Geneva, co-authored the HTTP spec and co-created th world wide web with Tim Berners Lee and the team
  2. – ASP.NET has a bad reputation, as being an unnecessary abstraction over the web and being HEAVY – MVC has changed that a bit, but still the perception remains – especilly now with the rise of new sexy technologies such as node.js or earlier rails – i&apos;d like to show you that MS can also make stuff that&apos;s good for the web, and lightweight
  3. – the root for HTTP services in the MS stack lies in WCF, and was very poor, with complex configuration, a lot of “angle bracket coding” and lots of runtime errors – this evolved with a few “out of band” releases such as REST starter kit, and eventually became WCF Web API – WCF Web API was already open source – then WCF and ASP.NET teams were merged and the result was Web API, as it adopted some concepts from MVC – this lowers the barriers of entry for MVC developers, who&apos;d instantly be familiar with the Web API way of building services because they know it from MVC
  4. – content negotiation – so the process of determining the response media type based on request message – and opposite determining how to read the payload of the incoming request – message handlers – which run first and last in the stack and allow you to work with raw HTTP objects – RESTful approach (as opposed to traditional RPC) – the configuration process of Web API is based on how configuration was done in WCF web api and does not require XML files
  5. – the concept of model binding. While Web API does model binding completely differently than MVC, conceptually the task is the same – controller centric approach, where each resource (also called API endpoint) is a controller – ASP.NET routing; the routetable has been ported so that it can work outside of ASP.NET as well – filters which run before and after an action – dependency injection was already supported in WCF Web API, but they way it&apos;s implemented, almost mirrors how it&apos;s done ine MVC
  6. – here is the problem – naming things is difficult, and in the case of Web API it creates lots of problems
  7. – Web API can be hosted in IIS, on top of ASP.NET but it&apos;s not a requirement – Web API is a fully fledged framework, not just API tool. You can do whatever you&apos;d expect from a web framework including handle binary files, handle state if needed, even serve HTML files with Razor engine
  8. – 3 hosting options – web hosting is on top of ASP.NET and can be in IIS but it doesn&apos;t have to, it can also be hosted with any OWIN (open web interface for .NET) implementation such as Katana. I blogged about that – self hosting means spinning up a web server inside of the managed process we are running (using WCF hardened core which wraps around httplistener). This can be done from any .NET app – memory hosting means running th whole pipeline in memory without using netowrk hardware. You can create an instance of HttpServer and send data from HttpClient directly to it in memory
  9. – does not have the baggage of .NET 1.1 on whch Web Forms and MVC are built!
  10. – new HTTP programming model has been introduced in .NET 4.5, but Web API team backported a lot of the stuff to .NET 4.0 – replaces old stuff from .NET 1.1 and System.Web, which started to show its age, and a lot of its concepts were synchronous and string based – HTTP as a first class citizen; – you get to embrace HTTP and you get a lot of things for free such as caching at various intermediary levels. You also don&apos;t have to reinvent the wheel with operation statuses and such – with REST you follow the standards – client and server work with same objects – whole pipeline is async (as opposed to MVC or other frmwks). In MVC controllers are async but not pipeline. This means it scales well
  11. – NancyFX, ServiceStack – built around IhttpHandler and are fully synchronous
  12. – symmetrical between client and server – pretty much everything you can imagine about HTTP – from headers, through body content to response &amp; request themselves are strongly typed – no static configuration – fully asynchrnous – not just for sending messages, but even for tasks such s reading the request.response body – very flexible in terms of extending media type support
  13. – symmetrical between client and server – pretty much everything you can imagine about HTTP – from headers, through body content to response &amp; request themselves are strongly typed – no static configuration – fully asynchrnous – not just for sending messages, but even for tasks such s reading the request.response body – very flexible in terms of extending media type support
  14. – traditional model, familiar from perhaps ASMX or MVC – call server methods by name – gets messy
  15. – is shit
  16. – REST is probably the most verused buzz word in the web world – but has several advantages, mainly cause it&apos;s standard – STATELESS – no session, so for example as an authenticated user, you have to sign requests and reauthenticate each time – true REST should be hypermedia driven with a one entry point to the application and navigational properties – you build around HTTP VERBs NEXT SLIDE
  17. – cornerstone of any REST system – standard
  18. – now we can see the same API as before, but in a RESTful manner. You can see it&apos;s much cleaner, readable and maintainable – also much more discoverable
  19. – content negotiation is a two-way process, it can determine the format (media type) of a response based on the request – it can also determine how to deserialize the incoming request – there are countless examples of media types, two most popular ones are XML &amp; JSON – media type don&apos;t have to support read and write for example RSS is read only
  20. – media type mappings allow you define extension i.e. .json or querystring paramter i.e. ?format=json – accept headers are sent by default by i.e. The browser &apos;text/html&apos; – content-type headers come in play when client sens in some data, for example on POST or PUT. If there is data coming back, it wil be symmetrically formatted – finally the mediatypeformatter order and JSON is default. Web API will also check if the given Type is supported by the formatter. Like we said, RSS is write only and FormData read only
  21. – out of the box web API has 3 formatters, but form is read only – XML &amp; JSON are universal
  22. – when it comes to reading data is a bit more compllicated since data can also come from URI – QS and route data – this type of data is read using model binders not media type formatters – formatters only scan the body, normally for complex types (eve though primitives can also be sent) – body in Web API can only be read once, that&apos;s for performance reasons. – in MVC the whole body was buffered into memoery. Now imagine a request that has an body of 400MB of upload data – can cause server instability
  23. – web api formatter collection can be super easily extended
  24. – the whole point is to abstract away the request/response format from the actual action which should work with CLR types
  25. – what&apos;s important here are the colors. – message handlers run before anything else, they process raw request and are perfect for things like API usage logging or authentication – handlers can run on specific routes only if needed – think public/prvate API – filters run before controller actions – then the action runs – and the process reverses – so whatever ran first, runs last All in all this is called the russion doll model
  26. So maybe we dont need the chart
  27. – mesage handlers dont exist in MVC – suitable for generic tasks applicable for entire or part of your API – filters do the same except they apply to individual action – architecturaly, handlers are singletons so it creates additional considerations when it comes to DI and so on
  28. – filters allow you do to pre/post processing – perfect for applying repeated logic such as checking model state or checking the incoming request for null values – you can have many filters
  29. – the default dispatched is RESTful – your actions don&apos;t have to be named as HTTP verbs, but should be prefixed by the HTTP verb – alternatively you can use the attribute
  30. – in the original ASP.NET web forms nothing was extendible it then started changning, later versions were much better – the big strength about Web API is that you can replace almost everything in the framework – entire content negotiation engine (remember the slide where i showed the order of precendece) this entire logic can be scraped. – model binding can be customized, and changed to i.e. MVC style binding if you want – you can plug in any DI container – you can plug in any logging framework, even for the internal tracing
  31. – because of memoery hosting, Web API facilitates very well TDD, BDD – asynchrony is very important as it increases your overall thgroughput – beauty in simplicity – Odata is MS data exchange protocol. I.e. Netflix API supports it and it&apos;s great for querying data – works well with signalr for realtime apps, so you can have an app which i.e. Adds an order through POST and immediately notifies the connected clients about the new order