Splitting hairs with REST: Does a standard JSON REST API violate HATEOAS? - rest

I was doing some reading on REST this morning and I came across the HATEOAS principle ("hypermedia as the engine of application state").
Quoting the REST Wikipedia page:
Clients make state transitions only through actions that are dynamically identified within hypermedia by the server (e.g. by hyperlinks within hypertext). Except for simple fixed entry points to the application, a client does not assume that any particular actions will be available for any particular resources beyond those described in representations previously received from the server.
And Roy Fielding's blog:
...if the engine of application state (and hence the API) is not being driven by hypertext, then it cannot be RESTful and cannot be a REST API. Period.
I read this as: The client may only request state changes based on the actions made available from the body of the response from the server (the hypertext).
In an HTML world, this makes perfect sense. The client should only be able to request state changes (new actions/pages) based on the links made available to them through the hypertext (HTML).
When the resource is represented in other ways - such as JSON, XML, YAML etc. This is not so apparent.
Let's take an example "REST" JSON API:
I create a new resource (a new comment for example) by sending a POST request to
/comments.json? # with params...
The server responds with:
# Headers
HTTP/1.1 201 Created
Location: http://example.com/comments/3
Content-Type: application/json; charset=utf-8
... Etc.
# Body
{"id":3,"name":"Bodacious","body":"An awesome comment","post_id":"1"}
I know that I can now access this comment at the URI returned in the header: http://example.com/comments/3.json
When I visit http://example.com/comments/3.json I see:
{"id":3,"name":"Bodacious","body":"An awesome comment","post_id":"1"}
Suppose the API's documentation tells me that I can delete this comment by sending a DELETE request to the same URI. This is fairly common amongst "REST" APIs.
However:
The response from the server at GET http://example.com/comments/3.json doesn't tell me anything about being able to delete the comment by sending a DELETE request. All it shows me is the resource.
That I can also DELETE a comment with the same URL is something the client knows through out-of-band information (the documentation) and is not discovered and driven by the response from the server.
Here, the client is assuming that the DELETE action (and possible others) are available for this resource and this information has not been previously received from the server.
Have I misunderstood HATEOAS or am I right in saying than an API matching the above description would not, in the strict sense, be a REST API?
I'm aware 100% adherence to REST is not always possible or the most pragmatic way to go. I've posted this question purely to satisfy my own curiosity about the theory behind REST, not for advice on real world best-practice.

Jon Moore gave an excellent talk in Nov 2010 about the nuts and bolts of writing a truly RESTful (i.e. HATEOAS supporting) API and client. In the first part, he suggests the JSON is not a proper media type for REST because it lacks a commonly understood way of representing links and supported HTTP methods. He argues that good ol' XHTML is actually perfect for this since tools for parsing it (i.e. XPath) are readily available, it supports forms (think GET link templating and PUT, POST, and DELETE methods) and has a well-understood way of identifying hyperlinks, plus some other advantages mainly achieved through the ability to use the API with any standard web browser (eases the jobs for devs, QA, and support staff.)
The argument I'd always made prior to watching his talk is that JSON is so much lower of bandwidth consumer than any *ML language e.g. XML, HTML, XHTML. But by using terse XHTML where possible such as relative links instead of absolute ones (hinted at but not so evident in the example he uses throughout his talk), and by using gzip compression, this argument loses a lot of weight.
I realize efforts such as JSON-Schema and other RFC's are underway to try standardizing things in JSON, but in the meantime, Moore's talk convinced me to give XHTML a try.

JSON as a hypermedia type doesn't define an identifier for application flow. HTML has link and form tag that that guide a user through a process.
If your application is only concerned with PUT, POST, DELETE, GET on a resource, your documentation could easily explain that.
However, if it were more complicated like adding a rebuttal to a comment and that rebuttal was a different resource then the comment you would need hypermedia type that would guide the consumer create the rebuttal.
You could use HTML/XHTML, Create your own 'bodacious+json' or use something else. Here are all the different media types
http://www.iana.org/assignments/media-types/index.html
I'm using HAL and it has a pretty active group. Here are links to it.
http://www.iana.org/assignments/media-types/application/vnd.hal+json
http://stateless.co/hal_specification.html
The book "Building Hypermedia APIs with HTML5 and Node" goes deep into hypermedia and media types. It shows how to create a media type for a specific or general purpose in XML or JSON.

A RESTful solution would be to utilise the Allow-header to inform the client of the available methods/actions:
> GET /posts/1/comments/1 HTTP/1.1
> Content-Type: application/json
>
< HTTP/1.1 200 OK
< Allow: HEAD, GET, DELETE
< Content-Type: application/json
<
< {
< "name": "Bodacious",
< "body": "An awesome comment",
< "id": "1",
< "uri": "/posts/1/comments/1"
< }
Fielding's dissertation sets out two types of metadata: representation metadata; and resource metadata.
The Allow-header in HTTP/1.1 functions as resource metadata because it describes some property of a resource; i.e. the methods it allows.
By fully utilising the features provided by HTTP you eliminate the need for any out-of-bound information, and become more RESTful.
HATEOAS in a simple HTTP context describes how a client can navigate from one representation to another by following URIs using GET, whilst the Allow-header informs the client of the additional methods supported by the resource that generated the representation.
It's a neat design; the client asked for a representation, and additionally received a whole bunch of extra metadata about the resource that enables the efficient requesting of further representations.
I think the quote you have from the Wikipedia REST page is somewhat misleading in its choice of words and hasn't helped here (N.B. It has been improved since this question was asked).
All HTTP clients have to assume that a GET-method is likely to be available for the majority of resources. They do this because support for GET and HEAD are the minimum requirements for an HTTP/1.1 server. Without this assumption the web would not function. If a client can assume GET is available, then why not make other assumptions about common methods such as DELETE, or POST?
REST and HTTP aim to leverage the power of making assumptions about a basic set of methods in order to reduce the overall volume of requests on a network; if a request succeeds there's no need for further communication; but if a request fails with status '405 Method Not Allowed', then the client is immediately in receipt of the requests that could succeed via the Allow-header:
> ANNIHILATE /posts/1/comments/1 HTTP/1.1
> Content-Type: application/json
>
< HTTP/1.1 405 Method Not Allowed
< Allow: HEAD, GET, DELETE
< Content-Type: application/json
<
If the basic set of HTTP/1.1 methods aren't enough then you are free to define your own. However, it would be RESTful to solve problems using the available features of HTTP before defining new methods or putting metadata into the message-body.

A fully discoverable JSON API that doesn't require any out-of-band knowledge as you put it so succinctly:
"That I can also DELETE a comment with the same URL is something the client knows through out-of-band information (the documentation) and is not discovered and driven by the response from the server."
...is completely possible. It just requires a simple standard and a client that understands the standard. Check out hm-json and the hm-json Browser project:
https://bitbucket.org/ratfactor/hm-json-browser/
As you can see in the demo, absolutely no out-of-band documentation is needed - only one entry point URI from which all other resources and their HTTP methods can be discovered by browsing.
By the way, HAL as mentioned in suing's answer is very, very close to your hypothetical requirements for HATEOAS. It's a great standard and it has a lot of cool ideas like embedded resources, but it has no way of informing the client about all available HTTP methods such as DELETE for a given resource.

Another solid (and new as of May 2013) attempt at resolving HATEOAS for JSON can be found here:
JSON API: http://jsonapi.org/

