SlideShare uma empresa Scribd logo
1 de 31
ASP.NET WEB API

          @thangchung
           08-08-2012
Agenda
•   A model of restful maturity
•   ASP.NET Web API
•   Mapping from WCF to Web API
•   Integrated stack supporting features
•   What we do in BC Survey project
A model of restful maturity
• Restful coined by Roy Thomas Fielding in his
  dissesertation (2000)
• A model of restful maturity introduced by
  Leonard Richardson (2008)
• The glory of REST by Martin Fowler (2010)
• We have 4 levels of maturity
  –   Level 0: The swamp of POX (Plain Old XML)
  –   Level 1: Resources
  –   Level 2: HTTP verbs
  –   Level 3: Hypermedia Controls
Level 0: The swamp of POX
• Use RPC (Remote Procedure Invocation)




• POST /appointmentService HTTP/1.1 [various
  other headers]
     <openSlotRequest date = "2010-01-04" doctor =
          "mjones"/>
• The server return an open slot list as
   HTTP/1.1 200 OK [various headers]
      <openSlotList>
       <slot start = "1400" end = "1450">
             <doctor id = “mjones”/>
       </slot>
       <slot start = "1600" end = "1650">
             <doctor id = “mjones”/>
       </slot>
     </openSlotList>
• We choose the the first item and send it to server:
   POST /appointmentService HTTP/1.1 [various other headers]
      <appointmentRequest>
             <slot doctor = "mjones" start = "1400" end =
                     "1450"/>
             <patient id = "jsmith"/>
      </appointmentRequest>
• The server accept this request and register
  name of patient
  HTTP/1.1 200 OK [various headers]
     <appointment>
      <slot doctor = "mjones" start = "1400" end = "1450"/>
      <patient id = "jsmith"/>
     </appointment>
• If some thing wrong, the result should be
  HTTP/1.1 200 OK [various headers]
  <appointmentRequestFailure>
     <slot doctor = "mjones" start = "1400" end = "1450"/>
     <patient id = "jsmith"/>
     <reason>Slot not available</reason>
     </appointmentRequestFailure>
Level 1: Resources
• POST /doctors/mjones HTTP/1.1 [various
  other headers]
  <openSlotRequest date = "2010-01-04"/>
• HTTP/1.1 200 OK [various headers]
  <openSlotList>
   <slot id = "1234" doctor = "mjones" start = "1400"
            end = "1450"/>
   <slot id = "5678" doctor = "mjones" start = "1600"
            end = "1650"/>
  </openSlotList>
• POST /slots/1234 HTTP/1.1 [various other
  headers]
  <appointmentRequest>
     <patient id = "jsmith"/>
  </appointmentRequest>
• HTTP/1.1 200 OK [various headers]
  <appointment>
   <slot id = "1234" doctor = "mjones" start = "1400"
     end = "1450"/>
   <patient id = "jsmith"/>
  </appointment>
• The link at the moment should be like this
  – http://royalhope.nhs.uk/slots/1234/appointment
Level 2: HTTP Verbs
• GET/POST/PUT/DELETE
• Use GET
 /doctors/mjones/slots?date=20100104&status=open
  HTTP/1.1 Host: royalhope.nhs.uk
• HTTP/1.1 200 OK [various headers]
  <openSlotList>
     <slot id = "1234" doctor = "mjones" start = "1400"
            end = "1450"/>
     <slot id = "5678" doctor = "mjones" start = "1600"
            end = "1650"/>
  </openSlotList>
• POST /slots/1234 HTTP/1.1 [various other
  headers]
  <appointmentRequest>
     <patient id = "jsmith"/>
  </appointmentRequest>
• HTTP/1.1 201 Created Location:
  slots/1234/appointment [various headers]
  <appointment>
     <slot id = "1234" doctor = "mjones" start =
            "1400" end = "1450"/>
     <patient id = "jsmith"/>
  </appointment>
• If something wrong when we use POST to
  server, the result should be
  HTTP/1.1 409 Conflict [various headers]
  <openSlotList>
     <slot id = "5678" doctor = "mjones" start =
            "1600" end = "1650"/>
  </openSlotList>
