SlideShare una empresa de Scribd logo
1 de 30
Click to edit Master title style
• Click to edit Master text styles
      – Second level
             • Third level
               – Fourth level
             The Lightweight Approach to
                   » Fifth level
             Building Web Based APIs with
             .NET
                    MOW 2012




19-04-2012                                  1
Agenda

 Who Am I?


 What is “lightweight”
 RestBucks
 REST
 Nancy
What is lightweight?




3
What is lightweight?




               Low ceremony
               Low cruft
               Conventions




4
What is lightweight?




                 Open
                 Agile
                 Inexpensive




5
Restbucks




6
REST




7
REST – Richardsons Maturity Model


       Level 3: Hypermedia


       Level 2: HTTP Verbs


       Level 1: Resources


       Level 0: POX-RPC

8
REST - Resources

     The basic building blocks of web API
     Anything with a URI


     http://restbucks.com/menu/
     http://restbucks.com/orders/
     http://restbucks.com/order/42/
     http://restbucks.com/order/42/payment/



9
REST- Representations

   GET http://restbucks.com/order/19202048/ HTTP/1.1

   Accept: application/vnd.restbucks+xml

<?xml version="1.0"?>
<order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="h
   <links>
     <link uri="http://restbucks.com/order/19202048" rel="http://restbucks
     <link uri="http://restbucks.com/order/19202048" rel="http://restbucks
     <link uri="http://restbucks.com/order/19202048" rel="http://restbucks
     <link uri="http://restbucks.com/order/19202048/payment" rel="http://r
   </links>
   <location>inShop</location>
   <cost>7.60000</cost>
   <items>
     <item>
       <name>Latte</name>
       <quantity>1</quantity>
       <milk>skim</milk>
       <size>large</size>
10
     </item>
REST - Representations

      GET http://restbucks.com/order/19202048/ HTTP/1.1

      Accept: application/vnd.restbucks+json

