SlideShare a Scribd company logo
ASP.NET MVC 4 Web API




Tiago Knoch – tiago.knoch@comtrade.com
Contents
•   What is an API?
•   Why ASP.NET MVC Web API?
•   HyperText Transfer Protocol
•   REST
•   JSON
•   Introduction to Web API
•   Routing Table
•   Error & Exception Handling
•   Model Validation
•   Odata Protocol
•   Media Formatters
•   Security
•   HTTPClient
•   What Else?
•   Road Map
What is an API?
• An application programming interface (API) is a specification intended to
  be used as an interface by software components to communicate with
  each other. An API may include specifications for routines, data structures,
  object classes, and variables.

• For the web this mean Web Services (SOAP + XML + WSDL) but in Web 2.0
  we are moving away to REST Services (HTTP + XML/JSON) – Web API

• Web APIs allow the combination of multiple services into new applications
  known as mashups.
• Common examples:
         – Facebook, Twitter, Amazon, LinkedIn...




Source: http://blogs.mulesoft.org/cloud-apis-and-the-new-spaghetti-factory/
Why ASP.NET MVC Web Api?
• Web Api
  – Defined in HTTP
  – Messages in Json/XML
  – RESTful
  – CRUD operations
  – Ready for Cloud
HyperText Transfer Protocol
• The Hypertext Transfer Protocol (HTTP) is an application protocol for
  distributed, collaborative, hypermedia information systems. HTTP is the
  foundation of data communication for the World Wide Web.
• HTTP functions as a request-response protocol in the client-server
  computing model. A web browser, for example, may be the client and an
  application running on a computer hosting a web site may be the server.
• The client submits an HTTP request message to the server. The server,
  which provides resources such as HTML files and other content, or
  performs other functions on behalf of the client, returns a response
  message to the client. The response contains completion status
  information about the request and may also contain requested content in
  its message body.
HTTP – Example GET
GET / HTTP/1.1[CRLF]
Host: www.google.rs[CRLF] User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0)
Gecko/20100101 Firefox/15.0.1[CRLF]
Accept-Encoding: gzip[CRLF]
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8[CRLF]
Accept-Language: en-us,en;q=0.5[CRLF]




             Status: HTTP/1.1 200 OK
             Content-Type: text/html
             Content-Length: 1354
             Content: <HTML data>
HTTP – Example POST
  POST /somepage.php HTTP/1.1
  Host: example.com
  Content-Type: application/x-www-form-urlencoded
  Content-Length: 19
  name=tiago&surname=knoch




     Status: HTTP/1.1 404 Not Found
Rest - Representational State Transfer
• REST is a style of software architecture for distributed systems such as the
  WWW, where, virtually in all cases, the HTTP protocol is used.
• Uses CRUD actions (HTTP methods)
    CRUD Action                   HTTP Method
    Create                        Post
    Read                          Get
    Update                        Put
    Delete                        Delete
• Each resource is represented by an global id (URI in HTTP)
• The resources are conceptually separate from the representations that are
   returned to the client (JSON/XML)
In many ways, the World Wide Web itself, based on HTTP, can be viewed as
a REST-based architecture.
Despite being simple, REST is fully-featured; there's basically nothing you
can do in Web Services that can't be done with a RESTful architecture!
JSON
• JSON, or JavaScript Object Notation, is a text-based open standard
  designed for human-readable data interchange. It is derived from the
  JavaScript scripting language for representing simple data structures and
  associative arrays, called objects. Despite its relationship to JavaScript, it is
  language-independent, with parsers available for many languages.
ASP.NET MVC Web API
• MVC: Model -> View -> Controller
• Create a Model




• Create a controller
Routing Table
• Route is defined, by default, as api/{controller}/{id} where action is
  defined by an HTTP method (in global.asax Application_Start method).




HTTP Method      URI Path                            Action
GET              /api/products                       GetAllProducts
GET              /api/products/id                    GetProductById
GET              /api/products/?category=category    GetProductsByCategory
POST             /api/products                       PostProduct
PUT              /api/products/id                    PutProduct
DELETE           /api/products/id                    DeleteProduct
Routing Table
The four main HTTP methods are mapped to CRUD operations:

• GET retrieves the representation of the resource at a specified URI. GET
  should have no side effects on the server.

• PUT updates a resource at a specified URI (idempotent).

• POST creates a new resource. The server assigns the URI for the new
  object and returns this URI as part of the response message.

• DELETE deletes a resource at a specified URI (idempotent).
Oi?!
Time for some DEMO!
Error & Exception Handling
• Response messages, errors and exceptions are translated to HTTP
  response status codes.
• For example:
    – POST request should reply with HTTP status 201 (created).
    – DELETE request should reply with HTTP status 204 (no content).
• But:
    – If a PUT/GET request is done with an invalid id, it should reply with HTTP status 404 (not
      found)




    – Or if a PUT request has an invalid model, it can reply with HTTP status 400 (bad request)
Error & Exception Handling
• By default, all .NET exceptions are translated into and HTTP response with
  status code 500 (internal error).

• It is possible to register Exception filters:
Model Validation
• Like MVC, Web API supports Data Annotations
  (System.ComponentModel.DataAnnotations, .net 4.0).




• If in your model there is a difference between 0 and not set, use nullable
  values.
Model Validation - Example
Model Validation – FilterAttribute
   Create a FilterAttribute




   Add it to Filters in Global.asax App_Start
Odata Protocol
• http://www.odata.org/
• “The Open Data Protocol (OData) is a Web protocol for querying and
  updating data. OData does this by applying and building upon Web
  technologies such as HTTP, Atom Publishing Protocol (AtomPub) and JSON
  to provide access to information from a variety of
  applications, services, and stores.”

• In Web API we want to do something like this:
                        /api/products?$top=3&$orderby=Name
              /api/products/?$filter=substringof('a', Name) eq true
                        /api/products/?$filter=Price gt 5
         /api/products/?$filter=Price gt 1 and Category eq 'Hardware'
Odata Protocol
 • Change GET action method to return
   IQueryable<T> and to use Queryable attribute




 • Available as Nuget package (prerelease)!
PM> Install-Package Microsoft.AspNet.WebApi.OData -Pre
DEMO!
Media Formatters
• Web API only provides media formatters for JSON (using Json.NET library)
  and XML!
• In HTTP, the format of message body is defined by the MIME type (media
  type):
                 text/html, image/png, application/json, application/octet-stream
