I come across this question many times that Rest by principle does not impose any restriction on the http verbs used on the methods .i.e I can still use a http post (#Post) to fetch a resource.
What would be the side effect on such an implementation?
It will have semantic impact basically, to read a resource GET should be used and to Create/Update PUT/POST should be used.
GET doesn't effect the resource on server means not creating updating its just a read, whereas POST/PUT effect the resource on server it is created or updated.
First of all, you are mentioning "class methods". When talking about RESTful APIs, the methods in your classes are an implementation detail that should have nothing to do with the RESTful API you are designing. You could choose a design where methods at a class level closely relate to actions your RESTful API provides, but you don't have to. The important part here is that both are conceptually on different layers.
Second, you should absolutely not design your RESTful API in a way that enables clients to fetch resources via the HTTP POST method. While there's technically nothing that prevents you from doing so, it directly contradicts the spirit of what RESTful APIs are all about.
Related
I was thinking of how to make a RESTFul API more intention revealing. A common patter I see around various blogs on this is that conventional REST API results in
Ban a Player -> POST /players.
But I were to change to a more intention revealing interface , I could use
Ban a Player -> POST /players/{ playerid }/banPlayer
The second one I feel is more intention revealing.
The common objection I get from the team is that the second one does not comply with start REST style.
Also currently I cannot move away from a RESTful API.
I would like to hear your thoughts on this.
With Restful API design there are two schools of thought around how to apply actions to a resource.
You describe the action to be taken against the resource in the Uri:
Request Uri:
POST /players/{id}/ban
Note: Just use ban - we already know the resource is a player, its in the base Uri.
You can have the action in the body of the request:
Request Uri:
POST /players/{id}
Request Body:
{ 'action': 'ban' }
You can pick either way - whichever you prefer, there is lots of discussion on both but ultimately both are correct.
Note:
My assumption here that banning a player is more than just updating a part of it, but rather a system action (or state transition) relating to the player. Otherwise if it was just an update to the player resource you should handle with a PATCH or PUT as appropriate.
Some discussions for reference:
http://restful-api-design.readthedocs.io/en/latest/methods.html
https://github.com/interagent/http-api-design/issues/58
https://nordicapis.com/designing-a-true-rest-state-machine/
https://softwareengineering.stackexchange.com/questions/141410/restful-state-changing-actions
With plenty more if you do some Googling...
Long story short: it shouldn't be mandatory to be intention revealing but if you want to add some DDD on how this API looks like then it is nothing that prevents you from doing that
According to HATEOAS constraint of a RESTful web API (this constraint is an essential part of the "uniform interface" feature of REST, as defined in Roy Fielding's doctoral dissertation), the software clients of your API should not care about the URLs. Every possible&permitted action should be included in the response, with the corresponding link relation and URI. In this way you have to hardcode only the link relations.
This constraint does not however prevent you from making the API more intention revealing for the Human clients that try to understand the overall architecture. I recommend you to choose this path, as Human users are at least as important as the software that they write.
Roy Fielding wrote about this on his blog post.
Since you asked for the RESTful way not the best way, here's my thoughts.
Your RESTful URI options include:
/players
/players/{ playerid }/banPlayer
/player-banning
/entities?action=ban_player&method=PUT
/banana
anything else, REST doesn't dictate what your URIs should look like
The RESTful way is to expose knowledge of the next available states purely through hypertext. To do REST, you must use Hypertext As The Engine Of Application State (HATEOAS). Relying on client knowledge of the URI is depending on out-of-band knowledge, which is antithetical to REST.
Your resources do not need to map directly to your business objects. If you choose, you can represent user intent itself as a resource, e.g. a banned player event resource. You can POST to it with some info on which player to ban, and subsequent GETs will provide information on the event.
Oh and just because REST doesn't care what your URIs are, doesn't mean you shouldn't. You'll just have to use a different standard to decide what's best.
According to the REST API approaches, you need to use your entities in URI, so, as banPlayer is not an entity, you cannot use it.
I suggest to UPDATE your record with PUT method.
Here you can read more about rules. Actually, the first section about URIs is just about your case.
The common objection I get from the team is that the second one does not comply with start REST style.
The easy answer is this: consistency in the API has value, whether REST or not. So "that's not how we do it here" is going to trump "but REST says".
The spelling of URI in an API is a lot like the spelling of method names in your code. There are a lot of different arguments for different styles, but "local convention" is a strong argument by itself.
That said -- REST does not care what spelling you use for your identifiers.
This is what Fielding had to say in 2008
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. Any effort spent describing what methods to use on what URIs of interest should be entirely defined within the scope of the processing rules for a media type (and, in most cases, already defined by existing media types). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]
In band would be including the URI in the representation of the resource -- putting it into the description of a form in the HTML document. Out of band is documenting the URI, and expecting people to do the right thing with it.
Note: there's nothing wrong with human-readable URI, or documenting the URI that should be used. But notice that you can post questions to stackoverflow even though the people who wrote your browser didn't read stack overflow's API documentation -- that's REST.
This Google Cloud article API design: Understanding gRPC, OpenAPI and REST and when to use them clarifies the REST vs RPC debate. REST is more relevant for entity-centric API whereas RPC is more relevant for action-centric API (and CQRS). The most mature REST level 3 with hypermedia controls works well only for entities with simple state models.
Understand and evaluate first the benefits of REST for your case. Many APIs are REST-ish and not RESTful. OpenAPI is actually RPC mapped over and HTTP endpoints but it doesn't prevent it to be widely adopted.
I'm not sure I understand correctly the notion of RESTful API. If I understand correctly, such an API should provide functions you can trigger with GET, POST, PUT & DELETE requests. My question is: if an API only provides POST requests functions, is it still RESTful?
You should probably watch this lecture and read this article.
REST a such has nothing to do with how much of available HTTP methods you use. So, the quick answer is: yes, it could be considered "restful" (whatever that actually means).
Buuut ... it most likely - isn't. And it has nothing to do with the abuse of POST calls.
The main indicator for this magical "RESTfulness" has nothing really to do with how you make the HTTP request (methods and pretty URLs are pointless worthless as a determining factor).
What matters is the returned data and whether, by looking at this data, you can learn about other resources and actions, that are related the resource in any given endpoint. It's basically about the discover-ability.
REST is a misused term for some time and the community especially at Stackoverflow doesn't even care about its actual intention, the decoupling of clients from server APIs in a distributed system.
Client and server achieve the decoupling by following certain recommendations like avoiding stateful connections where client state is stored at and managed by the server, using unique identifiers for resources (URIs) and further nice-to-have features like cacheability to reduce the workload both server and clients have to perform. While Fieldings dissertation lists 6 constraints, he later on explained some further rules applications following the REST architectural style have to follow and the benefits the system gains by following these. Among these are:
The API should not depend on any single communication protocol and adhere to and not violate the underlying protocol used. Altough REST is used via HTTP most of the time, it is not restricted to this protocol.
Strong focus on resources and their presentation via media-types.
Clients should not have initial knowledge or assumptions on the available resources or their returned state ("typed" resource) in an API but learn them on the fly via issued requests and analyzed responses. This gives the server the opportunity to move arround or rename resources easily without breaking a client implementation.
So, basically, if you limit yourself only to HTTP you somehow already violate the general idea REST tries to impose.
As #tereško mentioned the Richardson maturity model I want to clarify that this model is rather nonsense in the scope of REST. Even if level 3 is reached it does not mean that this architecture follows REST. And any application that hasn't reached level 3 isn't following this architectural style anyways. Note that an application that only partially follows REST isn't actually following it. It's like either properly or not at all.
In regards to RESTful (the dissertation doesn't contain this term) usually one regards a JSON based API exposed via HTTP as such.
To your actual question:
Based on this quote
... such an API should provide functions you can trigger with GET, POST, PUT & DELETE requests
in terms of REST architectural style I'd say NO as you basically use such an API for RPC calls (a relaxed probably JSON based SOAP if you will), limit yourself to HTTP only and do not use the semantics of the underlying HTTP protocol fully; if you follow the JSON based HTTP API crowd the answer is probably it depends on who you ask as there is no precise definition of the term "RESTful" IMO. I'd say no here as well if you trigger functions rather than resources on the server.
Yes. Restful has some guidelines you should follow. As long as you use HTTP verbs correctly and good practices with regards to URLs naming having only POSTs would be OK. If, on the other hand, a POST request in your application can also delete a record, then I would not call it Restful.
I want to know the main difference between REST and API. Sometimes I see REST API in programming documents, then is REST or API same as REST API? I would like to know more about relation between REST, API and REST API.
REST is a type of API. Not all APIs are REST, but all REST services are APIs.
API is a very broad term. Generally it's how one piece of code talks to another. In web development API often refers to the way in which we retrieve information from an online service. The API documentation will give you a list of URLs, query parameters and other information on how to make a request from the API, and inform you what sort of response will be given for each query.
REST is a set of rules/standards/guidelines for how to build a web API. Since there are many ways to do so, having an agreed upon system of structuring an API saves time in making decisions when building one, and saves time in understanding how to use one.
Other popular API paradigms include SOAP and GraphQL.
Note that the above attempts to answer the question in regards to how the terms are commonly used in web development. Roman Vottner has offered a different answer below which offers good insights into the original definition of the term REST with more technical precision than I have provided here.
REST mostly just refers to using the HTTP protocol the way it was intended. Use the GET HTTP method on a URL to retrieve information, possibly in different formats based on HTTP Accept headers. Use the POST HTTP method to create new items on the server, PUT to edit existing items, DELETE to delete them. Make the API idempotent, i.e. repeating the same query with the same information should yield the same result. Structure your URLs in a hierarchical manner etc.
REST just is a guiding principle how to use URLs and the HTTP protocol to structure an API. It says nothing about return formats, which may just as well be JSON.
That is opposed to, for example, APIs that send binary or XML messages to a designated port, not using differences in HTTP methods or URLs at all.
There is no comparison in REST and API, REST is an API type.
API, in general, is a set of protocols deployed over an application software to communicate with other software components (Like browser interacting with servers) and provide an interface to services which the application software
offers to several live consumers.
And Rest is a form of principle which an API follows in which the server provides information whatever the client desires to interact with services.
REST basically is a style of web architecture that governs the behavior of clients and servers. While API is a more general set of protocols and is deployed over the software to help it interact with some other software.
REST is only geared towards web applications. And mostly deals with HTTP requests and responses. This makes it practically usable by any programming language and easy to test.
API is an acronym for Application Programming Interface and defines a set of structures (i.e. classes) one has to implement in order to interact with a service the API was exposed for. APIs usually expose operations that can be invoked including any required or supported arguments as well as the expected responses. Classical examples here are Corba IDL, SOAP or RMI in the Java ecosystem but also RPC-like usages of Web systems specified in documentation like Swagger or OpenAPI.
REST (REpresentational State Transfer) on the contrary was specified by Fielding in his doctoral thesis where he analyzed how the whole user interactions occurs on the Web. He realized that on the Web only a transport protocol, a naming scheme for stuff as well as a well defined exchanged format is needed to exchange messages or documents. These three parts therefore define the interface to interact with peers in such a ecosystem. The transport layer is covered by HTTP while the naming scheme is defined by URI/IRI. Contrary to traditional RPC protocols which usually only support one syntax, REST is actually independent from a particular syntax. To upkeep interoperability both client and server though need do negotiate about it, which HTTP itself supports through the Accept request and Content-Type response headers. As long as client and server support HTTP, URI/IRI and a set of negotiated representation formats, defined by backing hypermedia capable media-types, they will be able to interact with each other. In a more narrow sense REST therefore has no API other than HTTP, URI/IRI and the respective media types.
However, things are unfortunately not that easy. Most people unfortunately understand something very different in terms of REST or REST API. While URIs should not convey any semantics itself, after all they are just pointers to a resource, plenty of programmers attribute more importance to URIs than they should. Some clients i.e. will attempt to extract some knowledge off of URIs or consider URIs to return responses that represent a certain type. I.e. it may seem natural to consider an URI such as https://api.acme.org/users/1 to return a representation that describes a particular user of that particualar system. An external documentation may specify that a JSON structure is returned that follows a given template such as
{
"id": 1,
"firstName": "Roman",
"lastName": "Vottner",
"role": "Admin",
...
}
can be expected, however, such a thing is closer to RPC than it is to REST. Neither is the response self-descriptive, as required by REST, nor does it follow a representation format that follows a well defined media type that defines the syntax and each of the elements that may form a message. Clients therefore are usually tailor-made for exactly one particular system (or REST API if you will) and can't be used to interact with different systems out of the box without further manual integration/updates. External documentation such as OpenAPI or Swagger are used to describe the available endpoints, the payload-templates that a server will be able to process as well as the expected responses, depending on the input. These documentation therefore is the truth and thus defines the API a client can look up or even use to autogenerate stub classes to interact with the server-side, similar to SOAP.
I therefore don't agree with the answer given by dave. While for RPC systems or the common understood term of REST API his definition may be suitable, for actual REST architectures his explanation isn't fitting at all and thus, IMO at least, not correct either. REST isn't a collection of rules, standards and/or guidelines. It is a set of few constraints that just ensure that peers in such an architecture avoid coupling, support future evolution and become more robust to change.
API is basically a set of functions and procedures which allow one application to access the feature of other application
REST is a set of rules or guidelines to build a web API.
It is basically an architectural style for networked applications on the web which is limited to client-server based applications.
Read more at: https://www.freelancinggig.com/blog/2018/11/02/what-is-the-difference-between-api-and-rest-api/
What is the advantage of using the REST verbs GET, POST, PUT, DELETE
instead of just using POST and embedding an XML-RPC operation description
in the POST body describing what we want to insert, update, or delete.
Plus, what if we wanted to do more than one of these operations in one
go, wouldn't the rest design be useless in this case, as REST does not
seem to support transactions or multiple operations in one go.
Thanks.
Below are my thoughts on why i prefer REST services over others.
REST uses the HTTP verbs GET, POST, PUT, DELETE to convey the intention of the service.
A majority of the HTTP framework is used as is.
In my opinion, there is no need to circumvent the HTTP to build a new protocol. Only an understanding of HTTP is required to build and use RESTful services. I think a carefully designed service acting on any resource will fit into the RESTful model.
In a RESTful service, the operation on the resource is intuitive. So, when a GET operation is made on a resource, it is imperative that the operation is idempotent.
REST enables to use lighter payload. It so easy and light to make an ajax call to a RESTful service.
It provides the ability to service different request/response formats like json, xml etc by the same service.
Event though there is no ws transaction type support in REST, a RESTful service can be built to achieve the same consistent state.
There can be cases where REST is not appropriate, that depends on the architecture and the contract required for the solution.
I'm working on a web service and I'm trying to decide whether to make it RESTful or not. I've found lost of information on what REST is, but not a lot on why it's useful.
In particular I'm confused as it seems using RESTful methods makes it very difficult to interact with the service through a client webpage, since you have to use AJAX to submit anything other than the GET/POST queries, and if your service lives on a different server, then it's nigh impossible because of the same origin policy.
Can anyone fill me on on how this is usually done and what benefits REST gives you over something like a simple RPC API?
Modern browsers (HTML5 compliant) support all the appropriate HTTP verbs (GET, PUT, POST, DELETE). For dealing with the same origin policy issue, you can always expose an endpoint on your server to tunnel through to the foreign server.
The benefits gained from REST come (IMO) from the representation of your data model as resources, and not as services. In particular, representation of data model elements can leverage the HTTP caching mechanisms. As well, using a representational model can force a design-time evaluation of your data model that (in my experience) proves to be very useful.
1)
Why REST:
Just think of the MVC pattern.
Model-View separation makes especially sense if you have multiple views of the same content.
Now think of REST as a machine-friendly view via an application specific protocol which is easy to implement. Making your application also useful to other developers who want to integrate your application as a web service into their own apps.
REST is an application integration technology.
REST is a good choice if you want to offer a machine and developer friendly web service API to your application.
2)
REST vs RPC
REST should be per definition implemented in a stateless manner.
RPC calls are remote method calls on objects or session variables, which makes RPC APIs stateful and in many situation more expensive.
3)
Different REST styles
The problem with REST is it's not always easy to map all operations of an object on the common HTTP methods GET, POST, PUT, DELETE, OPTIONS.
Obviously CRUD can be implemented by assigning the 4 CRUD operations on to the GET, POST, PUT, DELETE methods.
But you can also codify in the HTTP body of the POST method the kind of operation, which is the minimalistic GET,POST style of doing REST.
The problem is not all HTTP clients can send a PUT request.
The solution advocated by the CRUD style services is to emulate a PUT request by annotating a POST request with a special HTTP header:
X-HTTP-Method-Override: PUT
But this does not solve it, because some exotic firewalls remove this non-standard HTTP header.
Roy Fielding, who coined the term RESTful API, mentions also that he think it is well possible to design a perfectly RESTful system with just GET and POST.
4)
Adding REST to an existing MVC web application requires at least the implementation of an extra RESTful controller which translates the HTTP method verbs PUT, POST, DELETE into operations on the model object identified by the request URI but often also the implementation of a more machine-friendly view (JSON,XML,...).