• Benefits:
  – Caching on GET request (natural capability with
    HTTP protocol)
Level 3: Hypermedia Controls
• HATEOAS (Hypertext As The Engine Of
  Application State)
• GET
  /doctors/mjones/slots?date=20100104&status=o
  pen HTTP/1.1 Host: royalhope.nhs.uk
• HTTP/1.1 200 OK [various headers]
  <openSlotList>
     <slot id = "1234" doctor = "mjones" start = "1400"
             end = "1450">
      <link rel = "/linkrels/slot/book" uri =
             "/slots/1234"/>
     </slot>
     <slot id = "5678" doctor = "mjones" start = "1600"
             end = "1650">
      <link rel = "/linkrels/slot/book" uri =
             "/slots/5678"/>
     </slot>
  </openSlotList>
• POST /slots/1234 HTTP/1.1 [various other
  headers]
  <appointmentRequest>
     <patient id = "jsmith"/>
  </appointmentRequest>
• HTTP/1.1 201 Created Location:
   http://royalhope.nhs.uk/slots/1234/appointment [various headers]
  <appointment>
   <slot id = "1234" doctor = "mjones" start = "1400" end = "1450"/>
        <patient id = "jsmith"/>
        <link rel = "/linkrels/appointment/cancel" uri =
                  "/slots/1234/appointment"/>
        <link rel = "/linkrels/appointment/addTest" uri =
                  "/slots/1234/appointment/tests"/>
        <link rel = "self" uri = "/slots/1234/appointment"/>
        <link rel = "/linkrels/appointment/changeTime" uri =
"/doctors/mjones/slots?date=20100104@status=open"/>
        <link rel = "/linkrels/appointment/updateContactInfo" uri =
"/patients/jsmith/contactInfo"/>
        <link rel = "/linkrels/help" uri = "/help/appointment"/>
  </appointment>


• What’s benefit of those?
ASP.NET Web API
• What is the purpose of the WebAPIs?
• Why do we need REST HTTP services? What’s
  wrong with SOAP-over-HTTP?
• Why did the WebAPIs move from WCF to
  ASP.NET MVC?
• Is there still a use for WCF? When should I
  choose Web APIs over WCF?
Mapping from WCF to Web API
•   WCF Web AP -> ASP.NET Web API
•   Service -> Web API controller
•   Operation -> Action
•   Service contract -> Not applicable
•   Endpoint -> Not applicable
•   URI templates -> ASP.NET Routing
•   Message handlers -> Same
•   Formatters -> Same
•   Operation handlers -> Filters, model binders
Integrated stack supporting features
• Modern HTTP programming model
• Full support for ASP.NET Routing
• Content negotiation and custom formatters
• Model binding and validation
• Filters
• Query composition
• Easy to unit test
• Improved Inversion of Control (IoC) via
  DependencyResolver
• Code-based configuration
• Self-host
What we do in BC Survey project
•   Introduced Web API service
•   Web API routing and actions
•   Working with HTTP (Verb & return status)
•   Format & model binding
•   Dependency Resolver with Autofac
•   Web API clients
•   Host ASP.NET Web API on IIS
Web API service
public class SurveyAPIController : BaseApiController
{
  // GET api/Survey
  [Queryable]
  public IQueryable<SurveyDTO> Get()          {
    return _surveyAppService.GetAllSurvey().AsQueryable();
  }
  // GET api/Survey/5
  public SurveyDTO Get(int id) { … }
    // POST api/Survey
    public HttpResponseMessage Post(SurveyDTO value) { … }
    // PUT api/Survey/5
    public HttpResponseMessage Put(int id, SurveyDTO value) { … }
    // DELETE api/Survey/5
    public HttpResponseMessage Delete(int id) {… }
}
Web API service
• OData (Open data protocol): The Open Data
  Protocol is an open web protocol for querying
  and updating data. The protocol allows for a
  consumer to query a datasource over the
  HTTP protocol and get the result back in
  formats like Atom, JSON or plain XML,
  including pagination, ordering or filtering of
  the data.
Web API routing and actions
• routes.MapHttpRoute("DefaultApi",
      "api/{controller}/{id}", new { id =
      RouteParameter.Optional });