{
     "Location":inShop,
     "Cost":7.60000,
     "Items":[
       {
         "Name":"Latte",
         "Quantity":1,
         "Preferences":{
           "milk":"skim",
           "size":"large"
         }
       }
     ],
     "Status":1,
     "Links":[
       {
11
         "Uri":"http://restbucks.com/order/19202048",
REST - verbs

      GET
      POST
      PUT
      DELETE


      HEAD
      OPTIONS


      PATCH
12
REST - Headers

      Accept
      Content-Type
      If-None-Match
      Etag




13
14
Why Nancy?

      “Close” to http
      Very, very readable code
      Very explicit routing
      Embraces modularity
      Embraces IoC/DI
      Embraces testing
      Runs anywhere



15
Nancy Basics

 Organizes your routes

  public class MainModule : NancyModule
  {
         public MainModule()
         {
             Get["/"] = _ => "Hello from root";
         }
    }


  public class SubModule : NancyModule
   {
         public SubModule() : base("subpath")
         {
             Get["/"] = _ => "Hello from subpath";
         }
   }
Nancy Basics

 Defines which verbs you accepts
  public class MainModule : NancyModule
  {
         public MainModule()
         {
             Get["/"] = _ => "Hello from root";
             Post["/”] = _ => DoPost(Request.Form.my_value)
             Delete["/{id}”] = p => Delete(p.id);
             Put["/”] = _ => DoPut(Request.Body);
             Patch["/”] = _ => DoPatch(Request.Body);
         }
    }



 HEAD and OPTIONS and automatic
Restbuck on Nancy – Place an Order

public OrdersResourceHandler(IRepository<Product> productRepository,
                            IRepository<Order> orderRepository) : base("/orders")
{
   this.productRepository = productRepository;
   this.orderRepository = orderRepository;

     Post["/"] = _ => HandlePost(this.Bind<OrderRepresentation>());
}

private Response HandlePost(OrderRepresentation orderRepresentation)
{
  var order = TryBuildOrder(orderRepresentation);
  if (!order.IsValid())
    return InvalidOrderResponse(order);

     orderRepository.MakePersistent(order);
     return Created(order);
}



18
RestBucks on Nancy – View an Order
public OrderResourceHandler(IRepository<Order> orderRepository) : base(”/order”)
{
  this.orderRepository = orderRepository;
  Get["/{orderId}/”] = parameters => GetHandler((int) parameters.orderId);
  …
}

public Response GetHandler(int orderId)
{
  var order = orderRepository.GetById(orderId);
  if (order == null)
    return HttpStatusCode.NotFound;

     if (order.Status == OrderStatus.Canceled)
      return Response.MovedTo(new ResourceLinker(CanceledOrderUri(orderId);

     if (Request.IsNotModified(order))
       return Response.NotModified();

 return Response.WithContent(Request.Headers.Accept,
                          OrderRepresentationMapper.Map(order,Request.BaseUri()))
                .WithCacheHeaders(order);
}
19
RestBucks on Nancy – Cancel an Order




        Delete["/{orderId}/"] = parameters => Cancel((int) parameters.orderId);

        public Response Cancel(int orderId)
        {
          var order = orderRepository.GetById(orderId);
          if (order == null)
            return HttpStatusCode.NotFound;

            order.Cancel("canceled from the rest interface");
            return HttpStatusCode.NoContent;
        }




20
RestBucks on Nancy –Pay an Order



Post["/{orderId}/payment"] = parameters => Pay((int) parameters.orderId,
                                             this.Bind<PaymentRepresentation>());

public Response Pay(int orderId, PaymentRepresentation paymentArgs)
{
   var order = orderRepository.GetById(orderId);
   if (order == null)
     return HttpStatusCode.NotFound;

         order.Pay(paymentArgs.CardNumber, paymentArgs.CardOwner);
         return HttpStatusCode.OK;
     }




21
RestBucks on Nancy – XML or JSON



return
   Response.WithContent(Request.Headers.Accept,
                        OrderRepresentationMapper.Map(order, Request.BaseUri()))
           .WithCacheHeaders(order);

     public static Response WithContent<T>(this IResponseFormatter formatter,
                                 IEnumerable<Tuple<string, decimal>> acceptHeaders,
                                 T content)
     {
       var xmlWeight = CalculateWeightForContentType(acceptHeaders, "xml");
       var jsonWeight = CalculateWeightForContentType(acceptHeaders, "json");

         if (jsonWeight > xmlWeight)
           return formatter.AsJson(content);
         else
           return formatter.AsXml(content);
     }


22
RestBucks on Nancy – Conditional Gets


     return
       Response.WithContent(Request.Headers.Accept,
                            OrderRepresentationMapper.Map(order, Request.BaseUri()))
               .WithCacheHeaders(order);


public static Response WithCacheHeaders(this Response response,
                                        IVersionable versionable,
                                        TimeSpan? maxAge = null)
{
  return
     response.WithHeaders(
              new { Header = "ETag",
                    Value = string.Format(""{0}"", versionable.Version) },
              new { Header = "Cache-Control",
                    Value = string.Format("max-age={0}, public",
                                         maxAge ?? TimeSpan.FromSeconds(10)) });
 }


23
RestBucks on Nancy – Conditional Gets
     if (Request.IsNotModified(order))
            return Response.NotModified();

     public static bool IsNotModified(this Request request, IVersionable versionable)
     {
       if (!request.Headers.IfNoneMatch.Any())
         return false;
       var etag = request.Headers.IfNoneMatch.First();
       return string.Format(""{0}"", versionable.Version) == etag;
     }

     public static Response NotModified(this IResponseFormatter formatter,
                                        TimeSpan? maxAge = null)
     {
       Response response = HttpStatusCode.NotModified;

       return response.WithHeaders(
                          new { Header = "ReasonPhrase", Value = "Not modified"},
                          new { Header = "Cache-Control",
                                Value = string.Format("max-age={0}, public",
                                             maxAge ?? TimeSpan.FromSeconds(10)) });
      }
24
Nancy.Hosting


                Your Application


                     Nancy


                 Nancy.Hosting


                       …
Nancy.Hosting

 Usage:
   > Install-Package Nancy.Hosting.*


 Hosts:
   ASP.NET
   WCF
   Self
   OWIN
Nancy.Testing
  [Test]
  public void WhenOrderHasNotChanged_ThenReturn304()
  {
    // Arrange
    var orderRepo = new RepositoryStub<Order>(new Order(1, 123);
    var app = new Browser(
               new ConfigurableBootstrapper
               (with =>
               {
                  with.Dependency<IRepository<Product>>(…);
                  with.Dependency<IRepository<Order>>(orderRepository);
            }
           ));
    // Act
    var response =
    app.Get("/order/123/",
            with =>
            {
              with.HttpRequest();
              with.Header("If-None-Match", ""1"");
            });
    //Assert
    response.StatusCode.Should().Be.EqualTo(HttpStatusCode.NotModified);
29}
Why Nancy?

      “Close” to http
      Very, very readable code
      Very explicit routing
      Embraces modularity
      Embraces IoC/DI
      Embraces testing
      Runs anywhere



30
Why REST + Nancy

      Lightweight
        Low ceremony
        Low cruft
        Follows conventions
        Open
        Agile




31
More …

      Restbucks on Nancy: http://github.com/horsdal/Restbucks-on-Nancy
      Rest in Practice: http://restinpractice.com/book.html
      Nancy: www.nancyfx.org
      Me:
         Twitter: @chr_horsdal
         Blog: horsdal.blogspot.com
         email: chg@mjolner.dk




32

Más contenido relacionado

La actualidad más candente

Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDMichele Capra
 
Developing cacheable backend applications - Appdevcon 2019
Developing cacheable backend applications - Appdevcon 2019Developing cacheable backend applications - Appdevcon 2019
Developing cacheable backend applications - Appdevcon 2019Thijs Feryn
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harianKhairunnisaPekanbaru
 
Top5 scalabilityissues withappendix
Top5 scalabilityissues withappendixTop5 scalabilityissues withappendix
Top5 scalabilityissues withappendixColdFusionConference
 
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!Ryosuke Uchitate
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeWim Godden
 
Nginx and friends - putting a turbo button on your site
Nginx and friends - putting a turbo button on your siteNginx and friends - putting a turbo button on your site
Nginx and friends - putting a turbo button on your siteWim Godden
 
Building High Performance and Reliable Windows Phone 8 Apps
Building High Performance and Reliable Windows Phone 8 AppsBuilding High Performance and Reliable Windows Phone 8 Apps
Building High Performance and Reliable Windows Phone 8 AppsMichele Capra
 
Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門Ryosuke Uchitate
 
Cassandra Summit EU 2014 - Testing Cassandra Applications
Cassandra Summit EU 2014 - Testing Cassandra ApplicationsCassandra Summit EU 2014 - Testing Cassandra Applications
Cassandra Summit EU 2014 - Testing Cassandra ApplicationsChristopher Batey
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaMongoDB
 
LJC Conference 2014 Cassandra for Java Developers
LJC Conference 2014 Cassandra for Java DevelopersLJC Conference 2014 Cassandra for Java Developers
LJC Conference 2014 Cassandra for Java DevelopersChristopher Batey
 
Spring data iii
Spring data iiiSpring data iii
Spring data iii명철 강
 
Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...
Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...
Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...EPAM_Systems_Bulgaria
 

La actualidad más candente (20)

Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
 
Developing cacheable backend applications - Appdevcon 2019
Developing cacheable backend applications - Appdevcon 2019Developing cacheable backend applications - Appdevcon 2019
Developing cacheable backend applications - Appdevcon 2019
 
Fia fabila
Fia fabilaFia fabila
Fia fabila
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian
 
Top5 scalabilityissues withappendix
Top5 scalabilityissues withappendixTop5 scalabilityissues withappendix
Top5 scalabilityissues withappendix
 
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
 
Mongo db for c# developers
Mongo db for c# developersMongo db for c# developers
Mongo db for c# developers
 
Tugas 2
Tugas 2Tugas 2
Tugas 2
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
 
Nginx and friends - putting a turbo button on your site
Nginx and friends - putting a turbo button on your siteNginx and friends - putting a turbo button on your site
Nginx and friends - putting a turbo button on your site
 
Building High Performance and Reliable Windows Phone 8 Apps
Building High Performance and Reliable Windows Phone 8 AppsBuilding High Performance and Reliable Windows Phone 8 Apps
Building High Performance and Reliable Windows Phone 8 Apps
 
Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門
 
Spock and Geb in Action
Spock and Geb in ActionSpock and Geb in Action
Spock and Geb in Action
 
Mongo db for C# Developers
Mongo db for C# DevelopersMongo db for C# Developers
Mongo db for C# Developers
 
Cassandra Summit EU 2014 - Testing Cassandra Applications
Cassandra Summit EU 2014 - Testing Cassandra ApplicationsCassandra Summit EU 2014 - Testing Cassandra Applications
Cassandra Summit EU 2014 - Testing Cassandra Applications
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
 
LJC Conference 2014 Cassandra for Java Developers
LJC Conference 2014 Cassandra for Java DevelopersLJC Conference 2014 Cassandra for Java Developers
LJC Conference 2014 Cassandra for Java Developers
 
Spring data iii
Spring data iiiSpring data iii
Spring data iii
 
Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...
Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...
Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...
 

Destacado

Middleware webnextconf - 20152609
Middleware   webnextconf - 20152609Middleware   webnextconf - 20152609
Middleware webnextconf - 20152609Christian Horsdal
 
Consolidating services with middleware - NDC London 2017
Consolidating services with middleware - NDC London 2017Consolidating services with middleware - NDC London 2017
Consolidating services with middleware - NDC London 2017Christian Horsdal
 

Destacado (6)

ASP.NET vNext ANUG 20140817
ASP.NET vNext ANUG 20140817ASP.NET vNext ANUG 20140817
ASP.NET vNext ANUG 20140817
 
Campus days 2014 owin
Campus days 2014 owinCampus days 2014 owin
Campus days 2014 owin
 
簡報2
簡報2簡報2
簡報2
 
Middleware webnextconf - 20152609
Middleware   webnextconf - 20152609Middleware   webnextconf - 20152609
Middleware webnextconf - 20152609
 
Intro to.net core 20170111
Intro to.net core   20170111Intro to.net core   20170111
Intro to.net core 20170111
 
Consolidating services with middleware - NDC London 2017
Consolidating services with middleware - NDC London 2017Consolidating services with middleware - NDC London 2017
Consolidating services with middleware - NDC London 2017
 

Similar a Nancy + rest mow2012

Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design PrinciplesJon Kruger
 
Lightweight Approach to Building Web APIs with .NET
Lightweight Approach to Building Web APIs with .NETLightweight Approach to Building Web APIs with .NET
Lightweight Approach to Building Web APIs with .NETChristian Horsdal
 
Async servers and clients in Rest.li
Async servers and clients in Rest.liAsync servers and clients in Rest.li
Async servers and clients in Rest.liKaran Parikh
 
Vert.x - Reactive & Distributed [Devoxx version]
Vert.x - Reactive & Distributed [Devoxx version]Vert.x - Reactive & Distributed [Devoxx version]
Vert.x - Reactive & Distributed [Devoxx version]Orkhan Gasimov
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug Italy
 
A portlet-API based approach for application integration
A portlet-API based approach for application integrationA portlet-API based approach for application integration
A portlet-API based approach for application integrationwhabicht
 
Finch.io - Purely Functional REST API with Finagle
Finch.io - Purely Functional REST API with FinagleFinch.io - Purely Functional REST API with Finagle
Finch.io - Purely Functional REST API with FinagleVladimir Kostyukov
 
Bare-knuckle web development
Bare-knuckle web developmentBare-knuckle web development
Bare-knuckle web developmentJohannes Brodwall
 
Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019Joe Keeley
 
Full Stack Toronto - the 3R Stack
Full Stack Toronto - the 3R StackFull Stack Toronto - the 3R Stack
Full Stack Toronto - the 3R StackScott Persinger
 
Serverless Ballerina
Serverless BallerinaServerless Ballerina
Serverless BallerinaBallerina
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to NodejsGabriele Lana
 
RESTful API 제대로 만들기
RESTful API 제대로 만들기RESTful API 제대로 만들기
RESTful API 제대로 만들기Juwon Kim
 
Hd insight programming
Hd insight programmingHd insight programming
Hd insight programmingCasear Chu
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in SwiftPeter Friese
 

Similar a Nancy + rest mow2012 (20)

Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles
 
Lightweight Approach to Building Web APIs with .NET
Lightweight Approach to Building Web APIs with .NETLightweight Approach to Building Web APIs with .NET
Lightweight Approach to Building Web APIs with .NET
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
Kitura Todolist tutorial
Kitura Todolist tutorialKitura Todolist tutorial
Kitura Todolist tutorial
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Async servers and clients in Rest.li
Async servers and clients in Rest.liAsync servers and clients in Rest.li
Async servers and clients in Rest.li
 
Vert.x - Reactive & Distributed [Devoxx version]
Vert.x - Reactive & Distributed [Devoxx version]Vert.x - Reactive & Distributed [Devoxx version]
Vert.x - Reactive & Distributed [Devoxx version]
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
A portlet-API based approach for application integration
A portlet-API based approach for application integrationA portlet-API based approach for application integration
A portlet-API based approach for application integration
 
Finch.io - Purely Functional REST API with Finagle
Finch.io - Purely Functional REST API with FinagleFinch.io - Purely Functional REST API with Finagle
Finch.io - Purely Functional REST API with Finagle
 
Bare-knuckle web development
Bare-knuckle web developmentBare-knuckle web development
Bare-knuckle web development
 
Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019
 
Full Stack Toronto - the 3R Stack
Full Stack Toronto - the 3R StackFull Stack Toronto - the 3R Stack
Full Stack Toronto - the 3R Stack
 
Serverless Ballerina
Serverless BallerinaServerless Ballerina
Serverless Ballerina
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
OWASP Proxy
OWASP ProxyOWASP Proxy
OWASP Proxy
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
 
RESTful API 제대로 만들기
RESTful API 제대로 만들기RESTful API 제대로 만들기
RESTful API 제대로 만들기
 
Hd insight programming
Hd insight programmingHd insight programming
Hd insight programming
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in Swift
 

Más de Christian Horsdal

Testing microservices.ANUG.20230111.pptx
Testing microservices.ANUG.20230111.pptxTesting microservices.ANUG.20230111.pptx
Testing microservices.ANUG.20230111.pptxChristian Horsdal
 
Scoping microservices.20190917
Scoping microservices.20190917Scoping microservices.20190917
Scoping microservices.20190917Christian Horsdal
 
Event sourcing anug 20190227
Event sourcing anug 20190227Event sourcing anug 20190227
Event sourcing anug 20190227Christian Horsdal
 
Three Other Web Frameworks. All .NET. All OSS. One Hour. Go
Three Other Web Frameworks. All .NET. All OSS. One Hour. GoThree Other Web Frameworks. All .NET. All OSS. One Hour. Go
Three Other Web Frameworks. All .NET. All OSS. One Hour. GoChristian Horsdal
 
Four .NET Web Frameworks in Less Than an Hour
Four .NET Web Frameworks in Less Than an HourFour .NET Web Frameworks in Less Than an Hour
Four .NET Web Frameworks in Less Than an HourChristian Horsdal
 
Nancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web FrameworkNancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web FrameworkChristian Horsdal
 
DCI ANUG - 24th November 2010
DCI ANUG - 24th November 2010DCI ANUG - 24th November 2010
DCI ANUG - 24th November 2010Christian Horsdal
 
DCI - ANUG 24th November 2010
DCI - ANUG 24th November 2010DCI - ANUG 24th November 2010
DCI - ANUG 24th November 2010Christian Horsdal
 

Más de Christian Horsdal (8)

Testing microservices.ANUG.20230111.pptx
Testing microservices.ANUG.20230111.pptxTesting microservices.ANUG.20230111.pptx
Testing microservices.ANUG.20230111.pptx
 
Scoping microservices.20190917
Scoping microservices.20190917Scoping microservices.20190917
Scoping microservices.20190917
 
Event sourcing anug 20190227
Event sourcing anug 20190227Event sourcing anug 20190227
Event sourcing anug 20190227
 
Three Other Web Frameworks. All .NET. All OSS. One Hour. Go
Three Other Web Frameworks. All .NET. All OSS. One Hour. GoThree Other Web Frameworks. All .NET. All OSS. One Hour. Go
Three Other Web Frameworks. All .NET. All OSS. One Hour. Go
 
Four .NET Web Frameworks in Less Than an Hour
Four .NET Web Frameworks in Less Than an HourFour .NET Web Frameworks in Less Than an Hour
Four .NET Web Frameworks in Less Than an Hour
 
Nancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web FrameworkNancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web Framework
 
DCI ANUG - 24th November 2010
DCI ANUG - 24th November 2010DCI ANUG - 24th November 2010
DCI ANUG - 24th November 2010
 
DCI - ANUG 24th November 2010
DCI - ANUG 24th November 2010DCI - ANUG 24th November 2010
DCI - ANUG 24th November 2010
 

Último

Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 

Último (20)

Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 

Nancy + rest mow2012

  • 1. Click to edit Master title style • Click to edit Master text styles – Second level • Third level – Fourth level The Lightweight Approach to » Fifth level Building Web Based APIs with .NET MOW 2012 19-04-2012 1
  • 2. Agenda  Who Am I?  What is “lightweight”  RestBucks  REST  Nancy
  • 4. What is lightweight?  Low ceremony  Low cruft  Conventions 4
  • 5. What is lightweight?  Open  Agile  Inexpensive 5
  • 8. REST – Richardsons Maturity Model Level 3: Hypermedia Level 2: HTTP Verbs Level 1: Resources Level 0: POX-RPC 8
  • 9. REST - Resources  The basic building blocks of web API  Anything with a URI  http://restbucks.com/menu/  http://restbucks.com/orders/  http://restbucks.com/order/42/  http://restbucks.com/order/42/payment/ 9
  • 10. REST- Representations GET http://restbucks.com/order/19202048/ HTTP/1.1 Accept: application/vnd.restbucks+xml <?xml version="1.0"?> <order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="h <links> <link uri="http://restbucks.com/order/19202048" rel="http://restbucks <link uri="http://restbucks.com/order/19202048" rel="http://restbucks <link uri="http://restbucks.com/order/19202048" rel="http://restbucks <link uri="http://restbucks.com/order/19202048/payment" rel="http://r </links> <location>inShop</location> <cost>7.60000</cost> <items> <item> <name>Latte</name> <quantity>1</quantity> <milk>skim</milk> <size>large</size> 10 </item>
  • 11. REST - Representations GET http://restbucks.com/order/19202048/ HTTP/1.1 Accept: application/vnd.restbucks+json { "Location":inShop, "Cost":7.60000, "Items":[ { "Name":"Latte", "Quantity":1, "Preferences":{ "milk":"skim", "size":"large" } } ], "Status":1, "Links":[ { 11 "Uri":"http://restbucks.com/order/19202048",
  • 12. REST - verbs  GET  POST  PUT  DELETE  HEAD  OPTIONS  PATCH 12
  • 13. REST - Headers  Accept  Content-Type  If-None-Match  Etag 13
  • 14. 14
  • 15. Why Nancy?  “Close” to http  Very, very readable code  Very explicit routing  Embraces modularity  Embraces IoC/DI  Embraces testing  Runs anywhere 15
  • 16. Nancy Basics  Organizes your routes public class MainModule : NancyModule { public MainModule() { Get["/"] = _ => "Hello from root"; } } public class SubModule : NancyModule { public SubModule() : base("subpath") { Get["/"] = _ => "Hello from subpath"; } }
  • 17. Nancy Basics  Defines which verbs you accepts public class MainModule : NancyModule { public MainModule() { Get["/"] = _ => "Hello from root"; Post["/”] = _ => DoPost(Request.Form.my_value) Delete["/{id}”] = p => Delete(p.id); Put["/”] = _ => DoPut(Request.Body); Patch["/”] = _ => DoPatch(Request.Body); } }  HEAD and OPTIONS and automatic
  • 18. Restbuck on Nancy – Place an Order public OrdersResourceHandler(IRepository<Product> productRepository, IRepository<Order> orderRepository) : base("/orders") { this.productRepository = productRepository; this.orderRepository = orderRepository; Post["/"] = _ => HandlePost(this.Bind<OrderRepresentation>()); } private Response HandlePost(OrderRepresentation orderRepresentation) { var order = TryBuildOrder(orderRepresentation); if (!order.IsValid()) return InvalidOrderResponse(order); orderRepository.MakePersistent(order); return Created(order); } 18
  • 19. RestBucks on Nancy – View an Order public OrderResourceHandler(IRepository<Order> orderRepository) : base(”/order”) { this.orderRepository = orderRepository; Get["/{orderId}/”] = parameters => GetHandler((int) parameters.orderId); … } public Response GetHandler(int orderId) { var order = orderRepository.GetById(orderId); if (order == null) return HttpStatusCode.NotFound; if (order.Status == OrderStatus.Canceled) return Response.MovedTo(new ResourceLinker(CanceledOrderUri(orderId); if (Request.IsNotModified(order)) return Response.NotModified(); return Response.WithContent(Request.Headers.Accept, OrderRepresentationMapper.Map(order,Request.BaseUri())) .WithCacheHeaders(order); } 19
  • 20. RestBucks on Nancy – Cancel an Order Delete["/{orderId}/"] = parameters => Cancel((int) parameters.orderId); public Response Cancel(int orderId) { var order = orderRepository.GetById(orderId); if (order == null) return HttpStatusCode.NotFound; order.Cancel("canceled from the rest interface"); return HttpStatusCode.NoContent; } 20
  • 21. RestBucks on Nancy –Pay an Order Post["/{orderId}/payment"] = parameters => Pay((int) parameters.orderId, this.Bind<PaymentRepresentation>()); public Response Pay(int orderId, PaymentRepresentation paymentArgs) { var order = orderRepository.GetById(orderId); if (order == null) return HttpStatusCode.NotFound; order.Pay(paymentArgs.CardNumber, paymentArgs.CardOwner); return HttpStatusCode.OK; } 21
  • 22. RestBucks on Nancy – XML or JSON return Response.WithContent(Request.Headers.Accept, OrderRepresentationMapper.Map(order, Request.BaseUri())) .WithCacheHeaders(order); public static Response WithContent<T>(this IResponseFormatter formatter, IEnumerable<Tuple<string, decimal>> acceptHeaders, T content) { var xmlWeight = CalculateWeightForContentType(acceptHeaders, "xml"); var jsonWeight = CalculateWeightForContentType(acceptHeaders, "json"); if (jsonWeight > xmlWeight) return formatter.AsJson(content); else return formatter.AsXml(content); } 22
  • 23. RestBucks on Nancy – Conditional Gets return Response.WithContent(Request.Headers.Accept, OrderRepresentationMapper.Map(order, Request.BaseUri())) .WithCacheHeaders(order); public static Response WithCacheHeaders(this Response response, IVersionable versionable, TimeSpan? maxAge = null) { return response.WithHeaders( new { Header = "ETag", Value = string.Format(""{0}"", versionable.Version) }, new { Header = "Cache-Control", Value = string.Format("max-age={0}, public", maxAge ?? TimeSpan.FromSeconds(10)) }); } 23
  • 24. RestBucks on Nancy – Conditional Gets if (Request.IsNotModified(order)) return Response.NotModified(); public static bool IsNotModified(this Request request, IVersionable versionable) { if (!request.Headers.IfNoneMatch.Any()) return false; var etag = request.Headers.IfNoneMatch.First(); return string.Format(""{0}"", versionable.Version) == etag; } public static Response NotModified(this IResponseFormatter formatter, TimeSpan? maxAge = null) { Response response = HttpStatusCode.NotModified; return response.WithHeaders( new { Header = "ReasonPhrase", Value = "Not modified"}, new { Header = "Cache-Control", Value = string.Format("max-age={0}, public", maxAge ?? TimeSpan.FromSeconds(10)) }); } 24
  • 25. Nancy.Hosting Your Application Nancy Nancy.Hosting …
  • 26. Nancy.Hosting  Usage:  > Install-Package Nancy.Hosting.*  Hosts:  ASP.NET  WCF  Self  OWIN
  • 27. Nancy.Testing [Test] public void WhenOrderHasNotChanged_ThenReturn304() { // Arrange var orderRepo = new RepositoryStub<Order>(new Order(1, 123); var app = new Browser( new ConfigurableBootstrapper (with => { with.Dependency<IRepository<Product>>(…); with.Dependency<IRepository<Order>>(orderRepository); } )); // Act var response = app.Get("/order/123/", with => { with.HttpRequest(); with.Header("If-None-Match", ""1""); }); //Assert response.StatusCode.Should().Be.EqualTo(HttpStatusCode.NotModified); 29}
  • 28. Why Nancy?  “Close” to http  Very, very readable code  Very explicit routing  Embraces modularity  Embraces IoC/DI  Embraces testing  Runs anywhere 30
  • 29. Why REST + Nancy  Lightweight  Low ceremony  Low cruft  Follows conventions  Open  Agile 31
  • 30. More …  Restbucks on Nancy: http://github.com/horsdal/Restbucks-on-Nancy  Rest in Practice: http://restinpractice.com/book.html  Nancy: www.nancyfx.org  Me:  Twitter: @chr_horsdal  Blog: horsdal.blogspot.com  email: chg@mjolner.dk 32

Notas del editor

  1. Basics
  2. Basics
  3. Basics
  4. Conneq
  5. Brug WhenOrderHasNotChanged_ThenReturn304()