Search Results

Search found 10 results on 1 pages for 'hateoas'.

Page 1/1 | 1 

  • Spring MVC, REST, and HATEOAS

    - by SingleShot
    I'm struggling with the correct way to implement Spring MVC 3.x RESTful services with HATEOAS. Consider the following constraints: I don't want my domain entities polluted with web/rest constructs. I don't want my controllers polluted with view constructs. I want to support multiple views. Currently I have a nicely put together MVC app without HATEOAS. Domain entities are pure POJOs without any view or web/rest concepts embedded. For example: class User { public String getName() {...} public String setName(String name) {...} ... } My controllers are also simple. They provide routing and status, and delegate to Spring's view resolution framework. Note my application supports JSON, XML, and HTML, yet no domain entities or controllers have embedded view information: @Controller @RequestMapping("/users") class UserController { @RequestMapping public ModelAndView getAllUsers() { List<User> users = userRepository.findAll(); return new ModelAndView("users/index", "users", users); } @RequestMapping("/{id}") public ModelAndView getUser(@PathVariable Long id) { User user = userRepository.findById(id); return new ModelAndView("users/show", "user", user); } } So, now my issue - I'm not sure of a clean way to support HATEOAS. Here's an example. Let's say when the client asks for a User in JSON format, it comes out like this: { firstName: "John", lastName: "Smith" } Let's also say that when I support HATEOAS, I want the JSON to contain a simple "self" link that the client can then use to refresh the object, delete it, or something else. It might also have a "friends" link indicating how to get the user's list of friends: { firstName: "John", lastName: "Smith", links: [ { rel: "self", ref: "http://myserver/users/1" }, { rel: "friends", ref: "http://myserver/users/1/friends" } ] } Somehow I want to attach links to my object. I feel the right place to do this is in the controller layer as the controllers all know the correct URLs. Additionally, since I support multiple views, I feel like the right thing to do is somehow decorate my domain entities in the controller before they are converted to JSON/XML/whatever in Spring's view resolution framework. One way to do this might be to wrap the POJO in question with a generic Resource class that contains a list of links. Some view tweaking would be required to crunch it into the format I want, but its doable. Unfortunately nested resources could not be wrapped in this way. Other things that come to mind include adding links to the ModelAndView, and then customizing each of Spring's out-of-the-box view resolvers to stuff links into the generated JSON/XML/etc. What I don't want is to be constantly hand-crafting JSON/XML/etc. to accommodate various links as they come and go during the course of development. Thoughts?

    Read the article

  • HATEOAS - Discovery and URI Templating

    - by Paul Kirby
    I'm designing a HATEOAS API for internal data at my company, but have been having troubles with the discovery of links. Consider the following set of steps for someone to retrieve information about a specific employee in this system: User sends GET to http://coredata/ to get all available resources, returns a number of links including one tagged as rel = "http://coredata/rels/employees" User follows HREF on the rel from the first request, performing a GET at (for example) http://coredata/employees The data returned from this last call is my conundrum and a situation where I've heard mixed suggestions. Here are some of them: That GET will return all employees (with perhaps truncated data), and the client would be responsible for picking the one it wants from that list. That GET would return a number of URI templated links describing how to query / get one employee / get all employees. Something like: "_links": { "http://coredata/rels/employees#RetrieveOne": { "href": "http://coredata/employees/{id}" }, "http://coredata/rels/employees#Query": { "href": "http://coredata/employees{?login,firstName,lastName}" }, "http://coredata/rels/employees#All": { "href": "http://coredata/employees/all" } } I'm a little stuck here with what remains closest to HATEOAS. For option 1, I really do not want to make my clients retrieve all employees every time for the sake of navigation, but I can see how using URI templating in example two introduces some out-of-band knowledge. My other thought was to use the RetrieveOne, Query, and All operations as my cool URLs, but that seems to violate the concept that you should be able to navigate to the resources you want from one base URI. Has anyone else managed to come up with a good way to handle this? Navigation is dead simple once you've retrieved one resource or a set of resources, but it seems very difficult to use for discovery.

    Read the article

  • "Invalid operation" status code in a HATEOAS REST API

    - by FinnNk
    In a HATEOAS API links are returned which represent possible state transitions. A conforming client should just be retrieving and following those links, but if a non-conforming client is constructing URIs rather than following the supplied links what would be the most appropriate status code/response to return? 400 would work, together with some information in the response body - this is what we're currently doing 403 I guess would be wrong, as it implies that the request could never work - but potentially the link may be available in the future 404 sounds plausible - at this point in time the resource doesn't exist What do people think? I know that conditional requests can handle requests based on stale responses (resulting in e.g. 412s), but this is a slightly different situation.

    Read the article

  • Is That REST API Really RPC? Roy Fielding Seems to Think So.

    - by Rich Apodaca
    A large amount of what I thought I knew about REST is apparently wrong - and I'm not alone. This question has a long lead-in, but it seems to be necessary because the information is a bit scattered. The actual question comes at the end if you're already familiar with this topic. From the first paragraph of Roy Fielding's REST APIs must be hypertext-driven, it's pretty clear he believes his work is being widely misinterpreted: I am getting frustrated by the number of people calling any HTTP-based interface a REST API. Today’s example is the SocialSite REST API. That is RPC. It screams RPC. There is so much coupling on display that it should be given an X rating. Fielding goes on to list several attributes of a REST API. Some of them seem to go against both common practice and common advice on SO and other forums. For example: A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types that are appropriate for the intended audience (i.e., expected to be understood by any client that might use the API). ... A REST API must not define fixed resource names or hierarchies (an obvious coupling of client and server). ... A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types. ... The idea of "hypertext" plays a central role - much more so than URI structure or what HTTP verbs mean. "Hypertext" is defined in one of the comments: When I [Fielding] say hypertext, I mean the simultaneous presentation of information and controls such that the information becomes the affordance through which the user (or automaton) obtains choices and selects actions. Hypermedia is just an expansion on what text means to include temporal anchors within a media stream; most researchers have dropped the distinction. Hypertext does not need to be HTML on a browser. Machines can follow links when they understand the data format and relationship types. I'm guessing at this point, but the first two points above seem to suggest that API documentation for a Foo resource that looks like the following leads to tight coupling between client and server and has no place in a RESTful system. GET /foos/{id} # read a Foo POST /foos/{id} # create a Foo PUT /foos/{id} # update a Foo Instead, an agent should be forced to discover the URIs for all Foos by, for example, issuing a GET request against /foos. (Those URIs may turn out to follow the pattern above, but that's beside the point.) The response uses a media type that is capable of conveying how to access each item and what can be done with it, giving rise to the third point above. For this reason, API documentation should focus on explaining how to interpret the hypertext contained in the response. Furthermore, every time a URI to a Foo resource is requested, the response contains all of the information needed for an agent to discover how to proceed by, for example, accessing associated and parent resources through their URIs, or by taking action after the creation/deletion of a resource. The key to the entire system is that the response consists of hypertext contained in a media type that itself conveys to the agent options for proceeding. It's not unlike the way a browser works for humans. But this is just my best guess at this particular moment. Fielding posted a follow-up in which he responded to criticism that his discussion was too abstract, lacking in examples, and jargon-rich: Others will try to decipher what I have written in ways that are more direct or applicable to some practical concern of today. I probably won’t, because I am too busy grappling with the next topic, preparing for a conference, writing another standard, traveling to some distant place, or just doing the little things that let me feel I have I earned my paycheck. So, two simple questions for the REST experts out there with a practical mindset: how do you interpret what Fielding is saying and how do you put it into practice when documenting/implementing REST APIs? Edit: this question is an example of how hard it can be to learn something if you don't have a name for what you're talking about. The name in this case is "Hypermedia as the Engine of Application State" (HATEOAS).

    Read the article

  • On REST: WADL or not IDL, is the following approach right ?

    - by redben
    This question is a bit long, please bear with me. In REST, i think we should not need WADL or any IDL. But rather something that would implicitly cover its concept. The way I think about it is when we (humans) surf the Web, when we go to a web site for the first time, we don't know what services it provides. You discover those on the html home page (or a sitemap page in a help section) or maybe just the main menu on the home page. If you make an analogy, the homepage or site map to us humans is what WSDL is to WS-* or what WADL could be to a REST service. Only that its just like any other html content. I think that in REST the following is a good way to do things, respecting the HATEOS paradigm. Have a top level (or default) resource that lists links to your other resources. For a library example, say RestLibrary.com/ it could be something like: <root xmlns:lib="http://librarystandards.com/libraryml"> <resource class="lib:book"> <link type="application/vnd.libraryml+xml" template="mylib.com/book/{isbn}" /> <link type="application/vnd.libraryml+xml" rel="add" href="mylib.com/book" method="POST" /> <link type="application/vnd.libraryml+xml" rel="update" template="mylib.com/book/{isbn}" method="PUT" /> </resource> <resource class="lib:bookList"> <link template="mylib.com/book?keywords={keywords}" type="application/vnd.openlibrary+xml" rel="search" /> </resource> </root> Note that it is assumed that the media type "application/vnd.libraryml+xml" is a defined standard or (may be just proprietary vocabulary) named libraryml. Also, the client should be able to understand this "homepage" resource (elements root, resource and link). This is the part that could be used instead of WADL : an Abstract vocabulary that should be understandable by any client. You could use an existing standard like Atom for example. But the main idea is to have an abstract vocabulary understandable by any client. Why not WADL then ? well wadl is only for service discovery. The idea here is to have an light abstract vocabulary that would serve as a base for hypermedia. A "root" vocabulary. Like in owl we have owl:thing...etc Now if the client knows the "libraryml" standard it can follow the links to the things it understands (after parsing the media type properties and xmlns). If not, it just won't. When i can't understand how to deal with something in REST architecture i tend to see how we Humans do it in the Web. In the Web, we have the Generic language that is HTML that enables site builders to deliver any specific content, regardless of its meaning to the client (the user), Browsers understand HTML but not the "meaning" of its content. It is the user that understands the (domain specific) content. If i go to say QuantumPhysics.org, my browser can render the home page (it is just html after all) and i can read the home page. If i understand quantum then fine i can continue browsing. If i don't i just get out (unless i want to learn the hardway :) ) In the RetsLibrary.com example the client app is just like me+my browser on QuantumPhysics.org. the media type "application/vnd.libraryml+xml" is quantum physics (knowledge). http is http in both examples. Now HTML of QuantumPhysics.org is in RestLibrary.com is XML + that tiny little abstract vocabulary (root resource and link, that you could replace with something like Atom). So does this approach have any value ? don't we need a root tiny hyper-vocabulary so we can succeed with hypermedia and the "initial URI" concept ? edit Yeah why not RDF as the root vocabulary !

    Read the article

  • RESTful Java on Steroids (Parleys, Podcast, ...)

    - by alexismp
    As reported previously here, the JAX-RS 2.0 (JSR 339) expert group is making good progress. If you're interested in what the future holds for RESTful Java web services, you can now watch Marek's Devoxx presentation or listen to him in the latest Java Spotlight Podcast (#74). Marek discusses the new client API, filters/handlers, BeanValidation integration, Hypermedia support (HATEOAS), server-side async processing and more. With JSR 339's Early Draft Review 2 currently out, another draft review is planned for April, the public review should be available in June while the final draft is currently scheduled for the end of the summer. In short, expect completion sometime before the end of 2012.

    Read the article

  • JavaOne Latin America Sessions

    - by Tori Wieldt
    The stars of Java are gathering in São Paulo next week. Here are just a few of the outstanding sessions you can attend at JavaOne Latin America: “Designing Java EE Applications in the Age of CDI” Michel Graciano, Michael Santos “Don’t Get Hacked! Tips and Tricks for Securing Your Java EE Web Application” Fabiane Nardon, Fernando Babadopulos “Java and Security Programming” Juan Carlos Herrera “Java Craftsmanship: Lessons Learned on How to Produce Truly Beautiful Java Code” Edson Yanaga “Internet of Things with Real Things: Java + Things – API + Raspberry PI + Toys!” Vinicius Senger “OAuth 101: How to Protect Your Resources in a Web-Connected Environment” Mauricio Leal “Approaching Pure REST in Java: HATEOAS and HTTP Tuning” Eder Ignatowicz “Open Data in Politics: Using Java to Follow Your Candidate” Bruno Gualda, Thiago Galbiatti Vespa "Java EE 7 Platform: More Productivity and Integrated HTML" Arun Gupta  Go to the JavaOne site for a complete list of sessions. JavaOne Latin America will in São Paulo, 4-6 December 2012 at the Transamerica Expo Center. Register by 3 December and Save R$ 300,00! Para mais informações ou inscrição ligue para (11) 2875-4163. 

    Read the article

  • Cloud Application Management for Platforms

    - by user756764
    Today Oracle, along with CloudBees, Cloudsoft, Huawei, Rackspace, Red Hat, and Software AG, published the Cloud Application Management for Platforms (CAMP) specification. This spec deals with application management in the context of PaaS. It defines a model (consisting of a set resources and their relationships), a REST-based API for manipulating that model, and a packaging format for getting applications (and their attendant metadata) into and out of the platform. My colleague, Mark Carlson, has already provided an excellent writeup on the spec here. The following, additional points bear emphasizing: CAMP is language, framework and platform neutral; it should be equally applicable to the task of deploying and managing Ruby on Rails applications as Java/Spring applications (as Node.js applications, etc.) CAMP only covers the interactions between a Cloud Consumer and a Cloud Provider (using the definitions of these terms provided in the NIST Cloud Computing Reference Architecture). The internal APIs used by the Cloud Provider to, for example, deploy additional platform services (e.g. a new message queuing service) are out of CAMP's scope. CAMP supports the management of the entire lifecycle of the application (e.g. start/stop, suspend/resume, etc.) not just the deployment of the components that make up the application. Complexity is the antithesis of interoperability. One of CAMP's goals is to be as broadly interoperable as possible. To this end, the authors of CAMP tried to "make things as simple as possible, but no simpler". For example, JSON is the only serialization format used in the spec (although Providers can extend this to support additional serialization formats such as XML). It remains to be seen whether we can preserve this simplicity as the spec is processed by OASIS. So far, those who have indicated an interest in collaborating on the spec seem to be of a like mind with regards to the need for simplicity. The flip side to simplicity is the knowledge that you undoubtedly missed something that is important to someone. To make up for this, CAMP is designed to be extensible. The idea is to ship what we know will work, allow implementers to extend the spec, then re-factor the spec to incorporate the most popular extensions. Anyone interested in this effort, particularly those of you using PaaS-level services, is encouraged to join the forthcoming OASIS TC. As you may have noticed, CAMP is a bit of a departure from some of the more monolithic management standards that have preceded it. The idea is to develop simple, discrete standards targeted to address specific interoperability and portability problems and tie these standards together with common patterns based on REST and HATEOAS. I'm excited to see how this idea plays out.

    Read the article

  • Java???????·????????Java EE????JAX-RS 2.0??????Java Developers Workshop 2012 Summer????

    - by ???02
    ???Java??????????????????1?????“GlassFish Guy”??????????????·????????????·????????????8???????Java Developers Workshop 2012 Summer???????????????Java EE????2??????????????????????????????????(???) Java EE??????“????·?????”????? ??????·?????????Java????????????·???? Java??????????????????????????????Java??????????Java????????·????????????????????????????????Java????????Java EE 7?JAX-RS?????????????????? 1?????????Java EE 7 and HTML5: Developing for the Cloud????????Java EE??????????????·?????????????????????????????????? Java EE?????????2009?10?????????Java EE 6??????????????????????????4,000????????????????17?????????·????Java EE 6??????????????Java EE 6?????????????????????Java EE 6??????10??????? ?????????????????WAR???????????EJB??? ????Java EE???EJB????·???????????????????????????·???????(DD)?????????????????????Java EE 6????????????EJB?“?????”?????????POJO????????????????EJB????????????????????POJO?WAR??????????????????????DD???????????????????????????????????????(????) ??1??????????????????CDI(Context Dependency Injection)????DI????Java EE 5??????????????????????????????????Java EE 6?CDI???????????·?????????????DI???????????????????Spring Framework??????????????????????????Java EE???DI??????????????????????? ????????????Java EE????????????????????????????Amazon Web Services?Windows Azure????IaaS?Google App Engine????PaaS?Salesforce.com????SaaS?????????????????????·?????????????????????????????????????????????????????????????? ????????Java EE???????????????????????????????Java EE?????????????????·????????????Java EE??????????????????????????????????????????·?????????????? ??????????????????Java EE 7??????????????Java EE 8??????·??????????????????????????HTML5??3???????????????????????????????????????????????????????????????? ?????Java EE???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ?????Cloud Application Service(??)??????????????????????????????????????????????????????????????????????????????? ???HTML5??????“Web??????·??????”????JSON?WebSockets??????????????Java EE???????????????Web????????????????????????WebSocket???????????????????????·?????????????WebSocket?????Java EE????????????????????????????? ???Java EE 7????????API????????????????????? ??????????????????·?????????????????????·????????????????????????????5??API??Java EE 7??????????????????????????????????????????????????????????????????????????????????????????????????????????????????(????)???? Java EE 7?????????????????API????????????????????????????2013??2??????????????????????????????????????????????????????????????????Web???(http://javaee-spec.java.net/)???????????????????????????????? ??????????Project Avatar???????????Project Avatar??????????Java????????????????????????????Java????????????HTML5???????????????????????????HTML?Java???????????????????????Java EE???????????????????????????????? JAX-RS 2.0?Java??????????????????? ???????2?????????JAX-RS 2.0: RESTful Java on Steroids???Java????RESTful?????????????API???JAX-RS?????Java EE 7???????JAX-RS 2.0???????????????????????????????? ?????????“RESTful”???????????????????? ????????????????????????????? ?????????????? ???????????????? ??????????????(??)??? ????????????????????(?????????????????) ????Java EE????????API?????????????JAX-RS 1.0??JAX-RS 1.0???POJO????API???HTTP??????????????????????????????????????????????? ????????????JAX-RS 2.0???????????8??????????/???????????? ?Client API ?Client-side and Server-side Asynchronous ?Filters and Interceptors ?Improved Connection Negotiation ?Validation ?Hypermedia ?Alignment with JSR 330 ?Model-View-Controller JAX-RS 2.0??????????????·????????????????????Model-View-Controller?????????????????????Model-View-Controller?????????JSF????MVC???????????????JAX-RS???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ???Client API???????????????HTTP??????·????????????????????????API???????????????JAX-RS 2.0?Client API???JAX-RS?????API??????????????Java EE?????????????REST??????????????????? ?Filters&Interceptors????????????????????????JAX-RS??????????????????JAX-RS 1.0???????????JAX-RS 2.0??????????????????????? ?Asynchronus??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ?Connect Negotiation???Validation???????????????????????Validation????????????????Bean Validation?????JAX-RS?????????????????????????? ?Hypermedia???????????????????Web???????????????????HATEOAS(Hypermedia As The Engine Of App State)?????JAX-RS????????????????????????????????Asynchronus???????????????????????????? JAX-RS 2.0???????????JSR 330:Dependency Injection for Java???????????????????Client API??????????????????????????????????????JAX-RS 2.0??????????????????????Web???????????·??????????(http://jcp.org/en/jsr/detail?id=339)????????????????????????????????????????

    Read the article

  • ASPNET WebAPI REST Guidance

    - by JoshReuben
    ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. While I may be more partial to NodeJS these days, there is no denying that WebAPI is a well engineered framework. What follows is my investigation of how to leverage WebAPI to construct a RESTful frontend API.   The Advantages of REST Methodology over SOAP Simpler API for CRUD ops Standardize Development methodology - consistent and intuitive Standards based à client interop Wide industry adoption, Ease of use à easy to add new devs Avoid service method signature blowout Smaller payloads than SOAP Stateless à no session data means multi-tenant scalability Cache-ability Testability   General RESTful API Design Overview · utilize HTTP Protocol - Usage of HTTP methods for CRUD, standard HTTP response codes, common HTTP headers and Mime Types · Resources are mapped to URLs, actions are mapped to verbs and the rest goes in the headers. · keep the API semantic, resource-centric – A RESTful, resource-oriented service exposes a URI for every piece of data the client might want to operate on. A REST-RPC Hybrid exposes a URI for every operation the client might perform: one URI to fetch a piece of data, a different URI to delete that same data. utilize Uri to specify CRUD op, version, language, output format: http://api.MyApp.com/{ver}/{lang}/{resource_type}/{resource_id}.{output_format}?{key&filters} · entity CRUD operations are matched to HTTP methods: · Create - POST / PUT · Read – GET - cacheable · Update – PUT · Delete - DELETE · Use Uris to represent a hierarchies - Resources in RESTful URLs are often chained · Statelessness allows for idempotency – apply an op multiple times without changing the result. POST is non-idempotent, the rest are idempotent (if DELETE flags records instead of deleting them). · Cache indication - Leverage HTTP headers to label cacheable content and indicate the permitted duration of cache · PUT vs POST - The client uses PUT when it determines which URI (Id key) the new resource should have. The client uses POST when the server determines they key. PUT takes a second param – the id. POST creates a new resource. The server assigns the URI for the new object and returns this URI as part of the response message. Note: The PUT method replaces the entire entity. That is, the client is expected to send a complete representation of the updated product. If you want to support partial updates, the PATCH method is preferred DELETE deletes a resource at a specified URI – typically takes an id param · Leverage Common HTTP Response Codes in response headers 200 OK: Success 201 Created - Used on POST request when creating a new resource. 304 Not Modified: no new data to return. 400 Bad Request: Invalid Request. 401 Unauthorized: Authentication. 403 Forbidden: Authorization 404 Not Found – entity does not exist. 406 Not Acceptable – bad params. 409 Conflict - For POST / PUT requests if the resource already exists. 500 Internal Server Error 503 Service Unavailable · Leverage uncommon HTTP Verbs to reduce payload sizes HEAD - retrieves just the resource meta-information. OPTIONS returns the actions supported for the specified resource. PATCH - partial modification of a resource. · When using PUT, POST or PATCH, send the data as a document in the body of the request. Don't use query parameters to alter state. · Utilize Headers for content negotiation, caching, authorization, throttling o Content Negotiation – choose representation (e.g. JSON or XML and version), language & compression. Signal via RequestHeader.Accept & ResponseHeader.Content-Type Accept: application/json;version=1.0 Accept-Language: en-US Accept-Charset: UTF-8 Accept-Encoding: gzip o Caching - ResponseHeader: Expires (absolute expiry time) or Cache-Control (relative expiry time) o Authorization - basic HTTP authentication uses the RequestHeader.Authorization to specify a base64 encoded string "username:password". can be used in combination with SSL/TLS (HTTPS) and leverage OAuth2 3rd party token-claims authorization. Authorization: Basic sQJlaTp5ZWFslylnaNZ= o Rate Limiting - Not currently part of HTTP so specify non-standard headers prefixed with X- in the ResponseHeader. X-RateLimit-Limit: 10000 X-RateLimit-Remaining: 9990 · HATEOAS Methodology - Hypermedia As The Engine Of Application State – leverage API as a state machine where resources are states and the transitions between states are links between resources and are included in their representation (hypermedia) – get API metadata signatures from the response Link header - in a truly REST based architecture any URL, except the initial URL, can be changed, even to other servers, without worrying about the client. · error responses - Do not just send back a 200 OK with every response. Response should consist of HTTP error status code (JQuery has automated support for this), A human readable message , A Link to a meaningful state transition , & the original data payload that was problematic. · the URIs will typically map to a server-side controller and a method name specified by the type of request method. Stuff all your calls into just four methods is not as crazy as it sounds. · Scoping - Path variables look like you’re traversing a hierarchy, and query variables look like you’re passing arguments into an algorithm · Mapping URIs to Controllers - have one controller for each resource is not a rule – can consolidate - route requests to the appropriate controller and action method · Keep URls Consistent - Sometimes it’s tempting to just shorten our URIs. not recommend this as this can cause confusion · Join Naming – for m-m entity relations there may be multiple hierarchy traversal paths · Routing – useful level of indirection for versioning, server backend mocking in development ASPNET WebAPI Considerations ASPNET WebAPI implements a lot (but not all) RESTful API design considerations as part of its infrastructure and via its coding convention. Overview When developing an API there are basically three main steps: 1. Plan out your URIs 2. Setup return values and response codes for your URIs 3. Implement a framework for your API.   Design · Leverage Models MVC folder · Repositories – support IoC for tests, abstraction · Create DTO classes – a level of indirection decouples & allows swap out · Self links can be generated using the UrlHelper · Use IQueryable to support projections across the wire · Models can support restful navigation properties – ICollection<T> · async mechanism for long running ops - return a response with a ticket – the client can then poll or be pushed the final result later. · Design for testability - Test using HttpClient , JQuery ( $.getJSON , $.each) , fiddler, browser debug. Leverage IDependencyResolver – IoC wrapper for mocking · Easy debugging - IE F12 developer tools: Network tab, Request Headers tab     Routing · HTTP request method is matched to the method name. (This rule applies only to GET, POST, PUT, and DELETE requests.) · {id}, if present, is matched to a method parameter named id. · Query parameters are matched to parameter names when possible · Done in config via Routes.MapHttpRoute – similar to MVC routing · Can alternatively: o decorate controller action methods with HttpDelete, HttpGet, HttpHead,HttpOptions, HttpPatch, HttpPost, or HttpPut., + the ActionAttribute o use AcceptVerbsAttribute to support other HTTP verbs: e.g. PATCH, HEAD o use NonActionAttribute to prevent a method from getting invoked as an action · route table Uris can support placeholders (via curly braces{}) – these can support default values and constraints, and optional values · The framework selects the first route in the route table that matches the URI. Response customization · Response code: By default, the Web API framework sets the response status code to 200 (OK). But according to the HTTP/1.1 protocol, when a POST request results in the creation of a resource, the server should reply with status 201 (Created). Non Get methods should return HttpResponseMessage · Location: When the server creates a resource, it should include the URI of the new resource in the Location header of the response. public HttpResponseMessage PostProduct(Product item) {     item = repository.Add(item);     var response = Request.CreateResponse<Product>(HttpStatusCode.Created, item);     string uri = Url.Link("DefaultApi", new { id = item.Id });     response.Headers.Location = new Uri(uri);     return response; } Validation · Decorate Models / DTOs with System.ComponentModel.DataAnnotations properties RequiredAttribute, RangeAttribute. · Check payloads using ModelState.IsValid · Under posting – leave out values in JSON payload à JSON formatter assigns a default value. Use with RequiredAttribute · Over-posting - if model has RO properties à use DTO instead of model · Can hook into pipeline by deriving from ActionFilterAttribute & overriding OnActionExecuting Config · Done in App_Start folder > WebApiConfig.cs – static Register method: HttpConfiguration param: The HttpConfiguration object contains the following members. Member Description DependencyResolver Enables dependency injection for controllers. Filters Action filters – e.g. exception filters. Formatters Media-type formatters. by default contains JsonFormatter, XmlFormatter IncludeErrorDetailPolicy Specifies whether the server should include error details, such as exception messages and stack traces, in HTTP response messages. Initializer A function that performs final initialization of the HttpConfiguration. MessageHandlers HTTP message handlers - plug into pipeline ParameterBindingRules A collection of rules for binding parameters on controller actions. Properties A generic property bag. Routes The collection of routes. Services The collection of services. · Configure JsonFormatter for circular references to support links: PreserveReferencesHandling.Objects Documentation generation · create a help page for a web API, by using the ApiExplorer class. · The ApiExplorer class provides descriptive information about the APIs exposed by a web API as an ApiDescription collection · create the help page as an MVC view public ILookup<string, ApiDescription> GetApis()         {             return _explorer.ApiDescriptions.ToLookup(                 api => api.ActionDescriptor.ControllerDescriptor.ControllerName); · provide documentation for your APIs by implementing the IDocumentationProvider interface. Documentation strings can come from any source that you like – e.g. extract XML comments or define custom attributes to apply to the controller [ApiDoc("Gets a product by ID.")] [ApiParameterDoc("id", "The ID of the product.")] public HttpResponseMessage Get(int id) · GlobalConfiguration.Configuration.Services – add the documentation Provider · To hide an API from the ApiExplorer, add the ApiExplorerSettingsAttribute Plugging into the Message Handler pipeline · Plug into request / response pipeline – derive from DelegatingHandler and override theSendAsync method – e.g. for logging error codes, adding a custom response header · Can be applied globally or to a specific route Exception Handling · Throw HttpResponseException on method failures – specify HttpStatusCode enum value – examine this enum, as its values map well to typical op problems · Exception filters – derive from ExceptionFilterAttribute & override OnException. Apply on Controller or action methods, or add to global HttpConfiguration.Filters collection · HttpError object provides a consistent way to return error information in the HttpResponseException response body. · For model validation, you can pass the model state to CreateErrorResponse, to include the validation errors in the response public HttpResponseMessage PostProduct(Product item) {     if (!ModelState.IsValid)     {         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); Cookie Management · Cookie header in request and Set-Cookie headers in a response - Collection of CookieState objects · Specify Expiry, max-age resp.Headers.AddCookies(new CookieHeaderValue[] { cookie }); Internet Media Types, formatters and serialization · Defaults to application/json · Request Accept header and response Content-Type header · determines how Web API serializes and deserializes the HTTP message body. There is built-in support for XML, JSON, and form-urlencoded data · customizable formatters can be inserted into the pipeline · POCO serialization is opt out via JsonIgnoreAttribute, or use DataMemberAttribute for optin · JSON serializer leverages NewtonSoft Json.NET · loosely structured JSON objects are serialzed as JObject which derives from Dynamic · to handle circular references in json: json.SerializerSettings.PreserveReferencesHandling =    PreserveReferencesHandling.All à {"$ref":"1"}. · To preserve object references in XML [DataContract(IsReference=true)] · Content negotiation Accept: Which media types are acceptable for the response, such as “application/json,” “application/xml,” or a custom media type such as "application/vnd.example+xml" Accept-Charset: Which character sets are acceptable, such as UTF-8 or ISO 8859-1. Accept-Encoding: Which content encodings are acceptable, such as gzip. Accept-Language: The preferred natural language, such as “en-us”. o Web API uses the Accept and Accept-Charset headers. (At this time, there is no built-in support for Accept-Encoding or Accept-Language.) · Controller methods can take JSON representations of DTOs as params – auto-deserialization · Typical JQuery GET request: function find() {     var id = $('#prodId').val();     $.getJSON("api/products/" + id,         function (data) {             var str = data.Name + ': $' + data.Price;             $('#product').text(str);         })     .fail(         function (jqXHR, textStatus, err) {             $('#product').text('Error: ' + err);         }); }            · Typical GET response: HTTP/1.1 200 OK Server: ASP.NET Development Server/10.0.0.0 Date: Mon, 18 Jun 2012 04:30:33 GMT X-AspNet-Version: 4.0.30319 Cache-Control: no-cache Pragma: no-cache Expires: -1 Content-Type: application/json; charset=utf-8 Content-Length: 175 Connection: Close [{"Id":1,"Name":"TomatoSoup","Price":1.39,"ActualCost":0.99},{"Id":2,"Name":"Hammer", "Price":16.99,"ActualCost":10.00},{"Id":3,"Name":"Yo yo","Price":6.99,"ActualCost": 2.05}] True OData support · Leverage Query Options $filter, $orderby, $top and $skip to shape the results of controller actions annotated with the [Queryable]attribute. [Queryable]  public IQueryable<Supplier> GetSuppliers()  · Query: ~/Suppliers?$filter=Name eq ‘Microsoft’ · Applies the following selection filter on the server: GetSuppliers().Where(s => s.Name == “Microsoft”)  · Will pass the result to the formatter. · true support for the OData format is still limited - no support for creates, updates, deletes, $metadata and code generation etc · vnext: ability to configure how EditLinks, SelfLinks and Ids are generated Self Hosting no dependency on ASPNET or IIS: using (var server = new HttpSelfHostServer(config)) {     server.OpenAsync().Wait(); Tracing · tracability tools, metrics – e.g. send to nagios · use your choice of tracing/logging library, whether that is ETW,NLog, log4net, or simply System.Diagnostics.Trace. · To collect traces, implement the ITraceWriter interface public class SimpleTracer : ITraceWriter {     public void Trace(HttpRequestMessage request, string category, TraceLevel level,         Action<TraceRecord> traceAction)     {         TraceRecord rec = new TraceRecord(request, category, level);         traceAction(rec);         WriteTrace(rec); · register the service with config · programmatically trace – has helper extension methods: Configuration.Services.GetTraceWriter().Info( · Performance tracing - pipeline writes traces at the beginning and end of an operation - TraceRecord class includes aTimeStamp property, Kind property set to TraceKind.Begin / End Security · Roles class methods: RoleExists, AddUserToRole · WebSecurity class methods: UserExists, .CreateUserAndAccount · Request.IsAuthenticated · Leverage HTTP 401 (Unauthorized) response · [AuthorizeAttribute(Roles="Administrator")] – can be applied to Controller or its action methods · See section in WebApi document on "Claim-based-security for ASP.NET Web APIs using DotNetOpenAuth" – adapt this to STS.--> Web API Host exposes secured Web APIs which can only be accessed by presenting a valid token issued by the trusted issuer. http://zamd.net/2012/05/04/claim-based-security-for-asp-net-web-apis-using-dotnetopenauth/ · Use MVC membership provider infrastructure and add a DelegatingHandler child class to the WebAPI pipeline - http://stackoverflow.com/questions/11535075/asp-net-mvc-4-web-api-authentication-with-membership-provider - this will perform the login actions · Then use AuthorizeAttribute on controllers and methods for role mapping- http://sixgun.wordpress.com/2012/02/29/asp-net-web-api-basic-authentication/ · Alternate option here is to rely on MVC App : http://forums.asp.net/t/1831767.aspx/1

    Read the article

1