MapHttpRoute really different from default
routing in ASP.NET MVC
• routes.MapRoute("Default",
      "{controller}/{action}/{id}", new {
      controller = "Home", action = "Index", id =
      UrlParameter.Optional });
Working with HTTP (Verb & return
                status)
• It have 9 method definitions like
   –   GET
   –   HEAD
   –   POST
   –   PUT
   –   DELETE
   –   TRACE
   –   CONNECT
• We can reference more at
  http://www.w3.org/Protocols/rfc2616/rfc2616-
  sec9.html
Working with HTTP (Verb & return
                  status)
•   200 OK
•   201 Created
•   400 Bad Request
•   401 Unauthorized
•   404 Not Found
•   409 Conflict
•   500 Internal Server Error
•   501 Not Implemented
•   Reference more at
    http://en.wikipedia.org/wiki/List_of_HTTP_status_cod
    es
Format & model binding
• Media-Type Formatters
     // Remove the XML formatter
     config.Formatters.Remove(config.Formatters.XmlF
            ormatter);
     var json = config.Formatters.JsonFormatter;
     json.SerializerSettings.DateFormatHandling =
            DateFormatHandling.MicrosoftDateFormat;
     json.SerializerSettings.Formatting =
            Formatting.Indented;
• Content Negotiation
• Model Validation in ASP.NET Web API
Dependency Resolver with Autofac
var builder = new ContainerBuilder();
 // register autofac modules
builder.RegisterModule<WebModule>();
builder.RegisterModule<DataSurveyModule>();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterFilterProvider();

var container = builder.Build();
DependencyResolver.SetResolver(new
AutofacDependencyResolver(container));
Q&A
References
• http://www.ics.uci.edu/~fielding/pubs/dissert
  ation/top.htm
• http://www.crummy.com/writing/speaking/2
  008-QCon/act3.html
• http://martinfowler.com/articles/richardsonM
  aturityModel.html
• http://www.asp.net/web-api/

Mais conteúdo relacionado

Mais procurados

Comandos utilizados en sql
Comandos utilizados en sqlComandos utilizados en sql
Comandos utilizados en sqlByron Eras
 
Historia de la tecnologia de base de datos
Historia de la tecnologia de base de datosHistoria de la tecnologia de base de datos
Historia de la tecnologia de base de datosralbarracin
 
Uso de Excepciones en JAVA
Uso de Excepciones en JAVAUso de Excepciones en JAVA
Uso de Excepciones en JAVAinnovalabcun
 
HISTORIA DE LAS BASES DE DATOS
HISTORIA DE LAS BASES DE DATOSHISTORIA DE LAS BASES DE DATOS
HISTORIA DE LAS BASES DE DATOSdfgdfgs
 
Unidad 1. Fundamentos de Base de Datos
Unidad 1. Fundamentos de Base de DatosUnidad 1. Fundamentos de Base de Datos
Unidad 1. Fundamentos de Base de Datoshugodanielgd
 
Sql DML Lenguaje de manipulación de datos
Sql DML Lenguaje de manipulación de datos Sql DML Lenguaje de manipulación de datos
Sql DML Lenguaje de manipulación de datos josecuartas
 
Presentación tcp y udp
Presentación tcp y udpPresentación tcp y udp
Presentación tcp y udpgonsu90
 
Metodologías Para AnáLisis Y DiseñO Orientado A Objetos
Metodologías Para AnáLisis Y DiseñO Orientado A ObjetosMetodologías Para AnáLisis Y DiseñO Orientado A Objetos
Metodologías Para AnáLisis Y DiseñO Orientado A Objetoshector_h30
 
Diagramas de Clases, Secuencia, Patrones de Diseño MVC, Disño de Interfaces d...
Diagramas de Clases, Secuencia, Patrones de Diseño MVC, Disño de Interfaces d...Diagramas de Clases, Secuencia, Patrones de Diseño MVC, Disño de Interfaces d...
Diagramas de Clases, Secuencia, Patrones de Diseño MVC, Disño de Interfaces d...Oswaldo Hernández
 