The premise of your question contains an often misunderstood aspect of REST – that the API response body entity be responsible for not only communicating the representational state of the requested resource but for also communicating the over-all state of the application the resource belongs to. These two things - resource state and application state are not the same thing.
The response entity body by definition provides you the state of the resource at a point in time. But a single resource is only one of many that comprises an application. Application state is the combined states of all in scope related resources – at any point in time – from the perspective of the application consumer - human or machine. To deliver this 'application state' a level 3 REST API make possible HATEOAS.
Since Hypertext is what most people mean when referring to the 'Hyper'media in HATEOAS, the special power of hypertext is it's ability to link to other media. Further, since most experience hypertext via HTTP/HTML this tends to lead many to think hyperlinks are only possible via an anchor tag or link tag within the body of a response entity - but this is not so.
If the transport protocol is HTTP then application state can and should be communicated via headers. Specifically, one or more 'Link' HEADERS with a 'rel' attribute to provide semantics. The Link HEADER along with the ALLOW header are the HTTP mechanisms for communicating what the next possible state transitions are and how to go about accessing them.
If you decide to not use these built-in mechanisms than your options are to try and communicate the application state by 'piggy-backing' on your resource state communication channel i.e. the response body, which leads to trying to devise some form of additional specification into the design of the resource itself.
When this is done - 'piggy-backing'- many run into content-type issues because the response body has to be specified by a MIME/Content-type like XML or JSON which means figuring out how to implement the HATEOAS mechanisms via some custom content-type specific format like custom XML tags or key:value pairs of nested object. You can do this, many do - e.g. see json-api suggestion above, but again HTTP already provides mechanisms for this.
I think it goes to us as humans always thinking we have to see or be able to click on these links as in the normal web use-case but we are talking about APIs that I can only assume are being built not for human consumption but for machine consumption - right? The fact that headers - which are there by the way as part of the response - are not visible in most human interfaces to HTTP i.e. browsers is not an issue with REST but rather an implementation limitation of the HTTP Agents on the market.
Hope this helps. BTW if you want a good human browser for APIs google 'Paw API Browser'

Related

REST API URL structure when resource not in URL

We are creating a two REST APIs
To do a template processing
To convert the HTML to PDF.
The template in 1, and the HTML in 2 can be provided along with the request body as well as present in a persistent location.
What is the best way to design the REST contract? Are these good ways to design it? Or are there better suggestions for this?
For Scenario 1
PUT - /template/process; include the Template markup in the body
PUT - /templates/{id}/process; there is a template with that {id} in a persistent location
For Scenario 2
PUT /html2pdf/convert with the HTML markup mentioned in the body
PUT html2pdf/{id}/convert with the resource HTML with the {id} available in a persistent location.
Is it a good idea to have the action too (process, convert in this case) in the URL? Or is it possible to give a meaning to it using the HTTP verb itself?
The use of PUT is suspicious. Remember, part of the point of REST is that we have a uniform interface - everybody understands HTTP messages the same way.
In particular, PUT is the method token that we use if we are uploading a web page to a server. The semantics of the request are analogous to "save" or "upsert" - you are telling the server that you want to make the server's copy of the target resource look like your copy of the target resource.
POST serves many useful purposes in HTTP, including the general purpose of “this action isn’t worth standardizing.” -- Fielding, 2009
What we want in a lot of cases similar to yours is an effectively read only request with a payload. As of early 2021, the registry of HTTP methods doesn't have a good match for that case - the closest options are SEARCH and REPORT, but both of those carry WebDAV baggage.
But in late 2020, the HTTP WG adopted the draft-snell-search-method spec:
the scope of work is to define a method that has the behavior of a GET with a body -- Tommy Pauly
So when that work is done, we'll have another standard method to consider for this type of problem.
Is it a good idea to have the action too in the URL?
It's a neutral idea.
URL/URI are identifiers; they are (from the point of view of the protocol) semantically opaque. So long as your spelling conventions are consistent with the production rules defined in RFC 3986, you can do as you like.
Any HTTP compliant component should understand that the semantics of the message are defined my the method token, not by the target-uri.
Resources are generalization of documents. The URI is, effectively, the "name" of the document. You can use any name for your documents that makes sense to your human beings (operators looking at access logs, tech writers trying to document your app, other developers trying to read those documents, etc).

Does RESTFul mean URL shouldn't contain parameters

