I'm doing some R&D on what seems like a very confusing topic, I've also read quite a few of the other SO questions, but I feel my question might be unique enough to warrant me asking. We've never developed an app using pure WebAPI.
We're trying to write a SPA style app, where the back end is fully decoupled from the front end code
Assuming our service does not know anything about who is accessing/consuming it:
WebAPI seems like the logical route to serve data, as opposed to using the standard MVC controllers, and serving our data via an action result and converting it to JSON. This to me at least seems like an MC design... which seems odd, and not what MVC was meant for.
(look mom... no view)
What would be considered normal convention in terms of performing action(y) calls?
My sense is that my understanding of WebAPI is incorrect.
The way I perceive WebAPI, is that its meant to be used in a CRUD sense, but what if I want to do something like: "InitialiseMonthEndPayment".... Would I need to create a WebAPI controller, called InitialiseMonthEndPaymentController, and then perform a POST... Seems a bit weird, as opposed to a MVC controller where i can just add a new action on the MonthEnd controller called InitialisePayment.
Or does this require a mindset shift in terms of design?
Any further links on this topic will be really useful, as my fear is we implement something that might be weird an could turn into a coding/maintenance concern later on?
If you are planning to make your services RESTful, the controller should represent a resource. In your example, the resource is Payment, so the controller would be called PaymentController.
You can have multiple POST methods in the same controller. In your scenario, I would call the action method PostMonthlyPayment or something similar. The URL (routing) would look like http://server.com/api/payment/monthly and the body (assuming JSON) would be something like:
{
user: user#internet.com,
month: 10,
year: 2013,
// any additional data
}
If the payment goes through, a good practice is to return HTTP error code 201 and the Location HTTP Header containing the URL to the payment GET method. If any data in the body is wrong, return a error code 400. If a payment had already been made by the user, conflict code 409 can work.
For SPA you will definitely need REST Web Sevice. My suggestion is to try servicestack instead WebApi
Related
I've searched for this answer in many places, but I just can't seem to understand the purpose of these services.
What exactly are web APIs meant to do? I've used Spring Boot quite extensively over the past few months, though without touching its REST services portion. I was recommended to check out ASP, and specifically use its web-API items, but I have to say I'm just baffled.
How exactly is the returning of just plain data useful? In Spring, I've used models and views, which are great and useful for directing users around. But that doesn't seem to be the goal of REST APIs. So is the main idea to separate the API from the server? But why do that, when I can just as easily separate the model from the controller anyways, following the MVC pattern? As far as I can tell, there's no real way to return a view with the JSON (or whatever format the data is), so that would necessitate another server, just to deal with providing the views, no?
I'm assuming it's faulty, per-existing information that I have that's getting me stuck up here, but I just don't understand what's the point of a service that only spits out data, yet is far more removed than the model in MVC.
What exactly are web APIs meant to do?
The best summary that I know of comes from Roy Fielding
REST is intended for long-lived network-based applications that span multiple organizations.
The reference application for the REST architectural style is the World Wide Web.
The point being that, if your API is "of the web", then you get to take full advantage of the work that has already been done for you: browsers, caches, servers, well understood media-types, code-on-demand, and so on.
is the main idea to separate the API from the server?
Really, the main idea is to separate the implementation from the messaging. As far as the outside world is concerned, your service is just a web site.
Web Services are used to fetch the data from some other application, only data is fetched and view is prepared by consuming application.
Example if you pass the customer number to web service then only data is received and its your responsibly to display the data in proper asp/jsp or any other view technology
Resource in my REST API context is application code written in some programming language. CRUD operations that can be easily mapped to HTTP verbs are save/edit/delete code. Non-CRUD operations that are difficult to map to HTTP methods are deploy the code on server, execute the code, and undeploy.
Common suggestions I came across in SO are:
Restructure the action to appear like a field of a resource, e.g. if your action is to activate an engine, design URI: PATCH engines/123, body: {"status":"active"}
Treat the action like a sub-resource, e.g. PUT engines/123/active without a body
Use query parameters, e.g. PUT engines/123?activate=true
Be pragmatic and go for a non-RESTful, RPC-style URL, e.g. PUT engines/activate?id=123
I am definitely not able to fit deploy/undeploy/execute code actions to a resource as suggested in #1 and #2. Could you please share your opinion how best we can design the APIs for these actions?
Could you please share your opinion how best we can design the APIs for these actions?
Create/Update/Delete information resources, and as a side effect of that, do work behind the API.
So think documents.
One very good example: In RESTful Casuistry, Tim Bray asked about an api to shut down a machine. Seth Ladd's response, in particular, is important to read
Fundamentally, REST is a bureaucracy that solves problems with paperwork. If you want to get anything done, you submit the right form; which becomes an information resource describing what you want done.
PUT /deploymentRequests/abcde
Please find the artifacts from build 12345 and deploy that artifact
to machine 67890
201 Created
The request is just a document, in exactly the same way a sticky note on your desk asking you to address some task is a document.
As far as REST is concerned, the spelling of the URI absolutely does not matter; but from the point of view of a human readable naming convention, start from the fact that the resource is the document -- not the side effect that you want the document to have.
So, for example, it's totally normal and compliant with REST that the document that describes the current state of a thing and the document that describes changes you want to make to a thing are different documents with different identifiers.
I think you are looking for controllers, according to REST API design RuleBook:
A controller resource models a procedural concept.
Controller resources are like executable functions, with parameters and return values; inputs and outputs.
Like a traditional web application’s use of HTML forms, a REST API relies on controller resources to perform application-specific actions that cannot be logically mapped to one of the standard methods (create, retrieve, update, and delete, also known as CRUD).
Controller names typically appear as the last segment in a URI path, with no child resources to follow them in the hierarchy.
The example below shows a controller resource that allows a client to resend an alert to a user:
POST /alerts/245743/resend
and also:
POST should be used to create a new resource within a collection and execute controllers.
CRUD operations that can be easily mapped to HTTP verbs are
save/edit/delete code. Non-CRUD operations that are difficult to map
to HTTP methods are deploy the code on server, execute the code, and
undeploy.
I think you misunderstood the whole concept. You map operations to the HTTP method and URI, not just to the HTTP method. In the case of CRUD this is evident. In the case of "non-CRUD", you need to add a new resource with a different URI instead of trying to add a new HTTP method to the list.
PATCH is for updating a resource just like PUT, but in the case of PATCH you send update instructions instead of a representation. Sure it can be used or POST can be used too. Using PUT is not a good idea if you don't send a representation of the new resource state in the body.
So any of these can be good:
PATCH engines/123 "activate"
PUT engines/123/state "active"
POST engines/123/activation null
You can do the same with "deploy/undeploy/execute":
PATCH engines/123 "deploy"
PUT engines/123/state "before-deploy"
POST engines/123/execution null
This is just a recommendation though. You can choose the verb based on the HTTP standard and I think it is better to avoid using verbs in the URI, I use just nouns, because it makes sense this way. The URI is not that important though, it is like nice URIs on web pages, it looks good, but nobody really cares unless they have to write it down. Just to make it clear, this is still not REST unless you send these hyperlinks in your responses.
{
id: "engines/123",
type: "docs/engine",
operations: [
{
operation: "docs/engine/activation",
id: "engines/123",
method: "PATCH",
body: "activate"
}
]
}
Using RDF and ontologies takes this a lot further.
Looking for answers on what exactly REST is, I came across a post on SOA on stack overflow:
"magine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.
You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services"
As far as I understand, this is saying that SOA is an umbrella term for designing software in such a way that functionality and presentation are separated (is that not MVC?). And that REST is a means of doing that.
What is the functionality, and what is the presentation is this case?
I understand REST as an architecture for designing server side code that creates URI links as included in the HTML on a browser, and that processes stateless server requests. Is this correct? and if so, what is the alternative to this?
What exactly would a server request that isn't stateless be?
Here is the original question:
JSON, REST, SOAP, WSDL, and SOA: How do they all link together
I don't know if my question makes sense, I'm quite confused.
As far as I understand, this is saying that SOA is an umbrella term for designing software in such a way that functionality and presentation are separated
Yes, that is the goal. But SOA implies a particular approach to that goal where the different parts of a system are actually separate programs, communicating over some API. Each of those parts might be in different programming languages, or on physically separate hosts.
(is that not MVC?)
MVC is a way of structuring a single program by breaking up its code into reusable units. But a Model object is only useful if it can be passed around the application, you couldn't run it as a separate program. You could, however, write an MVC program that was one of the components in an SOA system - e.g. consuming an API in a particular way and turning its results into model objects, then passing them to an HTML view.
I understand REST as an architecture for designing server side code that creates URI links as included in the HTML on a browser, and that processes stateless server requests. Is this correct? and if so, what is the alternative to this?
Not quite. REST has nothing to do with HTML, only HTTP: rather than using a wrapper like an XML document which says "I would like you to do action X, here is the input Y" (which is roughly what SOAP does), REST uses the URL and the type of HTTP request (GET, POST, PUT, DELETE) to describe what's needed. It comes with a philosophy that the object of an action (e.g. /user/42) is more central than the specific verb (e.g. ResetPassword)
What exactly would a server request that isn't stateless be?
HTTP itself is a stateless protocol, but that doesn't mean you can't build stateful applications on top of it. For instance, by using cookies, this website is maintaining the state that I'm logged in to credit me for this answer. In many APIs, some form of session identifier is passed with each request so that you can, for instance, build up a basket of items prior to booking. This can simplify the use of the API, but restrict the order in which operations can happen. A RESTful approach might instead let you create any number of baskets and retrieve them at any time, leaving an action such as searching for a product to be truly stateless.
I am looking at backbone for a project. I have many legacy services which are non-restful that I have no choice but to use them as is. I see that I have to override Backbone.Model.sync, parse and many other methods and handle the ajax service calls. I am not sure how the routing is going to work but I can see that there will be a lot of extra code to make that work. My question is: Is Backbone really recommended if I have to work with non-restful services? I don't find any examples or discussion anywhere online which talks about it.
Backbone's automatic understanding of REST conventions boils down to probably about 50 lines of code. If your back-end APIs are all odd and unique, yes, you'll need to write code to talk to them, but you'll need that no matter which framework you use because no framework is going to understand the unique weirdnesses of your back end services. If you feel good about the basic MVC with event bindings design of backbone, stick with it. That's the core of it. And it's a tiny core, that's why it's called backbone.
As per routing, that's really handled in the browser as a single page app and the browser URL routing and associated backbone router/view code is entirely separate from the API patterns and URLs that provide the back end services. The two can be utterly unrelated and that's fine. You'll still be able to define your own browser routing however you see fit.
Alright, so a better title here may have been "Progressive Enhancement with REST in CakePHP", but at least now I'll know you didn't read the question if your answer just refers to the difference between the two ;)
I'm pretty familiar with REST and how to integrate it with CakePHP, but I'm not 100% on board with how to still maintain a conventionally functioning website. Using Router::mapResources sounds like a great idea, but this creates a problem with maintaining the "gracefully degradation" version of the site, because both POST requests to /resource/ AND GET requests for /resource/add will route to the same action (add). Clearly I'll want this action to return a JSON object if they're using the REST api, but if they're using the degraded version of the site (no JS perhaps), it should be a add form, right?
What's the best way to deal with this. Do you route your REST requests to other action names using Router::resourceMap()? Do you do that crazy hack I saw to have the /api/ prefix part of the resourceMap so you can use api_action functions? Do you have the actions handle both REST and conventional requests via checking isAjax()? If so, how do you ensure that you can rely on the browser to properly support the other two request types?
I've searched around quite a bit but haven't found anything about how to keep conventional requests available in Cake along side REST, so if anyone has any advice or experience, I'd love to hear it!
CakePHP uses extension routing as well, via Router::parseExtension() so;
/test/action will render views/test/action.ctp
/test/action.html also
/test/action.json will render views/test/json/action.ctp
/test/action.xml will render views/test/xml/action.ctp
If all views are designed to handle the same data as set by your controller, you'll be able to show a regular HTML form and handle the posted data the same way as you'd handle the AJAX request.
You'll probably might have to add checks if any data is posted/submitted inside the /add, /edit, /delete actions to prevent items being deleted without a form being posted (haven't tested that though, it might be that cake blocks these urls if mapresources is set for the controller)
REST in CakePHP:
http://book.cakephp.org/2.0/en/development/rest.html
(Extension) Routing
http://book.cakephp.org/2.0/en/development/routing.html#file-extensions