Manejo de archivos en JAVA
Manejo de archivos en JAVAManejo de archivos en JAVA
Manejo de archivos en JAVAMichelle Torres
 
Dispositivos De Interconexión de Redes
Dispositivos De Interconexión de  RedesDispositivos De Interconexión de  Redes
Dispositivos De Interconexión de RedesUABC
 

Mais procurados (20)

Comandos utilizados en sql
Comandos utilizados en sqlComandos utilizados en sql
Comandos utilizados en sql
 
Interconexión redes
Interconexión redesInterconexión redes
Interconexión redes
 
Historia de la tecnologia de base de datos
Historia de la tecnologia de base de datosHistoria de la tecnologia de base de datos
Historia de la tecnologia de base de datos
 
Uso de Excepciones en JAVA
Uso de Excepciones en JAVAUso de Excepciones en JAVA
Uso de Excepciones en JAVA
 
HISTORIA DE LAS BASES DE DATOS
HISTORIA DE LAS BASES DE DATOSHISTORIA DE LAS BASES DE DATOS
HISTORIA DE LAS BASES DE DATOS
 
Metodologiasad 1
Metodologiasad 1Metodologiasad 1
Metodologiasad 1
 
Unidad 1. Fundamentos de Base de Datos
Unidad 1. Fundamentos de Base de DatosUnidad 1. Fundamentos de Base de Datos
Unidad 1. Fundamentos de Base de Datos
 
DIRECCIONAMIENTO IP BASICO I
DIRECCIONAMIENTO IP BASICO IDIRECCIONAMIENTO IP BASICO I
DIRECCIONAMIENTO IP BASICO I
 
Sql DML Lenguaje de manipulación de datos
Sql DML Lenguaje de manipulación de datos Sql DML Lenguaje de manipulación de datos
Sql DML Lenguaje de manipulación de datos
 
Routers CIsco: configu
Routers CIsco: configuRouters CIsco: configu
Routers CIsco: configu
 
Ado net
Ado netAdo net
Ado net
 
Lenguaje SQL
Lenguaje SQLLenguaje SQL
Lenguaje SQL
 
Presentación tcp y udp
Presentación tcp y udpPresentación tcp y udp
Presentación tcp y udp
 
Sql
SqlSql
Sql
 
Java con base de datos
Java con base de datosJava con base de datos
Java con base de datos
 
Metodologías Para AnáLisis Y DiseñO Orientado A Objetos
Metodologías Para AnáLisis Y DiseñO Orientado A ObjetosMetodologías Para AnáLisis Y DiseñO Orientado A Objetos
Metodologías Para AnáLisis Y DiseñO Orientado A Objetos
 
Diagramas de Clases, Secuencia, Patrones de Diseño MVC, Disño de Interfaces d...
Diagramas de Clases, Secuencia, Patrones de Diseño MVC, Disño de Interfaces d...Diagramas de Clases, Secuencia, Patrones de Diseño MVC, Disño de Interfaces d...
Diagramas de Clases, Secuencia, Patrones de Diseño MVC, Disño de Interfaces d...
 
Manejo de archivos en JAVA
Manejo de archivos en JAVAManejo de archivos en JAVA
Manejo de archivos en JAVA
 
Dispositivos De Interconexión de Redes
Dispositivos De Interconexión de  RedesDispositivos De Interconexión de  Redes
Dispositivos De Interconexión de Redes
 
Modelo de datos
Modelo de datosModelo de datos
Modelo de datos
 

Destaque

ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
C# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENTC# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENTDr. Awase Khirni Syed
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiTiago Knoch
 
The ASP.NET Web API for Beginners
The ASP.NET Web API for BeginnersThe ASP.NET Web API for Beginners
The ASP.NET Web API for BeginnersKevin Hazzard
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsIdo Flatow
 
Overview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB APIOverview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB APIPankaj Bajaj
 
Web API or WCF - An Architectural Comparison
Web API or WCF - An Architectural ComparisonWeb API or WCF - An Architectural Comparison
Web API or WCF - An Architectural ComparisonAdnan Masood
 
WCF tutorial
WCF tutorialWCF tutorial
WCF tutorialAbhi Arya
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web APIBrad Genereaux
 
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIThe Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIEyal Vardi
 