I've heard about the conception RESTFul for a long time but I always can't understand it clearly.
I've read the links below:
What are RESTful web services?
What exactly is RESTful programming?
As my understanding, RESTFul means that the URL shouldn't contain any verb, meaning that an URL represents an unique resource. And also, the method GET shouldn't modify any resource and we should use POST to do so.
But I still have a question.
For example, if we want to search a user by his name, we can design the URL like this:
www.example.com/user?name=test
Or like this:
www.example.com/user/name/test
Can you tell me which one is RESTFul?
When you are using rest - you are accessing resources through URI's and you can set actions on these resources through the HTTP request types.
There are different parameters that you can pass through REST request , there can be resource identifiers (That are usually passed through the URI - in your case the www.example.com/user/name/test is more restfull) or things like filters when you want to search, for example www.example.com/user/?age=....
In this post you can find more about best practices in passing parameters in rest:
REST API Best practices: Where to put parameters?
REST, to start with, is not a protocol but just an architectural style that when followed correctly decouples clients from server APIs and thus make them tolerant to changes done on the serverside. It should therefore be regarded as a design approach for distributed systems.
The difference between a protocol and an architectural style is simply that the former one defines a rule set a server or client has to follow. It should be defined as precise as possible to reduce ambiguity and thus reduce the likelihood of incompatible implementations by different vendors. The latter one just contains suggestions how to design the overall application and/or message flow and outlining the benefits one gains by adhering to the design.
By that definition, REST is a generalization of the interaction style used for browsing Web content. A Web browser is able to make use of multiple protocols such as HTTP, FTP, SMTP, IMAP, ... and different flavors of it while remaining independant of any server specific implementation though being capable of interacting with it as the communication is done according to the rules of the protocol used. REST does follow this approach by building up on the same protocols (most often just HTTP) which an application implementing the RESTful architeturce approach should adhere to as well to stay compatible with other users of that protocol.
Similar to a Web browser, which does not care whether the URI string contains any semantical structure, REST doesn't care how the URI is designed or if the resource is named after a verb either. Both will use the URI just to invoke a resource on the server providing the resource. A RESTful client should thus not expect a certain URI to return a certain type (= typed resources). Though how will a client know what an invoked URI will return? The keywords here are content-negotiation and media-types.
The format exchanged by both, Web browser and REST, is negotiated between client and server. While for typical Web browsers the representation is probably one of the HTML variants (i.e. XHTML, HTML 5, ...) it is not limited to it. Your browser is probably capable of processing other media types as well, i.e. pictures, videos, PDF, ... As REST is just a generalization of this idea it also should not limit itself to just XML or JSON.
Media types are thus some kind of guildlines of how to process and interpret data received in a representation format outlined by the media type. It should define the syntax and semantics of a received payload i.e. like text/html, which defines that a received representation will have a case-insensitive <html token (<xhtml in case of XHTML) near the beginning of the content and that fragment identifiers (# character in URIs) are according to URI semantics and that certain tags like A, IMG or others may define a name attribute which act as a target for anchors. It may also define a more thorough description of the syntax and how to interpret it like in case of text/vcard (vCard) (or one of its variants like application/vcard+json (jCard) or application/vcard+xml (xCard)).
As media types are one of the most important parts of the RESTful design, most effort has to be put into its creation. A client that can't deduct the next possible actions from the media type needs some out-of-band information which often is hardcoded into the client and thus couples it tightly to the API itself. If the API will change in future, the chances that the client will stop working once the changes are applied on the server are fairly high (depending on the changes).
I hope I could shed some light on the idea behind REST and that the design of URI is not of relevance to a true RESTful client/API as the client might deduct what to do with that URI based on some relation name returned for the URI and the media-type which might state that a relation name such as order can be invoked to trigger a new order with the API rather than having the client to analyze something like http://some.server.com/api/order/product/1234 or http:/some.server.com/ajfajd/fj/afja.
Further information and reasons why RESTful APIs should follow the design closely can be found in Roy Fielding famous blog post which explains some of the constraints an API should adhere to if it follows the RESTful approach.
REST resource is a noun, no notion of behavior should be in the uri, we use verbs to indicate action we are doing. Basically there are only two types of resources: Instance and Collections. So good practise is to use plurals in the uri: users instead of user:
www.example.com/users GET - fetch collection of all users
www.example.com/users/1 GET - fetch instance of a concrete user
www.example.com/users POST - create of a new user
etc.
REST is not a strict standard (but a list of 6 constraints) says nothing about how search feature should be implemented. But definetely your first option /users?name=test seems preferable for me: tt is straightforward and this is a huge benefit.
As alternative you may want to investigate OData protocol - it is a standard to make queryable apis. OData-like solution would be:
/users?$filter=name eq 'test'
Also Facebook APIs is a good source for inspiration.
Hope this helps

Super simple definition/explanation of "REST" [duplicate]

Looking for clear and concise explanations of this concept.
A RESTful application is an application that exposes its state and functionality as a set of resources that the clients can manipulate and conforms to a certain set of principles:
All resources are uniquely addressable, usually through URIs; other addressing can also be used, though.
All resources can be manipulated through a constrained set of well-known actions, usually CRUD (create, read, update, delete), represented most often through the HTTP's POST, GET, PUT and DELETE; it can be a different set or a subset though - for example, some implementations limit that set to read and modify only (GET and PUT) for example
The data for all resources is transferred through any of a constrained number of well-known representations, usually HTML, XML or JSON;
The communication between the client and the application is performed over a stateless protocol that allows for multiple layered intermediaries that can reroute and cache the requests and response packets transparently for the client and the application.
The Wikipedia article pointed by Tim Scott gives more details about the origin of REST, detailed principles, examples and so on.
The best explanation I found is in this REST tutorial.
REST by way of an example:
POST /user
fname=John&lname=Doe&age=25
The server responds:
200 OK
Location: /user/123
In the future, you can then retrieve the user information:
GET /user/123
The server responds:
200 OK
<fname>John</fname><lname>Doe</lname><age>25</age>
To update:
PUT /user/123
fname=Johnny
Frankly, the answer depends on context. REST and RESTful have meanings depending on what language or framework you're using or what you're trying to accomplish. Since you've tagged your question under "web services" I'll answer in the context of RESTful web services, which is still a broad category.
RESTful web services can mean anything from a strict REST interpretation, where all actions are done in a strict "RESTful" manner, to a protocol that is plain XML, meaning its not SOAP or XMLRPC. In the latter case, this is a misnomer: such a REST protocol is really a "plain old XML" (or "POX") protocol. While REST protocols usually use XML and as such are POX protocols, this doesn't necessarily have to be the case, and the inverse is not true (a just because a protocol uses XML doesn't make it RESTful).
Without further ado, a truly RESTful API consists of actions taken on objects, represented by the HTTP method used and the URL of that object. The actions are about the data and not about what the method does. For example, CRUD actions (create, read, update, and delete) can map to a certain set of URLs and actions. Lets say you are interacting with a photo API.
To create a photo, you'd send data via a POST request to /photos. It would let you know where the photo is via the Location header, e.g. /photos/12345
To view a photo, you'd use GET /photos/12345
To update a photo, you'd send data via a PUT request to /photos/12345.
To delete a photo, you'd use DELETE /photos/12345
To get a list of photos, you'd use GET /photos.
Other actions might be implemented, like the ability to copy photos via a COPY request.
In this way, the HTTP method you're using maps directly to the intent of your call, instead of sending the action you wish to take as part of the API. To contrast, a non-RESTful API might use many more URLs and only use the GET and POST actions. So, in this example, you might see:
To create a photo, send a POST to /photos/create
To view a photo, send a GET to /photos/view/12345
To update a photo, send a POST to /photos/update/12345
To delete a photo, send a GET to /photos/delete/12345
To get a list of photos, send a GET to /photos/list
You'll note how in this case the URLs are different and the methods are chosen only out of technical necessity: to send data, you must use a POST, while all other requests use GET.
Just a few points:
RESTFul doesn't depend on the framework you use. It depends on the architectural style it describes. If you don't follow the constraints, you're not RESTful. The constraints are defined in half a page of Chapter 5 of Roy Fielding's document, I encourage you to go and read it.
The identifier is opaque and does not cary any information beyond the identification of a resource. It's a nmae, not input data, just names. as far as the client is concerned, it has no logic or value beyond knowing how to build querystrings from a form tag. If your client builds its own URIs using a schema you've decided up-front, you're not restful.
The use or not use of all the http verbs is not really the constraint, and it's perfectly acceptable to design an architecture that only supports POST.
Caching, high decoupling, lack of session state and layered architecture are the points few talk about but the most important to the success of a RESTful architecture.
If you don't spend most of your time crafting your document format, you're probably not doing REST.
It means using names to identify both commands and parameters.
Instead of names being mere handles or monikers, the name itself contains information. Specifically, information about what is being requested, parameters for the request, etc..
Names are not "roots" but rather actions plus input data.
I've learned the most from reading the articles published on InfoQ.com:
http://www.infoq.com/rest and the RESTful Web Services book (http://oreilly.com/catalog/9780596529260/).
./alex
Disclaimer: I am associated with InfoQ.com, but this recommendation is based on my own learning experience.

REST API: returning newly create resource id?