• When the client sends an HTTP request, the Accept header tells the server
  wich media type it expects:
              Accept: text/html, application/json, application/xml; q=0.9, */*; q=0.01
• Web API uses media formatters to:
    – Read CLR objects from an HTTP message body (HTTP requests serializes to action
      methods parameters),
    – Write CLR objects to an HTTP message body (action methods returned objects serializes
      to HTTP replies)
• You can create your own Media Formatter to serialize-deserialize your
  model types!
Media Formatters - Example
 Define which http media type is supported




 Define which types can be deserialized
Media Formatters - Example
Deserialize type to stream




    Define formatter in global.asax App_Start
Security
• Support for the [Authorize] Attribute
  (System.Web.Http.AuthorizeAttribute)...but it only checks
  UserPrincipal.Identity.IsAuthenticated (Forms authentication).
• For more secure options you need to implement a custom filter:
    –   Tokens (ex, Public/Private Keys)
    –   Oauth (http://oauth.net/)
    –   OpenID (http://openid.net/)
    –   Forms Authentication (already supported by ASP.NET)
    –   Basic Http Authentication (username/password encrypted )
    –   SSL
• Amazon S3 REST API uses a custom HTTP scheme based on a keyed-HMAC
  (Hash Message Authentication Code) for authentication.
• The Facebook/Twitter/Google API use OAuth for authentication and
  authorization.
Testing from a .NET client - HttpClient
•   HttpClient - Available in .NET 4.5 or NuGet package
    Microsoft.AspNet.WebApi.Client




•   Or use RestSharp (http://restsharp.org/)
What else?
• Improved support for IoC containers
• Create help pages (IApiExplorer service)
• Web API Project Template in VS 2012
• Scaffold controllers from Entity Framework
  model (like MVC)
• Easy integration with Azure
Road Map
• MVC 4 was released in ASP.NET 4.5 with Visual Studio 2012 and .NET
  Framework 4.5.

• Check out more at http://www.asp.net/web-api
Questions?



Tiago Knoch: tiago.knoch@comtrade.com

More Related Content

What's hot

ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
REST and ASP.NET Web API (Milan)
REST and ASP.NET Web API (Milan)REST and ASP.NET Web API (Milan)
REST and ASP.NET Web API (Milan)Jef Claes
 
Web services - A Practical Approach
Web services - A Practical ApproachWeb services - A Practical Approach
Web services - A Practical Approach
Madhaiyan Muthu
 
REST and ASP.NET Web API (Tunisia)
REST and ASP.NET Web API (Tunisia)REST and ASP.NET Web API (Tunisia)
REST and ASP.NET Web API (Tunisia)
Jef Claes
 
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
Adnan Masood
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
Sam Brannen
 
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
Dr. Awase Khirni Syed
 
Best Practices in Web Service Design
Best Practices in Web Service DesignBest Practices in Web Service Design
Best Practices in Web Service DesignLorna Mitchell
 
Restful webservices
Restful webservicesRestful webservices
Restful webservices
Luqman Shareef
 
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
Pradeep Kumar
 
Soap and restful webservice
Soap and restful webserviceSoap and restful webservice
Soap and restful webservice
Dong Ngoc
 
Web Server-Side Programming Techniques
Web Server-Side Programming TechniquesWeb Server-Side Programming Techniques
Web Server-Side Programming Techniques
guest8899ec02
 
Web development with ASP.NET Web API
Web development with ASP.NET Web APIWeb development with ASP.NET Web API
Web development with ASP.NET Web API
Damir Dobric
 
Enjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIEnjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web API
Kevin Hazzard
 
Introducing ASP.NET vNext - A tour of the new ASP.NET platform
Introducing ASP.NET vNext - A tour of the new ASP.NET platformIntroducing ASP.NET vNext - A tour of the new ASP.NET platform
Introducing ASP.NET vNext - A tour of the new ASP.NET platform
Jeffrey T. Fritz
 
Building RESTfull Data Services with WebAPI
Building RESTfull Data Services with WebAPIBuilding RESTfull Data Services with WebAPI
Building RESTfull Data Services with WebAPI
Gert Drapers
 
What is an API?
What is an API?What is an API?
What is an API?
Muhammad Zuhdi
 
Rest api design by george reese
Rest api design by george reeseRest api design by george reese
Rest api design by george reese
buildacloud
 
Overview of java web services
Overview of java web servicesOverview of java web services

What's hot (20)

ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
REST and ASP.NET Web API (Milan)
REST and ASP.NET Web API (Milan)REST and ASP.NET Web API (Milan)
REST and ASP.NET Web API (Milan)
 
Web services - A Practical Approach
Web services - A Practical ApproachWeb services - A Practical Approach
Web services - A Practical Approach
 
REST and ASP.NET Web API (Tunisia)
REST and ASP.NET Web API (Tunisia)REST and ASP.NET Web API (Tunisia)
REST and ASP.NET Web API (Tunisia)
 
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
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
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
 
Best Practices in Web Service Design
Best Practices in Web Service DesignBest Practices in Web Service Design
Best Practices in Web Service Design
 
Web servers
Web serversWeb servers
Web servers
 
Restful webservices
Restful webservicesRestful webservices
Restful webservices
 
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
 
Soap and restful webservice
Soap and restful webserviceSoap and restful webservice
Soap and restful webservice
 
Web Server-Side Programming Techniques
Web Server-Side Programming TechniquesWeb Server-Side Programming Techniques
Web Server-Side Programming Techniques
 
Web development with ASP.NET Web API
Web development with ASP.NET Web APIWeb development with ASP.NET Web API
Web development with ASP.NET Web API
 
Enjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIEnjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web API
 
Introducing ASP.NET vNext - A tour of the new ASP.NET platform
Introducing ASP.NET vNext - A tour of the new ASP.NET platformIntroducing ASP.NET vNext - A tour of the new ASP.NET platform
Introducing ASP.NET vNext - A tour of the new ASP.NET platform
 
Building RESTfull Data Services with WebAPI
Building RESTfull Data Services with WebAPIBuilding RESTfull Data Services with WebAPI
Building RESTfull Data Services with WebAPI
 
What is an API?
What is an API?What is an API?
What is an API?
 
Rest api design by george reese
Rest api design by george reeseRest api design by george reese
Rest api design by george reese
 
Overview of java web services
Overview of java web servicesOverview of java web services
Overview of java web services
 

Viewers also liked

WCF tutorial
WCF tutorialWCF tutorial
WCF tutorial
Abhi Arya
 
Windows Communication Foundation (WCF)
Windows Communication Foundation (WCF)Windows Communication Foundation (WCF)
Windows Communication Foundation (WCF)
Betclic Everest Group Tech Team
 
Windows Communication Foundation (WCF)
Windows Communication Foundation (WCF)Windows Communication Foundation (WCF)
Windows Communication Foundation (WCF)
Peter R. Egli
 
Introduction to asp.net web api
Introduction to asp.net web apiIntroduction to asp.net web api
Introduction to asp.net web api
Lohith Goudagere Nagaraj
 
ASP.NET WebAPI 体験記 #clrh99
ASP.NET WebAPI 体験記 #clrh99ASP.NET WebAPI 体験記 #clrh99
ASP.NET WebAPI 体験記 #clrh99
Katsuya Shimizu
 
わんくま同盟名古屋勉強会18回目 ASP.NET MVC3を利用したHTML5な画面開発~クラウドも有るよ!~
わんくま同盟名古屋勉強会18回目 ASP.NET MVC3を利用したHTML5な画面開発~クラウドも有るよ!~わんくま同盟名古屋勉強会18回目 ASP.NET MVC3を利用したHTML5な画面開発~クラウドも有るよ!~
わんくま同盟名古屋勉強会18回目 ASP.NET MVC3を利用したHTML5な画面開発~クラウドも有るよ!~normalian
 
WCF security
WCF securityWCF security
WCF securityexatex
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
John Lewis
 
WCF (Windows Communication Foundation)
WCF (Windows Communication Foundation)WCF (Windows Communication Foundation)
WCF (Windows Communication Foundation)ipower softwares
 
שרת לינוקס המשמש להפעלת שוחן עבודה מרוחק במעבדת מחשבים של תחנות חלשות
שרת לינוקס המשמש להפעלת שוחן עבודה מרוחק במעבדת מחשבים של תחנות חלשותשרת לינוקס המשמש להפעלת שוחן עבודה מרוחק במעבדת מחשבים של תחנות חלשות
שרת לינוקס המשמש להפעלת שוחן עבודה מרוחק במעבדת מחשבים של תחנות חלשות
Nadav Kavalerchik
 
Web2 And Library
Web2 And LibraryWeb2 And Library
Web2 And Library
smadi melamed
 
Mobile Web Best Practices Eyal Sela [Hebrew]
Mobile Web Best Practices   Eyal Sela [Hebrew]Mobile Web Best Practices   Eyal Sela [Hebrew]
Mobile Web Best Practices Eyal Sela [Hebrew]
Israeli Internet Association technology committee
 
דמואים, הדגמות קוד ומסגרות פיתוח חדשניים בטכנולוגיות ווב פתוחות
 דמואים, הדגמות קוד ומסגרות פיתוח חדשניים בטכנולוגיות ווב פתוחות דמואים, הדגמות קוד ומסגרות פיתוח חדשניים בטכנולוגיות ווב פתוחות
דמואים, הדגמות קוד ומסגרות פיתוח חדשניים בטכנולוגיות ווב פתוחותIsraeli Internet Association technology committee
 
Ado.Net - שיטות לעבודה עם בסיס נתונים בסביבת
Ado.Net - שיטות לעבודה עם בסיס נתונים בסביבתAdo.Net - שיטות לעבודה עם בסיס נתונים בסביבת
Ado.Net - שיטות לעבודה עם בסיס נתונים בסביבתLior Zamir
 
SQL - שפת הגדרת הנתונים
SQL - שפת הגדרת הנתוניםSQL - שפת הגדרת הנתונים
SQL - שפת הגדרת הנתונים
מורן אלקובי
 
בניית אתרים שיעור ראשון
בניית אתרים שיעור ראשוןבניית אתרים שיעור ראשון
בניית אתרים שיעור ראשון
alechko.name
 

Viewers also liked (18)

WCF tutorial
WCF tutorialWCF tutorial
WCF tutorial
 
Windows Communication Foundation (WCF)
Windows Communication Foundation (WCF)Windows Communication Foundation (WCF)
Windows Communication Foundation (WCF)
 
Windows Communication Foundation (WCF)
Windows Communication Foundation (WCF)Windows Communication Foundation (WCF)
Windows Communication Foundation (WCF)
 
Introduction to asp.net web api
Introduction to asp.net web apiIntroduction to asp.net web api
Introduction to asp.net web api
 
ASP.NET WebAPI 体験記 #clrh99
ASP.NET WebAPI 体験記 #clrh99ASP.NET WebAPI 体験記 #clrh99
ASP.NET WebAPI 体験記 #clrh99
 
わんくま同盟名古屋勉強会18回目 ASP.NET MVC3を利用したHTML5な画面開発~クラウドも有るよ!~
わんくま同盟名古屋勉強会18回目 ASP.NET MVC3を利用したHTML5な画面開発~クラウドも有るよ!~わんくま同盟名古屋勉強会18回目 ASP.NET MVC3を利用したHTML5な画面開発~クラウドも有るよ!~
わんくま同盟名古屋勉強会18回目 ASP.NET MVC3を利用したHTML5な画面開発~クラウドも有るよ!~
 
WCF security
WCF securityWCF security
WCF security
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
 
WCF (Windows Communication Foundation)
WCF (Windows Communication Foundation)WCF (Windows Communication Foundation)
WCF (Windows Communication Foundation)
 
שרת לינוקס המשמש להפעלת שוחן עבודה מרוחק במעבדת מחשבים של תחנות חלשות
שרת לינוקס המשמש להפעלת שוחן עבודה מרוחק במעבדת מחשבים של תחנות חלשותשרת לינוקס המשמש להפעלת שוחן עבודה מרוחק במעבדת מחשבים של תחנות חלשות
שרת לינוקס המשמש להפעלת שוחן עבודה מרוחק במעבדת מחשבים של תחנות חלשות
 
אחסון מידע - ל-websql ו-indexdb רן בר-זיק
אחסון מידע - ל-websql ו-indexdb רן בר-זיקאחסון מידע - ל-websql ו-indexdb רן בר-זיק
אחסון מידע - ל-websql ו-indexdb רן בר-זיק
 
SAPUI5 on SAP Web IDE
SAPUI5 on SAP Web IDESAPUI5 on SAP Web IDE
SAPUI5 on SAP Web IDE
 
Web2 And Library
Web2 And LibraryWeb2 And Library
Web2 And Library
 
Mobile Web Best Practices Eyal Sela [Hebrew]
Mobile Web Best Practices   Eyal Sela [Hebrew]Mobile Web Best Practices   Eyal Sela [Hebrew]
Mobile Web Best Practices Eyal Sela [Hebrew]
 
דמואים, הדגמות קוד ומסגרות פיתוח חדשניים בטכנולוגיות ווב פתוחות
 דמואים, הדגמות קוד ומסגרות פיתוח חדשניים בטכנולוגיות ווב פתוחות דמואים, הדגמות קוד ומסגרות פיתוח חדשניים בטכנולוגיות ווב פתוחות
דמואים, הדגמות קוד ומסגרות פיתוח חדשניים בטכנולוגיות ווב פתוחות
 
Ado.Net - שיטות לעבודה עם בסיס נתונים בסביבת
Ado.Net - שיטות לעבודה עם בסיס נתונים בסביבתAdo.Net - שיטות לעבודה עם בסיס נתונים בסביבת
Ado.Net - שיטות לעבודה עם בסיס נתונים בסביבת
 
SQL - שפת הגדרת הנתונים
SQL - שפת הגדרת הנתוניםSQL - שפת הגדרת הנתונים
SQL - שפת הגדרת הנתונים
 
בניית אתרים שיעור ראשון
בניית אתרים שיעור ראשוןבניית אתרים שיעור ראשון
בניית אתרים שיעור ראשון
 

Similar to ASP.NET Mvc 4 web api

Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST API
Rasan Samarasinghe
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API RecommendationsJeelani Shaik
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
Lorna Mitchell
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
Lorna Mitchell
 
Web api
Web apiWeb api
Rest WebAPI with OData
Rest WebAPI with ODataRest WebAPI with OData
Rest WebAPI with OData
Mahek Merchant
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
Lorna Mitchell
 
Evolution Of The Web Platform & Browser Security
Evolution Of The Web Platform & Browser SecurityEvolution Of The Web Platform & Browser Security
Evolution Of The Web Platform & Browser Security
Sanjeev Verma, PhD
 
Hypermedia for Machine APIs
Hypermedia for Machine APIsHypermedia for Machine APIs
Hypermedia for Machine APIs
Michael Koster
 
Hia 1691-using iib-to_support_api_economy
Hia 1691-using iib-to_support_api_economyHia 1691-using iib-to_support_api_economy
Hia 1691-using iib-to_support_api_economy
Andrew Coleman
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01
raviIITRoorkee
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1vikram singh
 
Api design and development
Api design and developmentApi design and development
Api design and development
oquidave
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technologyvikram singh
 
REST API Basics
REST API BasicsREST API Basics
REST API Basics
Tharindu Weerasinghe
 
Restful web services with java
Restful web services with javaRestful web services with java
Restful web services with java
Vinay Gopinath
 

Similar to ASP.NET Mvc 4 web api (20)

Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST API
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API Recommendations
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Basics of the Web Platform
Basics of the Web PlatformBasics of the Web Platform
Basics of the Web Platform
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Web api
Web apiWeb api
Web api
 
APITalkMeetupSharable
APITalkMeetupSharableAPITalkMeetupSharable
APITalkMeetupSharable
 
Rest WebAPI with OData
Rest WebAPI with ODataRest WebAPI with OData
Rest WebAPI with OData
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
Evolution Of The Web Platform & Browser Security
Evolution Of The Web Platform & Browser SecurityEvolution Of The Web Platform & Browser Security
Evolution Of The Web Platform & Browser Security
 
Hypermedia for Machine APIs
Hypermedia for Machine APIsHypermedia for Machine APIs
Hypermedia for Machine APIs
 
Hia 1691-using iib-to_support_api_economy
Hia 1691-using iib-to_support_api_economyHia 1691-using iib-to_support_api_economy
Hia 1691-using iib-to_support_api_economy
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Api design and development
Api design and developmentApi design and development
Api design and development
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
06 web api
06 web api06 web api
06 web api
 
Rest with Spring
Rest with SpringRest with Spring
Rest with Spring
 
REST API Basics
REST API BasicsREST API Basics
REST API Basics
 
Restful web services with java
Restful web services with javaRestful web services with java
Restful web services with java
 

Recently uploaded

DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
"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
Fwdays
 
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...
Jeffrey Haguewood
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 

Recently uploaded (20)

DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
"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
 
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...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 

ASP.NET Mvc 4 web api

  • 1. ASP.NET MVC 4 Web API Tiago Knoch – tiago.knoch@comtrade.com
  • 2. Contents • What is an API? • Why ASP.NET MVC Web API? • HyperText Transfer Protocol • REST • JSON • Introduction to Web API • Routing Table • Error & Exception Handling • Model Validation • Odata Protocol • Media Formatters • Security • HTTPClient • What Else? • Road Map
  • 3. What is an API? • An application programming interface (API) is a specification intended to be used as an interface by software components to communicate with each other. An API may include specifications for routines, data structures, object classes, and variables. • For the web this mean Web Services (SOAP + XML + WSDL) but in Web 2.0 we are moving away to REST Services (HTTP + XML/JSON) – Web API • Web APIs allow the combination of multiple services into new applications known as mashups.
  • 4. • Common examples: – Facebook, Twitter, Amazon, LinkedIn... Source: http://blogs.mulesoft.org/cloud-apis-and-the-new-spaghetti-factory/
  • 5. Why ASP.NET MVC Web Api? • Web Api – Defined in HTTP – Messages in Json/XML – RESTful – CRUD operations – Ready for Cloud
  • 6. HyperText Transfer Protocol • The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web. • HTTP functions as a request-response protocol in the client-server computing model. A web browser, for example, may be the client and an application running on a computer hosting a web site may be the server. • The client submits an HTTP request message to the server. The server, which provides resources such as HTML files and other content, or performs other functions on behalf of the client, returns a response message to the client. The response contains completion status information about the request and may also contain requested content in its message body.
  • 7. HTTP – Example GET GET / HTTP/1.1[CRLF] Host: www.google.rs[CRLF] User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1[CRLF] Accept-Encoding: gzip[CRLF] Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8[CRLF] Accept-Language: en-us,en;q=0.5[CRLF] Status: HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1354 Content: <HTML data>
  • 8. HTTP – Example POST POST /somepage.php HTTP/1.1 Host: example.com Content-Type: application/x-www-form-urlencoded Content-Length: 19 name=tiago&surname=knoch Status: HTTP/1.1 404 Not Found
  • 9. Rest - Representational State Transfer • REST is a style of software architecture for distributed systems such as the WWW, where, virtually in all cases, the HTTP protocol is used. • Uses CRUD actions (HTTP methods) CRUD Action HTTP Method Create Post Read Get Update Put Delete Delete • Each resource is represented by an global id (URI in HTTP) • The resources are conceptually separate from the representations that are returned to the client (JSON/XML) In many ways, the World Wide Web itself, based on HTTP, can be viewed as a REST-based architecture. Despite being simple, REST is fully-featured; there's basically nothing you can do in Web Services that can't be done with a RESTful architecture!
  • 10. JSON • JSON, or JavaScript Object Notation, is a text-based open standard designed for human-readable data interchange. It is derived from the JavaScript scripting language for representing simple data structures and associative arrays, called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for many languages.
  • 11. ASP.NET MVC Web API • MVC: Model -> View -> Controller • Create a Model • Create a controller
  • 12. Routing Table • Route is defined, by default, as api/{controller}/{id} where action is defined by an HTTP method (in global.asax Application_Start method). HTTP Method URI Path Action GET /api/products GetAllProducts GET /api/products/id GetProductById GET /api/products/?category=category GetProductsByCategory POST /api/products PostProduct PUT /api/products/id PutProduct DELETE /api/products/id DeleteProduct
  • 13. Routing Table The four main HTTP methods are mapped to CRUD operations: • GET retrieves the representation of the resource at a specified URI. GET should have no side effects on the server. • PUT updates a resource at a specified URI (idempotent). • POST creates a new resource. The server assigns the URI for the new object and returns this URI as part of the response message. • DELETE deletes a resource at a specified URI (idempotent).
  • 15. Error & Exception Handling • Response messages, errors and exceptions are translated to HTTP response status codes. • For example: – POST request should reply with HTTP status 201 (created). – DELETE request should reply with HTTP status 204 (no content). • But: – If a PUT/GET request is done with an invalid id, it should reply with HTTP status 404 (not found) – Or if a PUT request has an invalid model, it can reply with HTTP status 400 (bad request)
  • 16. Error & Exception Handling • By default, all .NET exceptions are translated into and HTTP response with status code 500 (internal error). • It is possible to register Exception filters:
  • 17. Model Validation • Like MVC, Web API supports Data Annotations (System.ComponentModel.DataAnnotations, .net 4.0). • If in your model there is a difference between 0 and not set, use nullable values.
  • 19. Model Validation – FilterAttribute Create a FilterAttribute Add it to Filters in Global.asax App_Start
  • 20. Odata Protocol • http://www.odata.org/ • “The Open Data Protocol (OData) is a Web protocol for querying and updating data. OData does this by applying and building upon Web technologies such as HTTP, Atom Publishing Protocol (AtomPub) and JSON to provide access to information from a variety of applications, services, and stores.” • In Web API we want to do something like this: /api/products?$top=3&$orderby=Name /api/products/?$filter=substringof('a', Name) eq true /api/products/?$filter=Price gt 5 /api/products/?$filter=Price gt 1 and Category eq 'Hardware'
  • 21. Odata Protocol • Change GET action method to return IQueryable<T> and to use Queryable attribute • Available as Nuget package (prerelease)! PM> Install-Package Microsoft.AspNet.WebApi.OData -Pre
  • 22. DEMO!
  • 23. Media Formatters • Web API only provides media formatters for JSON (using Json.NET library) and XML! • In HTTP, the format of message body is defined by the MIME type (media type): text/html, image/png, application/json, application/octet-stream • When the client sends an HTTP request, the Accept header tells the server wich media type it expects: Accept: text/html, application/json, application/xml; q=0.9, */*; q=0.01 • Web API uses media formatters to: – Read CLR objects from an HTTP message body (HTTP requests serializes to action methods parameters), – Write CLR objects to an HTTP message body (action methods returned objects serializes to HTTP replies) • You can create your own Media Formatter to serialize-deserialize your model types!
  • 24. Media Formatters - Example Define which http media type is supported Define which types can be deserialized
  • 25. Media Formatters - Example Deserialize type to stream Define formatter in global.asax App_Start
  • 26. Security • Support for the [Authorize] Attribute (System.Web.Http.AuthorizeAttribute)...but it only checks UserPrincipal.Identity.IsAuthenticated (Forms authentication). • For more secure options you need to implement a custom filter: – Tokens (ex, Public/Private Keys) – Oauth (http://oauth.net/) – OpenID (http://openid.net/) – Forms Authentication (already supported by ASP.NET) – Basic Http Authentication (username/password encrypted ) – SSL • Amazon S3 REST API uses a custom HTTP scheme based on a keyed-HMAC (Hash Message Authentication Code) for authentication. • The Facebook/Twitter/Google API use OAuth for authentication and authorization.
  • 27. Testing from a .NET client - HttpClient • HttpClient - Available in .NET 4.5 or NuGet package Microsoft.AspNet.WebApi.Client • Or use RestSharp (http://restsharp.org/)
  • 28. What else? • Improved support for IoC containers • Create help pages (IApiExplorer service) • Web API Project Template in VS 2012 • Scaffold controllers from Entity Framework model (like MVC) • Easy integration with Azure
  • 29. Road Map • MVC 4 was released in ASP.NET 4.5 with Visual Studio 2012 and .NET Framework 4.5. • Check out more at http://www.asp.net/web-api

Editor's Notes

  1. Currently around 7 thousand APIsImage – Most used APIs All-Time
  2. You can make a Web API not RESTful if you want!
  3. Content = Body
  4. When a web browser sends a POST request from a web form element, the default Internet media type is &quot;application/x-www-form-urlencoded&quot;.[1] This is a format for encoding key-value pairs with possibly duplicate keys. Each key-value pair is separated by an &apos;&amp;&apos; character, and each key is separated from its value by an &apos;=&apos; character. Keys and values are both escaped by replacing spaces with the &apos;+&apos; character and then using URL encoding on all other non-alphanumeric[2] characters. HTML form tag should contains method=&quot;post&quot;.
  5. Rest is abstract! It’s an architecture, not a protocol or framework. You can implement a REST architecture in web or desktop apps, in web services, in whatever you want.
  6. The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.Douglas Crockford was the first to specify and popularize the JSON format.[1]JSON was used at State Software, a company co-founded by Crockford, starting around 2001. The JSON.org website was launched in 2002. In December 2005, Yahoo! began offering some of its web services in JSON.[2]Google started offering JSON feeds for its GData web protocol in December 2006.[3]
  7. If a method throw NotImplementedException, this ExceptionFilter kicks in
  8. Package Manager Console
  9. Media formatter is defined during HTTP Content NegoiationContent Negotiation is composed of the following headers:Accept: which media types the client can acceptAccept-Charset: which character sets are acceptable (ex, UTF-8 or ISO 8859-1)Accept-Encoding: which content encodings are acceptable (ex, gzip)Accept-Language: which culture is acceptable (ex, en-us, sr-SP-Cyrl, pt-pt)
  10. This is an example for deserialization (Get, from server to http). The correspondent methods for serialization exist (CanReadType and WriteToStream)
  11. IoC = Inversion of controlIApiExplorer is a service that can get a complete runtime description of your web APIs.
  12. ASP.NET MVC 4 was released in 15th Aug 2012You can use ASP.NET MVC4 with VS 2010 and .NET 4 too!