RESTful API Design Best Practices Using ASP.NET Web API
RESTful API Design Best Practices Using ASP.NET Web APIRESTful API Design Best Practices Using ASP.NET Web API
RESTful API Design Best Practices Using ASP.NET Web API💻 Spencer Schneidenbach
 
Secure Coding for NodeJS
Secure Coding for NodeJSSecure Coding for NodeJS
Secure Coding for NodeJSThang Chung
 
Passport Nodejs Lightening Talk
Passport Nodejs Lightening TalkPassport Nodejs Lightening Talk
Passport Nodejs Lightening TalkKianosh Pourian
 
ASP.NET Core 1 for MVC- and WebAPI-Devs
ASP.NET Core 1 for MVC- and WebAPI-DevsASP.NET Core 1 for MVC- and WebAPI-Devs
ASP.NET Core 1 for MVC- and WebAPI-DevsManfred Steyer
 
ASP.NET - Architecting single page applications with knockout.js
ASP.NET - Architecting single page applications with knockout.jsASP.NET - Architecting single page applications with knockout.js
ASP.NET - Architecting single page applications with knockout.jsDimitar Danailov
 
Web Technologies
Web TechnologiesWeb Technologies
Web TechnologiesLior Zamir
 

Destaque (20)

ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
C# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENTC# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENT
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
 
The ASP.NET Web API for Beginners
The ASP.NET Web API for BeginnersThe ASP.NET Web API for Beginners
The ASP.NET Web API for Beginners
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
 
Overview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB APIOverview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB API
 
Web API or WCF - An Architectural Comparison
Web API or WCF - An Architectural ComparisonWeb API or WCF - An Architectural Comparison
Web API or WCF - An Architectural Comparison
 
Excellent rest using asp.net web api
Excellent rest using asp.net web apiExcellent rest using asp.net web api
Excellent rest using asp.net web api
 
Web api
Web apiWeb api
Web api
 
WCF tutorial
WCF tutorialWCF tutorial
WCF tutorial
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIThe Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
 
RESTful API Design Best Practices Using ASP.NET Web API
RESTful API Design Best Practices Using ASP.NET Web APIRESTful API Design Best Practices Using ASP.NET Web API
RESTful API Design Best Practices Using ASP.NET Web API
 
Introduction to asp.net web api
Introduction to asp.net web apiIntroduction to asp.net web api
Introduction to asp.net web api
 
Secure Coding for NodeJS
Secure Coding for NodeJSSecure Coding for NodeJS
Secure Coding for NodeJS
 
Passport Nodejs Lightening Talk
Passport Nodejs Lightening TalkPassport Nodejs Lightening Talk
Passport Nodejs Lightening Talk
 
ASP.NET Core 1 for MVC- and WebAPI-Devs
ASP.NET Core 1 for MVC- and WebAPI-DevsASP.NET Core 1 for MVC- and WebAPI-Devs
ASP.NET Core 1 for MVC- and WebAPI-Devs
 
Web 2.0 y nube de internet
Web 2.0 y nube de internetWeb 2.0 y nube de internet
Web 2.0 y nube de internet
 
ASP.NET - Architecting single page applications with knockout.js
ASP.NET - Architecting single page applications with knockout.jsASP.NET - Architecting single page applications with knockout.js
ASP.NET - Architecting single page applications with knockout.js
 
Web Technologies
Web TechnologiesWeb Technologies
Web Technologies
 

Semelhante a ASP.NET WEB API

Rest in practice
Rest in practiceRest in practice
Rest in practiceGabor Torok
 
REST and Web API
REST and Web APIREST and Web API
REST and Web APIIT Weekend
 
About REST. Архитектурные семинары Softengi
About REST. Архитектурные семинары SoftengiAbout REST. Архитектурные семинары Softengi
About REST. Архитектурные семинары SoftengiSoftengi
 
