SlideShare a Scribd company logo
Web API Routing


  Eyal Vardi
  CEO E4D Solutions LTD
  Microsoft MVP Visual C#
  blog: www.eVardi.com
Expert Days 2012
                                                                                 




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Routing Has Three Main Phases

    1.      Matching the URI to a route template.

    2.      Selecting a controller.

    3.      Selecting an action.




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Routing Tables
            routes.MapHttpRoute(
                   name:                       "DefaultApi",
                   routeTemplate:              "api/{controller}/{id}",
                   defaults:                   new { id = RouteParameter.Optional }
                   constraints:                new { id = @"d+" }
            );


                         Action                       HTTP method                        Relative URI
         Get a list of all products                   GET                        /api/products
         Get a product by ID                          GET                        /api/products/id

         Get a product by category                    GET                        /api/products?category=1




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Action Mapping
            public class ProductsController : ApiController
            {
                public void GetAllProducts() { }
                public IEnumerable<Product> GetProductById(int id) { }
                public HttpResponseMessage DeleteProduct(int id) { }
            }




               Method                   URI Path                        Action       Parameter
          GET                    api/products                 GetAllProducts     (none)
          GET                    api/products/4               GetProductById     4
          DELETE                 api/products/4               DeleteProduct      4
          POST                   api/products                 (no match)



© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Routing by Action Name
           routes.MapHttpRoute(
               name: "ActionApi",
               routeTemplate: "api/{controller}/{action}/{id}",
               defaults: new { id = RouteParameter.Optional }
               );


           public class ProductsController : ApiController
           {
               [AcceptVerbs("GET", "HEAD")]
               public Product FindProduct(id) { }

                 // WebDAV method
                 [AcceptVerbs("MKCOL")]
                 public void MakeCollection() { }
           }




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Web API Routing


© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Paging and Querying (OData)
           ASP.NET Web API provides built-in support
            for OData query parameters.
                  $filter, $orderby, $skip & $top


           Examples
                  /api/products?$filter=substringof(Name, 'Ed') eq true
                  api/products?$skip=2
                  api/products?$top=3&$orderby=Name

                     [Queryable(ResultLimit=20)]
                     public IQueryable<Product> GetAllProducts()
                     {
                         return repository.GetAll().AsQueryable();
                     }

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Query string options
           $Expand
                  /Customers(ALFKI)?$expand=Orders.Employees

           $Orderby
                  /Customers?$orderby=City desc, CompanyName

           $Skip
                  /Customers?$skip=10

           $Top
                  /Orders?$orderby=TotalDue&$top=5

           $Filter
                  /Customers?$filter=City eq ‘London’

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Expression Syntax
      Operator           Description                                             Example
                                              Logical Operators
         eq        Equal                 /Customers?filter = City eq 'London'
         ne        Not equal             /Customers?filter = City ne 'London'
         gt        Greater than          /Product?$filter = UnitPrice gt 20
        gteq       Greater than or equal /Orders?$filter      = Freight gteq 800
         lt        Less than             /Orders?$filter      = Freight lt 1
        lteq       Less than or equal    /Product?$filter = UnitPrice lteq 20
        and        Logical and           /Product?filter=UnitPrice lteq 20 and UnitPrice gt 10
         or        Logical or            /Product?filter=UnitPrice lteq 20 or UnitPrice gt 10
        not        Logical negation      /Orders?$ ?$filter=not endswith(ShipPostalCode,'100')
                                             Arithmetic Operators
         add       Addition              /Product?filter = UnitPrice add 5 gt 10
         sub       Subtraction           /Product?filter = UnitPrice sub 5 gt 10
         mul       Multiplication        /Orders?$filter = Freight mul 800 gt 2000
         div       Division              /Orders?$filter = Freight div 10 eq 4
         mod       Modulo                /Orders?$filter = Freight mod 10 eq 0
                                             Grouping Operators
         ( )        Precedence grouping /Product?filter = (UnitPrice sub 5) gt 10




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Expression Syntax Cont.
    String Functions                                                             Date Functions
    bool contains(string p0, string p1)                                          int day(DateTime p0)
    bool endswith(string p0, string p1)                                          int hour(DateTime p0)
    bool startswith(string p0, string p1)                                        int minute(DateTime p0)
    int length(string p0)                                                        int month(DateTime p0)
    int indexof(string arg)                                                      int second(DateTime p0)
    string insert(string p0, int pos, string p1)                                 int year(DateTime p0)
    string remove(string p0, int pos)
    string remove(string p0, int pos, int length)
    string replace(string p0, string find, string replace)                       Math Functions
    string substring(string p0, int pos)                                         double round(double p0)
    string substring(string p0, int pos, int length)                             decimal round(decimal p0)
    string tolower(string p0)                                                    double floor(double p0)
    string toupper(string p0)                                                    decimal floor(decimal p0)
    string trim(string p0)                                                       double ceiling(double p0)
    string concat(string p0, string p1)                                          decimal ceiling(decimal p)


     Type Functions
     bool IsOf(type p0)
     bool IsOf(expression p0, type p1)
     <p0> Cast(type p0)
     <p1> Cast(expression p0, type p1)

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Data Services
          URL Syntax

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il