In terms of good REST API design, is it a good idea to return id of the newly created resource? Say I have an API:
api/resource POST
I've seen some guru who has such API to return empty json and insert the URI into with Location header in response. I think returning
{ 'id': '1000' }
so that the caller can do something right away with it is better. Save one more round-trip to the server. What's the problem with this approach if any?
As requested I reposted my comment as an answer and added some more details to be worth an answer at all.
The common approach for creating new resources via HTTP POST method is to return a 201 Created status code. The response furthermore should therefore contain the current state of the resource as entity body and a location header pointing to the URI the resource can be found. Not doing so, may break some clients and prevent their correct interaction with the service. Clients here may be browsers, tailor made "languageOfYourChoice" applications or even other services.
In an ideal RESTful world, the client is only aware of one single URI to start with (like the entrance URI of the service, f.e. http://service.company.com/). The response of an invocation of that URI should return a document which can be understood by the client and contains further links the client can use if interested. This concept is similar to the big brother HTML and similar web resources used everyday by humans where links can be used to move from the start page to sub-pages or even external resources or other hyper-media resources. REST is just an abstraction and a generalization of the Web thing.
Although not part of the actual question and this is rather opinion based, there is an ongoing discussion among RESTful devolopers regarding the usefulness of common vs. specialized document types (mime types, ...). I think that there should be a standardized common REST-aware format for JSON, XML, ... Just plain application/json is not enough as this does not define how links and schemas have to be included. Even HAL is not descriptive enough (IMO) regarding executable actions on URIs and what document formats to expect on invoking those URIs and what arguments needed to be passed to the service.
Document formats (a.k.a media types) are one of the core concepts of Roy Fieldings acronym HATEOAS. Clients should not need any prior knowledge other than the entrance point and the media types understood by the clients (thus the previous paragraph). The possible actions are all described through following the HTTP protocol specification and knowing what the respective media types express.
Therefore, returning a URI instead of an ID has a couple of advantages:
URIs are per se unique, different vendors though may have identical IDs
Client needs no knowledge on how the server is creating those URIs, the server on the other hand can provide them almost for free. Returning a product ID of 1234 has almost infintly ways to be combined in an URI by the client - the client therefore needs special knowledge on how to create the URI so that the server is actually able to process the request correctly.
The server can move resources without the need of clients to change as clients (in an ideal RESTful world) would retrieve the URI of the resource within a further request' response. The client therefore needs only the semantical knowledge what the returned field acutally "means"

What is RESTful programming?

What exactly is RESTful programming?
REST is the underlying architectural principle of the web. The amazing thing about the web is the fact that clients (browsers) and servers can interact in complex ways without the client knowing anything beforehand about the server and the resources it hosts. The key constraint is that the server and client must both agree on the media used, which in the case of the web is HTML.
An API that adheres to the principles of REST does not require the client to know anything about the structure of the API. Rather, the server needs to provide whatever information the client needs to interact with the service. An HTML form is an example of this: The server specifies the location of the resource and the required fields. The browser doesn't know in advance where to submit the information, and it doesn't know in advance what information to submit. Both forms of information are entirely supplied by the server. (This principle is called HATEOAS: Hypermedia As The Engine Of Application State.)
So, how does this apply to HTTP, and how can it be implemented in practice? HTTP is oriented around verbs and resources. The two verbs in mainstream usage are GET and POST, which I think everyone will recognize. However, the HTTP standard defines several others such as PUT and DELETE. These verbs are then applied to resources, according to the instructions provided by the server.
For example, Let's imagine that we have a user database that is managed by a web service. Our service uses a custom hypermedia based on JSON, for which we assign the mimetype application/json+userdb (There might also be an application/xml+userdb and application/whatever+userdb - many media types may be supported). The client and the server have both been programmed to understand this format, but they don't know anything about each other. As Roy Fielding points out:
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.
A request for the base resource / might return something like this:
Request
GET /
Accept: application/json+userdb
Response
200 OK
Content-Type: application/json+userdb
{
"version": "1.0",
"links": [
{
"href": "/user",
"rel": "list",
"method": "GET"
},
{
"href": "/user",
"rel": "create",
"method": "POST"
}
]
}
We know from the description of our media that we can find information about related resources from sections called "links". This is called Hypermedia controls. In this case, we can tell from such a section that we can find a user list by making another request for /user:
Request
GET /user
Accept: application/json+userdb
Response
200 OK
Content-Type: application/json+userdb
{
"users": [
{
"id": 1,
"name": "Emil",
"country: "Sweden",
"links": [
{
"href": "/user/1",
"rel": "self",
"method": "GET"
},
{
"href": "/user/1",
"rel": "edit",
"method": "PUT"
},
{
"href": "/user/1",
"rel": "delete",
"method": "DELETE"
}
]
},
{
"id": 2,
"name": "Adam",
"country: "Scotland",
"links": [
{
"href": "/user/2",
"rel": "self",
"method": "GET"
},
{
"href": "/user/2",
"rel": "edit",
"method": "PUT"
},
{
"href": "/user/2",
"rel": "delete",
"method": "DELETE"
}
]
}
],
"links": [
{
"href": "/user",
"rel": "create",
"method": "POST"
}
]
}
We can tell a lot from this response. For instance, we now know we can create a new user by POSTing to /user:
Request
POST /user
Accept: application/json+userdb
Content-Type: application/json+userdb
{
"name": "Karl",
"country": "Austria"
}
Response
201 Created
Content-Type: application/json+userdb
{
"user": {
"id": 3,
"name": "Karl",
"country": "Austria",
"links": [
{
"href": "/user/3",
"rel": "self",
"method": "GET"
},
{
"href": "/user/3",
"rel": "edit",
"method": "PUT"
},
{
"href": "/user/3",
"rel": "delete",
"method": "DELETE"
}
]
},
"links": {
"href": "/user",
"rel": "list",
"method": "GET"
}
}
We also know that we can change existing data:
Request
PUT /user/1
Accept: application/json+userdb
Content-Type: application/json+userdb
{
"name": "Emil",
"country": "Bhutan"
}
Response
200 OK
Content-Type: application/json+userdb
{
"user": {
"id": 1,
"name": "Emil",
"country": "Bhutan",
"links": [
{
"href": "/user/1",
"rel": "self",
"method": "GET"
},
{
"href": "/user/1",
"rel": "edit",
"method": "PUT"
},
{
"href": "/user/1",
"rel": "delete",
"method": "DELETE"
}
]
},
"links": {
"href": "/user",
"rel": "list",
"method": "GET"
}
}
Notice that we are using different HTTP verbs (GET, PUT, POST, DELETE etc.) to manipulate these resources, and that the only knowledge we presume on the client's part is our media definition.
Further reading:
The many much better answers on this very page.
How I explained REST to my wife.
How I explained REST to my wife.
Martin Fowler's
thoughts
PayPal's API has hypermedia controls
(This answer has been the subject of a fair amount of criticism for missing the point. For the most part, that has been a fair critique. What I originally described was more in line with how REST was usually implemented a few years ago when I first wrote this, rather than its true meaning. I've revised the answer to better represent the real meaning.)
An architectural style called REST (Representational State Transfer) advocates that web applications should use HTTP as it was originally envisioned. Lookups should use GET requests. PUT, POST, and DELETE requests should be used for mutation, creation, and deletion respectively.
REST proponents tend to favor URLs, such as
http://myserver.com/catalog/item/1729
but the REST architecture does not require these "pretty URLs". A GET request with a parameter
http://myserver.com/catalog?item=1729
is every bit as RESTful.
Keep in mind that GET requests should never be used for updating information. For example, a GET request for adding an item to a cart
http://myserver.com/addToCart?cart=314159&item=1729
would not be appropriate. GET requests should be idempotent. That is, issuing a request twice should be no different from issuing it once. That's what makes the requests cacheable. An "add to cart" request is not idempotent—issuing it twice adds two copies of the item to the cart. A POST request is clearly appropriate in this context. Thus, even a RESTful web application needs its share of POST requests.
This is taken from the excellent book Core JavaServer faces book by David M. Geary.
RESTful programming is about:
resources being identified by a persistent identifier: URIs are the ubiquitous choice of identifier these days
resources being manipulated using a common set of verbs: HTTP methods are the commonly seen case - the venerable Create, Retrieve, Update, Delete becomes POST, GET, PUT, and DELETE. But REST is not limited to HTTP, it is just the most commonly used transport right now.
the actual representation retrieved for a resource is dependent on the request and not the identifier: use Accept headers to control whether you want XML, HTTP, or even a Java Object representing the resource
maintaining the state in the object and representing the state in the representation
representing the relationships between resources in the representation of the resource: the links between objects are embedded directly in the representation
resource representations describe how the representation can be used and under what circumstances it should be discarded/refetched in a consistent manner: usage of HTTP Cache-Control headers
The last one is probably the most important in terms of consequences and overall effectiveness of REST. Overall, most of the RESTful discussions seem to center on HTTP and its usage from a browser and what not. I understand that R. Fielding coined the term when he described the architecture and decisions that lead to HTTP. His thesis is more about the architecture and cache-ability of resources than it is about HTTP.
If you are really interested in what a RESTful architecture is and why it works, read his thesis a few times and read the whole thing not just Chapter 5! Next look into why DNS works. Read about the hierarchical organization of DNS and how referrals work. Then read and consider how DNS caching works. Finally, read the HTTP specifications (RFC2616 and RFC3040 in particular) and consider how and why the caching works the way that it does. Eventually, it will just click. The final revelation for me was when I saw the similarity between DNS and HTTP. After this, understanding why SOA and Message Passing Interfaces are scalable starts to click.
I think that the most important trick to understanding the architectural importance and performance implications of a RESTful and Shared Nothing architectures is to avoid getting hung up on the technology and implementation details. Concentrate on who owns resources, who is responsible for creating/maintaining them, etc. Then think about the representations, protocols, and technologies.
This is what it might look like.
Create a user with three properties:
POST /user
fname=John&lname=Doe&age=25
The server responds:
200 OK
Location: /user/123
In the future, you can then retrieve the user information:
GET /user/123
The server responds:
200 OK
<fname>John</fname><lname>Doe</lname><age>25</age>
To modify the record (lname and age will remain unchanged):
PATCH /user/123
fname=Johnny
To update the record (and consequently lname and age will be NULL):
PUT /user/123
fname=Johnny
A great book on REST is REST in Practice.
Must reads are Representational State Transfer (REST) and REST APIs must be hypertext-driven
See Martin Fowlers article the Richardson Maturity Model (RMM) for an explanation on what an RESTful service is.
To be RESTful a Service needs to fulfill the Hypermedia as the Engine of Application State. (HATEOAS), that is, it needs to reach level 3 in the RMM, read the article for details or the slides from the qcon talk.
The HATEOAS constraint is an acronym
for Hypermedia as the Engine of
Application State. This principle is
the key differentiator between a REST
and most other forms of client server
system.
...
A client of a RESTful application need
only know a single fixed URL to access
it. All future actions should be
discoverable dynamically from
hypermedia links included in the
representations of the resources that
are returned from that URL.
Standardized media types are also
expected to be understood by any
client that might use a RESTful API.
(From Wikipedia, the free encyclopedia)
REST Litmus Test for Web Frameworks is a similar maturity test for web frameworks.
Approaching pure REST: Learning to love HATEOAS is a good collection of links.
REST versus SOAP for the Public Cloud discusses the current levels of REST usage.
REST and versioning discusses Extensibility, Versioning, Evolvability, etc.
through Modifiability
What is REST?
REST stands for Representational State Transfer. (It is sometimes
spelled "ReST".) It relies on a stateless, client-server, cacheable
communications protocol -- and in virtually all cases, the HTTP
protocol is used.
REST is an architecture style for designing networked applications.
The idea is that, rather than using complex mechanisms such as CORBA,
RPC or SOAP to connect between machines, simple HTTP is used to make
calls between machines.
In many ways, the World Wide Web itself, based on HTTP, can be viewed
as a REST-based architecture. RESTful applications use HTTP requests
to post data (create and/or update), read data (e.g., make queries),
and delete data. Thus, REST uses HTTP for all four CRUD
(Create/Read/Update/Delete) operations.
REST is a lightweight alternative to mechanisms like RPC (Remote
Procedure Calls) and Web Services (SOAP, WSDL, et al.). Later, we will
see how much more simple REST is.
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. REST is not a "standard". There will never be a W3C
recommendataion for REST, for example. And while there are REST
programming frameworks, working with REST is so simple that you can
often "roll your own" with standard library features in languages like
Perl, Java, or C#.
One of the best reference I found when I try to find the simple real meaning of rest.
http://rest.elkstein.org/
REST is using the various HTTP methods (mainly GET/PUT/DELETE) to manipulate data.
Rather than using a specific URL to delete a method (say, /user/123/delete), you would send a DELETE request to the /user/[id] URL, to edit a user, to retrieve info on a user you send a GET request to /user/[id]
For example, instead a set of URLs which might look like some of the following..
GET /delete_user.x?id=123
GET /user/delete
GET /new_user.x
GET /user/new
GET /user?id=1
GET /user/id/1
You use the HTTP "verbs" and have..
GET /user/2
DELETE /user/2
PUT /user
It's programming where the architecture of your system fits the REST style laid out by Roy Fielding in his thesis. Since this is the architectural style that describes the web (more or less), lots of people are interested in it.
Bonus answer: No. Unless you're studying software architecture as an academic or designing web services, there's really no reason to have heard the term.
I would say RESTful programming would be about creating systems (API) that follow the REST architectural style.
I found this fantastic, short, and easy to understand tutorial about REST by Dr. M. Elkstein and quoting the essential part that would answer your question for the most part:
Learn REST: A Tutorial
REST is an architecture style for designing networked applications.
The idea is that, rather than using complex mechanisms such as CORBA,
RPC or SOAP to connect between machines, simple HTTP is used to make
calls between machines.
In many ways, the World Wide Web itself, based on HTTP, can be viewed as a REST-based architecture.
RESTful applications use HTTP requests to post data (create and/or
update), read data (e.g., make queries), and delete data. Thus, REST
uses HTTP for all four CRUD (Create/Read/Update/Delete) operations.
I don't think you should feel stupid for not hearing about REST outside Stack Overflow..., I would be in the same situation!; answers to this other SO question on Why is REST getting big now could ease some feelings.
I apologize if I'm not answering the question directly, but it's easier to understand all this with more detailed examples. Fielding is not easy to understand due to all the abstraction and terminology.
There's a fairly good example here:
Explaining REST and Hypertext: Spam-E the Spam Cleaning Robot
And even better, there's a clean explanation with simple examples here (the powerpoint is more comprehensive, but you can get most of it in the html version):
http://www.xfront.com/REST.ppt or http://www.xfront.com/REST.html
After reading the examples, I could see why Ken is saying that REST is hypertext-driven. I'm not actually sure that he's right though, because that /user/123 is a URI that points to a resource, and it's not clear to me that it's unRESTful just because the client knows about it "out-of-band."
That xfront document explains the difference between REST and SOAP, and this is really helpful too. When Fielding says, "That is RPC. It screams RPC.", it's clear that RPC is not RESTful, so it's useful to see the exact reasons for this. (SOAP is a type of RPC.)
What is REST?
REST in official words, REST is an architectural style built on certain principles using the current “Web” fundamentals.
There are 5 basic fundamentals of web which are leveraged to create REST services.
Principle 1: Everything is a Resource
In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web.
Principle 2: Every Resource is Identified by a Unique Identifier (URI)
Principle 3: Use Simple and Uniform Interfaces
Principle 4: Communication is Done by Representation
Principle 5: Be Stateless
I see a bunch of answers that say putting everything about user 123 at resource "/user/123" is RESTful.
Roy Fielding, who coined the term, says REST APIs must be hypertext-driven. In particular, "A REST API must not define fixed resource names or hierarchies".
So if your "/user/123" path is hardcoded on the client, it's not really RESTful. A good use of HTTP, maybe, maybe not. But not RESTful. It has to come from hypertext.
The answer is very simple, there is a dissertation written by Roy Fielding.]1 In that dissertation he defines the REST principles. If an application fulfills all of those principles, then that is a REST application.
The term RESTful was created because ppl exhausted the word REST by calling their non-REST application as REST. After that the term RESTful was exhausted as well. Nowadays we are talking about Web APIs and Hypermedia APIs, because the most of the so called REST applications did not fulfill the HATEOAS part of the uniform interface constraint.
The REST constraints are the following:
client-server architecture
So it does not work with for example PUB/SUB sockets, it is based on REQ/REP.
stateless communication
So the server does not maintain the states of the clients. This means that you cannot use server a side session storage and you have to authenticate every request. Your clients possibly send basic auth headers through an encrypted connection. (By large applications it is hard to maintain many sessions.)
usage of cache if you can
So you don't have to serve the same requests again and again.
uniform interface as common contract between client and server
The contract between the client and the server is not maintained by the server. In other words the client must be decoupled from the implementation of the service. You can reach this state by using standard solutions, like the IRI (URI) standard to identify resources, the HTTP standard to exchange messages, standard MIME types to describe the body serialization format, metadata (possibly RDF vocabs, microformats, etc.) to describe the semantics of different parts of the message body. To decouple the IRI structure from the client, you have to send hyperlinks to the clients in hypermedia formats like (HTML, JSON-LD, HAL, etc.). So a client can use the metadata (possibly link relations, RDF vocabs) assigned to the hyperlinks to navigate the state machine of the application through the proper state transitions in order to achieve its current goal.
For example when a client wants to send an order to a webshop, then it have to check the hyperlinks in the responses sent by the webshop. By checking the links it founds one described with the http://schema.org/OrderAction. The client know the schema.org vocab, so it understands that by activating this hyperlink it will send the order. So it activates the hyperlink and sends a POST https://example.com/api/v1/order message with the proper body. After that the service processes the message and responds with the result having the proper HTTP status header, for example 201 - created by success. To annotate messages with detailed metadata the standard solution to use an RDF format, for example JSON-LD with a REST vocab, for example Hydra and domain specific vocabs like schema.org or any other linked data vocab and maybe a custom application specific vocab if needed. Now this is not easy, that's why most ppl use HAL and other simple formats which usually provide only a REST vocab, but no linked data support.
build a layered system to increase scalability
The REST system is composed of hierarchical layers. Each layer contains components which use the services of components which are in the next layer below. So you can add new layers and components effortless.
For example there is a client layer which contains the clients and below that there is a service layer which contains a single service. Now you can add a client side cache between them. After that you can add another service instance and a load balancer, and so on... The client code and the service code won't change.
code on demand to extend client functionality
This constraint is optional. For example you can send a parser for a specific media type to the client, and so on... In order to do this you might need a standard plugin loader system in the client, or your client will be coupled to the plugin loader solution.
REST constraints result a highly scalable system in where the clients are decoupled from the implementations of the services. So the clients can be reusable, general just like the browsers on the web. The clients and the services share the same standards and vocabs, so they can understand each other despite the fact that the client does not know the implementation details of the service. This makes possible to create automated clients which can find and utilize REST services to achieve their goals. In long term these clients can communicate to each other and trust each other with tasks, just like humans do. If we add learning patterns to such clients, then the result will be one or more AI using the web of machines instead of a single server park. So at the end the dream of Berners Lee: the semantic web and the artificial intelligence will be reality. So in 2030 we end up terminated by the Skynet. Until then ... ;-)
RESTful (Representational state transfer) API programming is writing web applications in any programming language by following 5 basic software architectural style principles:
Resource (data, information).
Unique global identifier (all resources are unique identified by URI).
Uniform interface - use simple and standard interface (HTTP).
Representation - all communication is done by representation (e.g. XML/JSON)
Stateless (every request happens in complete isolation, it's easier to cache and load-balance),
In other words you're writing simple point-to-point network applications over HTTP which uses verbs such as GET, POST, PUT or DELETE by implementing RESTful architecture which proposes standardization of the interface each “resource” exposes. It is nothing that using current features of the web in a simple and effective way (highly successful, proven and distributed architecture). It is an alternative to more complex mechanisms like SOAP, CORBA and RPC.
RESTful programming conforms to Web architecture design and, if properly implemented, it allows you to take the full advantage of scalable Web infrastructure.
Here is my basic outline of REST. I tried to demonstrate the thinking behind each of the components in a RESTful architecture so that understanding the concept is more intuitive. Hopefully this helps demystify REST for some people!
REST (Representational State Transfer) is a design architecture that outlines how networked resources (i.e. nodes that share information) are designed and addressed. In general, a RESTful architecture makes it so that the client (the requesting machine) and the server (the responding machine) can request to read, write, and update data without the client having to know how the server operates and the server can pass it back without needing to know anything about the client. Okay, cool...but how do we do this in practice?
The most obvious requirement is that there needs to be a universal language of some sort so that the server can tell the client what it is trying to do with the request and for the server to respond.
But to find any given resource and then tell the client where that resource lives, there needs to be a universal way of pointing at resources. This is where Universal Resource Identifiers (URIs) come in; they are basically unique addresses to find the resources.
But the REST architecture doesn’t end there! While the above fulfills the basic needs of what we want, we also want to have an architecture that supports high volume traffic since any given server usually handles responses from a number of clients. Thus, we don’t want to overwhelm the server by having it remember information about previous requests.
Therefore, we impose the restriction that each request-response pair between the client and the server is independent, meaning that the server doesn’t have to remember anything about previous requests (previous states of the client-server interaction) to respond to a new request. This means that we want our interactions to be stateless.
To further ease the strain on our server from redoing computations that have already been recently done for a given client, REST also allows caching. Basically, caching means to take a snapshot of the initial response provided to the client. If the client makes the same request again, the server can provide the client with the snapshot rather than redo all of the computations that were necessary to create the initial response. However, since it is a snapshot, if the snapshot has not expired--the server sets an expiration time in advance--and the response has been updated since the initial cache (i.e. the request would give a different answer than the cached response), the client will not see the updates until the cache expires (or the cache is cleared) and the response is rendered from scratch again.
The last thing that you’ll often here about RESTful architectures is that they are layered. We have actually already been implicitly discussing this requirement in our discussion of the interaction between the client and server. Basically, this means that each layer in our system interacts only with adjacent layers. So in our discussion, the client layer interacts with our server layer (and vice versa), but there might be other server layers that help the primary server process a request that the client does not directly communicate with. Rather, the server passes on the request as necessary.
Now, if all of this sounds familiar, then great. The Hypertext Transfer Protocol (HTTP), which defines the communication protocol via the World Wide Web is an implementation of the abstract notion of RESTful architecture (or an implementation of the abstract REST class if you're an OOP fanatic like me). In this implementation of REST, the client and server interact via GET, POST, PUT, DELETE, etc., which are part of the universal language and the resources can be pointed to using URLs.
If I had to reduce the original dissertation on REST to just 3 short sentences, I think the following captures its essence:
Resources are requested via URLs.
Protocols are limited to what you can communicate by using URLs.
Metadata is passed as name-value pairs (post data and query string parameters).
After that, it's easy to fall into debates about adaptations, coding conventions, and best practices.
Interestingly, there is no mention of HTTP POST, GET, DELETE, or PUT operations in the dissertation. That must be someone's later interpretation of a "best practice" for a "uniform interface".
When it comes to web services, it seems that we need some way of distinguishing WSDL and SOAP based architectures which add considerable overhead and arguably much unnecessary complexity to the interface. They also require additional frameworks and developer tools in order to implement. I'm not sure if REST is the best term to distinguish between common-sense interfaces and overly engineered interfaces such as WSDL and SOAP. But we need something.
REST is an architectural pattern and style of writing distributed applications. It is not a programming style in the narrow sense.
Saying you use the REST style is similar to saying that you built a house in a particular style: for example Tudor or Victorian. Both REST as an software style and Tudor or Victorian as a home style can be defined by the qualities and constraints that make them up. For example REST must have Client Server separation where messages are self-describing. Tudor style homes have Overlapping gables and Roofs that are steeply pitched with front facing gables. You can read Roy's dissertation to learn more about the constraints and qualities that make up REST.
REST unlike home styles has had a tough time being consistently and practically applied. This may have been intentional. Leaving its actual implementation up to the designer. So you are free to do what you want so as long as you meet the constraints set out in the dissertation you are creating REST Systems.
Bonus:
The entire web is based on REST (or REST was based on the web). Therefore as a web developer you might want aware of that although it's not necessary to write good web apps.
I think the point of restful is the separation of the statefulness into a higher layer while making use of the internet (protocol) as a stateless transport layer. Most other approaches mix things up.
It's been the best practical approach to handle the fundamental changes of programming in internet era. Regarding the fundamental changes, Erik Meijer has a discussion on show here: http://www.infoq.com/interviews/erik-meijer-programming-language-design-effects-purity#view_93197 . He summarizes it as the five effects, and presents a solution by designing the solution into a programming language. The solution, could also be achieved in the platform or system level, regardless of the language. The restful could be seen as one of the solutions that has been very successful in the current practice.
With restful style, you get and manipulate the state of the application across an unreliable internet. If it fails the current operation to get the correct and current state, it needs the zero-validation principal to help the application to continue. If it fails to manipulate the state, it usually uses multiple stages of confirmation to keep things correct. In this sense, rest is not itself a whole solution, it needs the functions in other part of the web application stack to support its working.
Given this view point, the rest style is not really tied to internet or web application. It's a fundamental solution to many of the programming situations. It is not simple either, it just makes the interface really simple, and copes with other technologies amazingly well.
Just my 2c.
Edit: Two more important aspects:
Statelessness is misleading. It is about the restful API, not the application or system. The system needs to be stateful. Restful design is about designing a stateful system based on a stateless API. Some quotes from another QA:
REST, operates on resource representations, each one identified by an URL. These are typically not data objects, but complex objects abstractions.
REST stands for "representational state transfer", which means it's all about communicating and modifying the state of some resource in a system.
Idempotence: An often-overlooked part of REST is the idempotency of most verbs. That leads to robust systems and less interdependency of exact interpretations of the semantics.
REST defines 6 architectural constraints which make any web service – a true RESTful API.
Uniform interface
Client–server
Stateless
Cacheable
Layered system
Code on demand (optional)
https://restfulapi.net/rest-architectural-constraints/
Old question, newish way of answering. There's a lot of misconception out there about this concept. I always try to remember:
Structured URLs and Http Methods/Verbs are not the definition of
restful programming.
JSON is not restful programming
RESTful programming is not for APIs
I define restful programming as
An application is restful if it provides resources (being the combination of data + state transitions controls) in a media type the client understands
To be a restful programmer you must be trying to build applications that allow actors to do things. Not just exposing the database.
State transition controls only make sense if the client and server agree upon a media type representation of the resource. Otherwise there's no way to know what's a control and what isn't and how to execute a control. IE if browsers didn't know <form> tags in html then there'd be nothing for you to submit to transition state in your browser.
I'm not looking to self promote, but i expand on these ideas to great depth in my talk http://techblog.bodybuilding.com/2016/01/video-what-is-restful-200.html .
An excerpt from my talk is about the often referred to richardson maturity model, i don't believe in the levels, you either are RESTful (level 3) or you are not, but what i like to call out about it is what each level does for you on your way to RESTful
This is amazingly long "discussion" and yet quite confusing to say the least.
IMO:
1) There is no such a thing as restful programing, without a big joint and lots of beer :)
2) Representational State Transfer (REST) is an architectural style specified in the dissertation of Roy Fielding.
It has a number of constraints. If your Service/Client respect those then it is RESTful. This is it.
You can summarize(significantly) the constraints to :
stateless communication
respect HTTP specs (if HTTP is used)
clearly communicates the content formats transmitted
use hypermedia as the engine of application state
There is another very good post which explains things nicely.
A lot of answers copy/pasted valid information mixing it and adding some confusion. People talk here about levels, about RESTFul URIs(there is not such a thing!), apply HTTP methods GET,POST,PUT ... REST is not about that or not only about that.
For example links - it is nice to have a beautifully looking API but at the end the client/server does not really care of the links you get/send it is the content that matters.
In the end any RESTful client should be able to consume to any RESTful service as long as the content format is known.
This answer is for absolute beginners, let's know about most used API architecture today.
To understand Restful programming or Restful API. First, you have to understand what API is, on a very high-level API stands for Application Programming Interface, it's basically a piece of software that can be used by another piece of software in order to allow applications to talk to each other.
The most widely used type of API in the globe is web APIs while an app that sends data to a client whenever a request comes in.
In fact, APIs aren't only used to send data and aren't always related to web development or javascript or python or any programming language or framework.
The application in API can actually mean many different things as long as the pice of software is relatively stand-alone. Take for example, the File System or the HTTP Modules we can say that they are small pieces of software and we can use them, we can interact with them by using their API. For example when we use the read file function for a file system module of any programming language, we are actually using the file_system_reading API. Or when we do DOM manipulation in the browser, we're are not really using the JavaScript language itself, but rather, the DOM API that browser exposes to us, so it gives us access to it. Or even another example let's say we create a class in any programming language like Java and then add some public methods or properties to it, these methods will then be the API of each object created from that class because we are giving other pieces of software the possibility of interacting with our initial piece of software, the objects in this case. S0, API has actually a broader meaning than just building web APIs.
Now let's take a look at the REST Architecture to build APIs.
REST which stands for Representational State Transfer is basically a way of building web APIs in a logical way, making them easy to consume for ourselves or for others.
To build Restful APIs following the REST Architecture, we just need to follow a couple of principles.
1. We need to separate our API into logical resources.
2. These resources should then be exposed by using resource-based URLs.
3. To perform different actions on data like reading, creating, or deleting data the API should use the right HTTP methods and not the URL.
4. Now the data that we actually send back to the client or that we received from the client should usually use the JSON data format, were some formatting standard applied to it.
5. Finally, another important principle of EST APIs is that they must be stateless.
Separate APIs into logical resources: The key abstraction of information in REST is a resource, and therefore all the data that we wanna share in the API should be divided into logical resources. What actually is a resource? Well, in the context of REST it is an object or a representation of something which has some data associated to it. For example, applications like tour-guide tours, or users, places, or revies are of the example of logical resources. So basically any information that can be named can be a resource. Just has to name, though, not a verb.
Expose Structure: Now we need to expose, which means to make available, the data using some structured URLs, that the client can send a request to. For example something like this entire address is called the URL. and this / addNewTour is called and API Endpoint.
Our API will have many different endpoints just like bellow
https://www.tourguide.com/addNewTour
https://www.tourguide.com/getTour
https://www.tourguide.com/updateTour
https://www.tourguide.com/deleteTour
https://www.tourguide.com/getRoursByUser
https://www.tourguide.com/deleteToursByUser
Each of these API will send different data back to the client on also perform different actions.
Now there is something very wrong with these endpoints here because they really don't follow the third rule which says that we should only use the HTTP methods in order to perform actions on data. So endpoints should only contain our resources and not the actions that we are performed on them because they will quickly become a nightmare to maintain.
How should we use these HTTP methods in practice? Well let's see how these endpoints should actually look like starting with /getTour. So this getTour endpoint is to get data about a tour and so we should simply name the endpoint /tours and send the data whenever a get request is made to this endpoint. So in other words, when a client uses a GET HTTP method to access the endpoint,
(we only have resources in the endpoint or in the URL and no verbs because the verb is now in the HTTP method, right?
The common practice to always use the resource name in the plural which is why I wrote /tours nor /tour.)
The convention is that when calling endpoint /tours will get back all the tours that are in a database, but if we only want the tour with one ID, let's say seven, we add that seven after another slash(/tours/7) or in a search query (/tours?id=7), And of course, it could also be the name of a tour instead of the ID.
HTTP Methods: What's really important here is how the endpoint name is the exact same name for all.
GET: (for requesting data from the server.)
https://www.tourguide.com/tours/7
POST: (for sending data to the server.)
https://www.tourguide.com/tours
PUT/PATCH: (for updating requests for data to the server.) https://www.tourguide.com/tours/7
DELETE: (for deleting request for data to the server.)
https://www.tourguide.com/tours/7
The difference between PUT and PATCH->
By using PUT, the client is supposed to send the entire updated object, while with PATCH it is supposed to send only the part of the object that has been changed.
By using HTTP methods users can perform basic four CRUD operations, CRUD stands for Create, Read, Update, and Delete.
Now there could be a situation like a bellow:
So, /getToursByUser can simply be translated to /users/tours, for user number 3 end point will be like /users/3/tours.
if we want to delete a particular tour of a particular user then the URL should be like /users/3/tours/7, here user id:3 and tour id: 7.
So there really are tons of possibilities of combining resources like this.
Send data as JSON: Now about data that the client actually receives, or that the server receives from the client, usually we use the JSON Data Format.
A typical JSON might look like below:
Before sending JSON Data we usually do some simple response formatting, there are a couple of standards for this, but one of the very simple ones called Jsend. We simply create a new object, then add a status message to it in order to inform the client whether the request was a success, fail, or error. And then we put our original data into a new object called Data.
Wrapping the data into an additional object like we did here is called Enveloping, and it's a common practice to mitigate some security issues and other problems.
Restful API should always be stateless: Finally a RESTful API should always be stateless meaning that, in a stateless RESTful API all state is handled on the client side no on the server. And state simply refers to a piece of data in the application that might change over time. For example, whether a certain user is logged in or on a page with a list with several pages what the current page is?
Now the fact that the state should be handled on the client means that each request must contain all the information that is necessary to process a certain request on the server. So the server should never ever have to remember the previous request in order to process the current request.
Let's say that currently we are on page five and we want to move forward to page six. Sow we could have a simple endpoint called /tours/nextPage and submit a request to server, but the server would then have to figure out what the current page is, and based on that server will send the next page to the client. In other words, the server would have to remember the previous request. This is what exactly we want to avoid in RESTful APIs.
Instead of this case, we should create a /tours/page endpoint
and paste the number six to it in order to request page number six /tours/page/6 . So the server doesn't have to remember anything in, all it has to do is to send back data for page number six as we requested.
Statelessness and Statefulness which is the opposite are very important concepts in computer science and applications in general
REST === HTTP analogy is not correct until you do not stress to the fact that it "MUST" be HATEOAS driven.
Roy himself cleared it here.
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). From that point on, all application state transitions must be driven by client selection of server-provided choices that are present in the received representations or implied by the user’s manipulation of those representations. The transitions may be determined (or limited by) the client’s knowledge of media types and resource communication mechanisms, both of which may be improved on-the-fly (e.g., code-on-demand).
[Failure here implies that out-of-band information is driving interaction instead of hypertext.]
REST stands for Representational state transfer.
It relies on a stateless, client-server, cacheable communications protocol -- and in virtually all cases, the HTTP protocol is used.
REST is often used in mobile applications, social networking Web sites, mashup tools and automated business processes. The REST style emphasizes that interactions between clients and services is enhanced by having a limited number of operations (verbs). Flexibility is provided by assigning resources (nouns) their own unique universal resource indicators (URIs).
Introduction about Rest
Talking is more than simply exchanging information. A Protocol is actually designed so that no talking has to occur. Each party knows what their particular job is because it is specified in the protocol. Protocols allow for pure information exchange at the expense of having any changes in the possible actions. Talking, on the other hand, allows for one party to ask what further actions can be taken from the other party. They can even ask the same question twice and get two different answers, since the State of the other party may have changed in the interim. Talking is RESTful architecture. Fielding's thesis specifies the architecture that one would have to follow if one wanted to allow machines to talk to one another rather than simply communicate.
There is not such notion as "RESTful programming" per se. It would be better called RESTful paradigm or even better RESTful architecture. It is not a programming language. It is a paradigm.
From Wikipedia:
In computing, representational state transfer (REST) is an
architectural style used for web development.
The point of rest is that if we agree to use a common language for basic operations (the http verbs), the infrastructure can be configured to understand them and optimize them properly, for example, by making use of caching headers to implement caching at all levels.
With a properly implemented restful GET operation, it shouldn't matter if the information comes from your server's DB, your server's memcache, a CDN, a proxy's cache, your browser's cache or your browser's local storage. The fasted, most readily available up to date source can be used.
Saying that Rest is just a syntactic change from using GET requests with an action parameter to using the available http verbs makes it look like it has no benefits and is purely cosmetic. The point is to use a language that can be understood and optimized by every part of the chain. If your GET operation has an action with side effects, you have to skip all HTTP caching or you'll end up with inconsistent results.
This is very less mentioned everywhere but the Richardson's Maturity Model is one of the best methods to actually judge how Restful is one's API. More about it here:
Richardson's Maturity Model
What is API Testing?
API testing utilizes programming to send calls to the API and get the yield. It testing regards the segment under test as a black box. The objective of API testing is to confirm right execution and blunder treatment of the part preceding its coordination into an application.
REST API
REST: Representational State Transfer.
It’s an arrangement of functions on which the testers performs requests and receive responses. In REST API interactions are made via HTTP protocol.
REST also permits communication between computers with each other over a network.
For sending and receiving messages, it involves using HTTP methods, and it does not require a strict message definition, unlike Web services.
REST messages often accepts the form either in form of XML, or JavaScript Object Notation (JSON).
4 Commonly Used API Methods:-
GET: – It provides read only access to a resource.
POST: – It is used to create or update a new resource.
PUT: – It is used to update or replace an existing resource or create a new resource.
DELETE: – It is used to remove a resource.
Steps to Test API Manually:-
To use API manually, we can use browser based REST API plugins.
Install POSTMAN(Chrome) / REST(Firefox) plugin
Enter the API URL
Select the REST method
Select content-Header
Enter Request JSON (POST)
Click on send
It will return output response
Steps to Automate REST API
I would say that an important building block in understanding REST lies in the endpoints or mappings, such as /customers/{id}/balance.
You can imagine such an endpoint as being the connecting pipeline from the website (front-end) to your database/server (back-end). Using them, the front-end can perform back-end operations which are defined in the corresponding methods of any REST mapping in your application.