Webservices Overview : XML RPC, SOAP and REST
Webservices Overview : XML RPC, SOAP and RESTWebservices Overview : XML RPC, SOAP and REST
Webservices Overview : XML RPC, SOAP and RESTPradeep Kumar
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
ERRest - Designing a good REST service
ERRest - Designing a good REST serviceERRest - Designing a good REST service
ERRest - Designing a good REST serviceWO Community
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
Android App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web ServicesAndroid App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web ServicesAnuchit Chalothorn
 
RESTful services
RESTful servicesRESTful services
RESTful servicesgouthamrv
 
Constraints Make You Sexy - What is Rest
Constraints Make You Sexy  - What is RestConstraints Make You Sexy  - What is Rest
Constraints Make You Sexy - What is Restanorqiu
 
A Quick Introduction to YQL
A Quick Introduction to YQLA Quick Introduction to YQL
A Quick Introduction to YQLMax Manders
 
Velocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web appsVelocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web appsandrewsmatt
 
Boost Your Content Strategy for REST APIs with Gururaj BS
Boost Your Content Strategy for REST APIs with Gururaj BSBoost Your Content Strategy for REST APIs with Gururaj BS
Boost Your Content Strategy for REST APIs with Gururaj BSInformation Development World
 
Introduction to rest using flask
Introduction to rest using flaskIntroduction to rest using flask
Introduction to rest using flaskWekanta
 
01. http basics v27
01. http basics v2701. http basics v27
01. http basics v27Eoin Keary
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdfArumugam90
 

Semelhante a ASP.NET WEB API (20)

Rest in practice
Rest in practiceRest in practice
Rest in practice
 
REST and Web API
REST and Web APIREST and Web API
REST and Web API
 
REST and Web API
REST and Web APIREST and Web API
REST and Web API
 
About REST. Архитектурные семинары Softengi
About REST. Архитектурные семинары SoftengiAbout REST. Архитектурные семинары Softengi
About REST. Архитектурные семинары Softengi
 
Webservices Overview : XML RPC, SOAP and REST
Webservices Overview : XML RPC, SOAP and RESTWebservices Overview : XML RPC, SOAP and REST
Webservices Overview : XML RPC, SOAP and REST
 
Rest
RestRest
Rest
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
ERRest - Designing a good REST service
ERRest - Designing a good REST serviceERRest - Designing a good REST service
ERRest - Designing a good REST service
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Android App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web ServicesAndroid App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web Services
 
RESTful services
RESTful servicesRESTful services
RESTful services
 
Constraints Make You Sexy - What is Rest
Constraints Make You Sexy  - What is RestConstraints Make You Sexy  - What is Rest
Constraints Make You Sexy - What is Rest
 
Doing REST Right
Doing REST RightDoing REST Right
Doing REST Right
 
From unREST to REST
From unREST to RESTFrom unREST to REST
From unREST to REST
 
A Quick Introduction to YQL
A Quick Introduction to YQLA Quick Introduction to YQL
A Quick Introduction to YQL
 
Velocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web appsVelocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web apps
 
Boost Your Content Strategy for REST APIs with Gururaj BS
Boost Your Content Strategy for REST APIs with Gururaj BSBoost Your Content Strategy for REST APIs with Gururaj BS
Boost Your Content Strategy for REST APIs with Gururaj BS
 
Introduction to rest using flask
Introduction to rest using flaskIntroduction to rest using flask
Introduction to rest using flask
 
01. http basics v27
01. http basics v2701. http basics v27
01. http basics v27
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 

Último

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 

Último (20)

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