More Related Content

Similar to Web api routing

OData and SharePoint
OData and SharePointOData and SharePoint
OData and SharePoint
Sanjay Patel
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
Kiev ALT.NET
 
Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Developing A Real World Logistic Application With Oracle Application - UKOUG ...Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Roel Hartman
 
Pearson Plug and Play @ Over the Air
Pearson Plug and Play @ Over the AirPearson Plug and Play @ Over the Air
Pearson Plug and Play @ Over the Air
Dan Murphy
 

Similar to Web api routing (20)

OData and SharePoint
OData and SharePointOData and SharePoint
OData and SharePoint
 
Web api crud operations
Web api crud operationsWeb api crud operations
Web api crud operations
 
Wcf data services
Wcf data servicesWcf data services
Wcf data services
 
Odata introduction
Odata introductionOdata introduction
Odata introduction
 
Federico Feroldi - Scala microservices
Federico Feroldi - Scala microservicesFederico Feroldi - Scala microservices
Federico Feroldi - Scala microservices
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
TPSE Thailand 2015 - Rethinking Web with React and Flux
TPSE Thailand 2015 - Rethinking Web with React and FluxTPSE Thailand 2015 - Rethinking Web with React and Flux
TPSE Thailand 2015 - Rethinking Web with React and Flux
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
 
RESTFul API Design and Documentation - an Introduction
RESTFul API Design and Documentation - an IntroductionRESTFul API Design and Documentation - an Introduction
RESTFul API Design and Documentation - an Introduction
 
Models
ModelsModels
Models
 
Prompt engineering for iOS developers (How LLMs and GenAI work)
Prompt engineering for iOS developers (How LLMs and GenAI work)Prompt engineering for iOS developers (How LLMs and GenAI work)
Prompt engineering for iOS developers (How LLMs and GenAI work)
 
apidays Paris 2022 - France Televisions : How we leverage API Platform for ou...
apidays Paris 2022 - France Televisions : How we leverage API Platform for ou...apidays Paris 2022 - France Televisions : How we leverage API Platform for ou...
apidays Paris 2022 - France Televisions : How we leverage API Platform for ou...
 
Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Developing A Real World Logistic Application With Oracle Application - UKOUG ...Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Developing A Real World Logistic Application With Oracle Application - UKOUG ...
 
OpenTox API introductory presentation
OpenTox API introductory presentationOpenTox API introductory presentation
OpenTox API introductory presentation
 
Post Sharp Talk
Post Sharp TalkPost Sharp Talk
Post Sharp Talk
 
Rack Middleware
Rack MiddlewareRack Middleware
Rack Middleware
 
Pearson Plug and Play @ Over the Air
Pearson Plug and Play @ Over the AirPearson Plug and Play @ Over the Air
Pearson Plug and Play @ Over the Air
 
SADI in Perl - Protege Plugin Tutorial (fixed Aug 24, 2011)
SADI in Perl - Protege Plugin Tutorial (fixed Aug 24, 2011)SADI in Perl - Protege Plugin Tutorial (fixed Aug 24, 2011)
SADI in Perl - Protege Plugin Tutorial (fixed Aug 24, 2011)
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMS
 

More from Eyal Vardi

More from Eyal Vardi (20)

Why magic
Why magicWhy magic
Why magic
 
Smart Contract
Smart ContractSmart Contract
Smart Contract
 
Rachel's grandmother's recipes
Rachel's grandmother's recipesRachel's grandmother's recipes
Rachel's grandmother's recipes
 
Performance Optimization In Angular 2
Performance Optimization In Angular 2Performance Optimization In Angular 2
Performance Optimization In Angular 2
 
Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)
 
Angular 2 NgModule
Angular 2 NgModuleAngular 2 NgModule
Angular 2 NgModule
 
Upgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.xUpgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.x
 
Angular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time CompilationAngular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time Compilation
 
Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And Navigation
 
Angular 2 Architecture
Angular 2 ArchitectureAngular 2 Architecture
Angular 2 Architecture
 
Angular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.xAngular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.x
 
Angular 2.0 Views
Angular 2.0 ViewsAngular 2.0 Views
Angular 2.0 Views
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
Template syntax in Angular 2.0
Template syntax in Angular 2.0Template syntax in Angular 2.0
Template syntax in Angular 2.0
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injection
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and Navigation
 
Async & Parallel in JavaScript
Async & Parallel in JavaScriptAsync & Parallel in JavaScript
Async & Parallel in JavaScript
 