ASP.NET WEB API

  • 1. ASP.NET WEB API @thangchung 08-08-2012
  • 2. Agenda • A model of restful maturity • ASP.NET Web API • Mapping from WCF to Web API • Integrated stack supporting features • What we do in BC Survey project
  • 3. A model of restful maturity • Restful coined by Roy Thomas Fielding in his dissesertation (2000) • A model of restful maturity introduced by Leonard Richardson (2008) • The glory of REST by Martin Fowler (2010) • We have 4 levels of maturity – Level 0: The swamp of POX (Plain Old XML) – Level 1: Resources – Level 2: HTTP verbs – Level 3: Hypermedia Controls
  • 4.
  • 5. Level 0: The swamp of POX • Use RPC (Remote Procedure Invocation) • POST /appointmentService HTTP/1.1 [various other headers] <openSlotRequest date = "2010-01-04" doctor = "mjones"/>
  • 6. • The server return an open slot list as HTTP/1.1 200 OK [various headers] <openSlotList> <slot start = "1400" end = "1450"> <doctor id = “mjones”/> </slot> <slot start = "1600" end = "1650"> <doctor id = “mjones”/> </slot> </openSlotList> • We choose the the first item and send it to server: POST /appointmentService HTTP/1.1 [various other headers] <appointmentRequest> <slot doctor = "mjones" start = "1400" end = "1450"/> <patient id = "jsmith"/> </appointmentRequest>
  • 7. • The server accept this request and register name of patient HTTP/1.1 200 OK [various headers] <appointment> <slot doctor = "mjones" start = "1400" end = "1450"/> <patient id = "jsmith"/> </appointment> • If some thing wrong, the result should be HTTP/1.1 200 OK [various headers] <appointmentRequestFailure> <slot doctor = "mjones" start = "1400" end = "1450"/> <patient id = "jsmith"/> <reason>Slot not available</reason> </appointmentRequestFailure>
  • 9. • POST /doctors/mjones HTTP/1.1 [various other headers] <openSlotRequest date = "2010-01-04"/> • HTTP/1.1 200 OK [various headers] <openSlotList> <slot id = "1234" doctor = "mjones" start = "1400" end = "1450"/> <slot id = "5678" doctor = "mjones" start = "1600" end = "1650"/> </openSlotList>
  • 10. • POST /slots/1234 HTTP/1.1 [various other headers] <appointmentRequest> <patient id = "jsmith"/> </appointmentRequest> • HTTP/1.1 200 OK [various headers] <appointment> <slot id = "1234" doctor = "mjones" start = "1400" end = "1450"/> <patient id = "jsmith"/> </appointment> • The link at the moment should be like this – http://royalhope.nhs.uk/slots/1234/appointment
  • 11. Level 2: HTTP Verbs • GET/POST/PUT/DELETE
  • 12. • Use GET /doctors/mjones/slots?date=20100104&status=open HTTP/1.1 Host: royalhope.nhs.uk • HTTP/1.1 200 OK [various headers] <openSlotList> <slot id = "1234" doctor = "mjones" start = "1400" end = "1450"/> <slot id = "5678" doctor = "mjones" start = "1600" end = "1650"/> </openSlotList>
  • 13. • POST /slots/1234 HTTP/1.1 [various other headers] <appointmentRequest> <patient id = "jsmith"/> </appointmentRequest> • HTTP/1.1 201 Created Location: slots/1234/appointment [various headers] <appointment> <slot id = "1234" doctor = "mjones" start = "1400" end = "1450"/> <patient id = "jsmith"/> </appointment>
  • 14. • If something wrong when we use POST to server, the result should be HTTP/1.1 409 Conflict [various headers] <openSlotList> <slot id = "5678" doctor = "mjones" start = "1600" end = "1650"/> </openSlotList> • Benefits: – Caching on GET request (natural capability with HTTP protocol)
  • 15. Level 3: Hypermedia Controls • HATEOAS (Hypertext As The Engine Of Application State)
  • 16. • GET /doctors/mjones/slots?date=20100104&status=o pen HTTP/1.1 Host: royalhope.nhs.uk • HTTP/1.1 200 OK [various headers] <openSlotList> <slot id = "1234" doctor = "mjones" start = "1400" end = "1450"> <link rel = "/linkrels/slot/book" uri = "/slots/1234"/> </slot> <slot id = "5678" doctor = "mjones" start = "1600" end = "1650"> <link rel = "/linkrels/slot/book" uri = "/slots/5678"/> </slot> </openSlotList>
  • 17. • POST /slots/1234 HTTP/1.1 [various other headers] <appointmentRequest> <patient id = "jsmith"/> </appointmentRequest>
  • 18. • HTTP/1.1 201 Created Location: http://royalhope.nhs.uk/slots/1234/appointment [various headers] <appointment> <slot id = "1234" doctor = "mjones" start = "1400" end = "1450"/> <patient id = "jsmith"/> <link rel = "/linkrels/appointment/cancel" uri = "/slots/1234/appointment"/> <link rel = "/linkrels/appointment/addTest" uri = "/slots/1234/appointment/tests"/> <link rel = "self" uri = "/slots/1234/appointment"/> <link rel = "/linkrels/appointment/changeTime" uri = "/doctors/mjones/slots?date=20100104@status=open"/> <link rel = "/linkrels/appointment/updateContactInfo" uri = "/patients/jsmith/contactInfo"/> <link rel = "/linkrels/help" uri = "/help/appointment"/> </appointment> • What’s benefit of those?
  • 19. ASP.NET Web API • What is the purpose of the WebAPIs? • Why do we need REST HTTP services? What’s wrong with SOAP-over-HTTP? • Why did the WebAPIs move from WCF to ASP.NET MVC? • Is there still a use for WCF? When should I choose Web APIs over WCF?
  • 20. Mapping from WCF to Web API • WCF Web AP -> ASP.NET Web API • Service -> Web API controller • Operation -> Action • Service contract -> Not applicable • Endpoint -> Not applicable • URI templates -> ASP.NET Routing • Message handlers -> Same • Formatters -> Same • Operation handlers -> Filters, model binders
  • 21. Integrated stack supporting features • Modern HTTP programming model • Full support for ASP.NET Routing • Content negotiation and custom formatters • Model binding and validation • Filters • Query composition • Easy to unit test • Improved Inversion of Control (IoC) via DependencyResolver • Code-based configuration • Self-host
  • 22. What we do in BC Survey project • Introduced Web API service • Web API routing and actions • Working with HTTP (Verb & return status) • Format & model binding • Dependency Resolver with Autofac • Web API clients • Host ASP.NET Web API on IIS
  • 23. Web API service public class SurveyAPIController : BaseApiController { // GET api/Survey [Queryable] public IQueryable<SurveyDTO> Get() { return _surveyAppService.GetAllSurvey().AsQueryable(); } // GET api/Survey/5 public SurveyDTO Get(int id) { … } // POST api/Survey public HttpResponseMessage Post(SurveyDTO value) { … } // PUT api/Survey/5 public HttpResponseMessage Put(int id, SurveyDTO value) { … } // DELETE api/Survey/5 public HttpResponseMessage Delete(int id) {… } }
  • 24. Web API service • OData (Open data protocol): The Open Data Protocol is an open web protocol for querying and updating data. The protocol allows for a consumer to query a datasource over the HTTP protocol and get the result back in formats like Atom, JSON or plain XML, including pagination, ordering or filtering of the data.
  • 25. Web API routing and actions • routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }); MapHttpRoute really different from default routing in ASP.NET MVC • routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
  • 26. Working with HTTP (Verb & return status) • It have 9 method definitions like – GET – HEAD – POST – PUT – DELETE – TRACE – CONNECT • We can reference more at http://www.w3.org/Protocols/rfc2616/rfc2616- sec9.html
  • 27. Working with HTTP (Verb & return status) • 200 OK • 201 Created • 400 Bad Request • 401 Unauthorized • 404 Not Found • 409 Conflict • 500 Internal Server Error • 501 Not Implemented • Reference more at http://en.wikipedia.org/wiki/List_of_HTTP_status_cod es
  • 28. Format & model binding • Media-Type Formatters // Remove the XML formatter config.Formatters.Remove(config.Formatters.XmlF ormatter); var json = config.Formatters.JsonFormatter; json.SerializerSettings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; json.SerializerSettings.Formatting = Formatting.Indented; • Content Negotiation • Model Validation in ASP.NET Web API
  • 29. Dependency Resolver with Autofac var builder = new ContainerBuilder(); // register autofac modules builder.RegisterModule<WebModule>(); builder.RegisterModule<DataSurveyModule>(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterFilterProvider(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
  • 30. Q&A
  • 31. References • http://www.ics.uci.edu/~fielding/pubs/dissert ation/top.htm • http://www.crummy.com/writing/speaking/2 008-QCon/act3.html • http://martinfowler.com/articles/richardsonM aturityModel.html • http://www.asp.net/web-api/