Angular 2.0 Pipes
Angular 2.0 PipesAngular 2.0 Pipes
Angular 2.0 Pipes
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 

Recently uploaded

Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Peter Udo Diehl
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
UXDXConf
 

Recently uploaded (20)

Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdf
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
The architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfThe architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdf
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Server-Driven User Interface (SDUI) at Priceline
Server-Driven User Interface (SDUI) at PricelineServer-Driven User Interface (SDUI) at Priceline
Server-Driven User Interface (SDUI) at Priceline
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAK
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 

Web api routing

  • 1. Web API Routing Eyal Vardi CEO E4D Solutions LTD Microsoft MVP Visual C# blog: www.eVardi.com
  • 2. Expert Days 2012  © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 3. Routing Has Three Main Phases 1. Matching the URI to a route template. 2. Selecting a controller. 3. Selecting an action. © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 4. Routing Tables routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } constraints: new { id = @"d+" } ); Action HTTP method Relative URI Get a list of all products GET /api/products Get a product by ID GET /api/products/id Get a product by category GET /api/products?category=1 © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 5. Action Mapping public class ProductsController : ApiController { public void GetAllProducts() { } public IEnumerable<Product> GetProductById(int id) { } public HttpResponseMessage DeleteProduct(int id) { } } Method URI Path Action Parameter GET api/products GetAllProducts (none) GET api/products/4 GetProductById 4 DELETE api/products/4 DeleteProduct 4 POST api/products (no match) © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 6. Routing by Action Name routes.MapHttpRoute( name: "ActionApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); public class ProductsController : ApiController { [AcceptVerbs("GET", "HEAD")] public Product FindProduct(id) { } // WebDAV method [AcceptVerbs("MKCOL")] public void MakeCollection() { } } © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 7. Web API Routing © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 8. Paging and Querying (OData)  ASP.NET Web API provides built-in support for OData query parameters.  $filter, $orderby, $skip & $top  Examples  /api/products?$filter=substringof(Name, 'Ed') eq true  api/products?$skip=2  api/products?$top=3&$orderby=Name [Queryable(ResultLimit=20)] public IQueryable<Product> GetAllProducts() { return repository.GetAll().AsQueryable(); } © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 9. Query string options  $Expand  /Customers(ALFKI)?$expand=Orders.Employees  $Orderby  /Customers?$orderby=City desc, CompanyName  $Skip  /Customers?$skip=10  $Top  /Orders?$orderby=TotalDue&$top=5  $Filter  /Customers?$filter=City eq ‘London’ © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 10. Expression Syntax Operator Description Example Logical Operators eq Equal /Customers?filter = City eq 'London' ne Not equal /Customers?filter = City ne 'London' gt Greater than /Product?$filter = UnitPrice gt 20 gteq Greater than or equal /Orders?$filter = Freight gteq 800 lt Less than /Orders?$filter = Freight lt 1 lteq Less than or equal /Product?$filter = UnitPrice lteq 20 and Logical and /Product?filter=UnitPrice lteq 20 and UnitPrice gt 10 or Logical or /Product?filter=UnitPrice lteq 20 or UnitPrice gt 10 not Logical negation /Orders?$ ?$filter=not endswith(ShipPostalCode,'100') Arithmetic Operators add Addition /Product?filter = UnitPrice add 5 gt 10 sub Subtraction /Product?filter = UnitPrice sub 5 gt 10 mul Multiplication /Orders?$filter = Freight mul 800 gt 2000 div Division /Orders?$filter = Freight div 10 eq 4 mod Modulo /Orders?$filter = Freight mod 10 eq 0 Grouping Operators ( ) Precedence grouping /Product?filter = (UnitPrice sub 5) gt 10 © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 11. Expression Syntax Cont. String Functions Date Functions bool contains(string p0, string p1) int day(DateTime p0) bool endswith(string p0, string p1) int hour(DateTime p0) bool startswith(string p0, string p1) int minute(DateTime p0) int length(string p0) int month(DateTime p0) int indexof(string arg) int second(DateTime p0) string insert(string p0, int pos, string p1) int year(DateTime p0) string remove(string p0, int pos) string remove(string p0, int pos, int length) string replace(string p0, string find, string replace) Math Functions string substring(string p0, int pos) double round(double p0) string substring(string p0, int pos, int length) decimal round(decimal p0) string tolower(string p0) double floor(double p0) string toupper(string p0) decimal floor(decimal p0) string trim(string p0) double ceiling(double p0) string concat(string p0, string p1) decimal ceiling(decimal p) Type Functions bool IsOf(type p0) bool IsOf(expression p0, type p1) <p0> Cast(type p0) <p1> Cast(expression p0, type p1) © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 12. Data Services URL Syntax © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il