r/AskComputerScience • u/[deleted] • Feb 14 '19
What is a REST API ? Explain it like I'm 5.
46
u/venuswasaflytrap Feb 14 '19 edited Feb 14 '19
The main thing about REST is that it's stateless. That means that it doesn't maintain some sort of session or anything like that. So you shouldn't need to do a handshake or anything. If you send a request with the right headers then you will get a response (though those headers might include some sort of authentication).
REST should not return a user interface either - only data.
e.g. you don't get a bunch of java-script and HTML to be rendered in order to interface with the API - you get data in some form, and the details of the interface are up to your application (which indeed may get HTML and JS or other interface from some other source).
In a colloquial sense, REST apis generally mean:
You get JSON data back
You correctly use HTTP Methods
GET should only get data, not change the state of the data
POST should only create a new record
PUT should only update all the fields of a record
PATCH should only update some of the fields of a record
DELETE should only delete records
There are other things that could be used instead of JSON or HTTP methods and still be RESTful, but generally this is what it used.
e.g.
GET api/movies/1returns
{
"id": 1,
"name": "Con Air",
"reviews": [
{
"id": 1,
"content": "A triumph"
}
]
}and
POST api/movies/1/reviews
BODY:
{
"content": "Best movie ever"
}Returns a HTTP status code of 201 (created) maybe with the body of the review:
{
"id": 2,
"content": "Best movie ever"
}Then when you get again
GET api/movies/1returns
{
"id": 1,
"name": "Con Air",
"reviews": [
{
"id": 1,
"content": "A triumph"
},
{
"id": 2,
"content": "Best movie ever"
}
]
}Or something like that
4
u/FinickyFizz Feb 14 '19
What's the difference between REST and SOAP
14
u/gradual_alzheimers Feb 14 '19
SOAP is an actual protocol where you pass serialized objects in XML that have a specific format. REST is an architectural style of sorts, think of it as a guideline or a big idea. In SOAP, you’ll have an envelope object that contains a body with the data you want to transmit. This protocol allows multiple state changes to occur in a single transaction. Though this protocol is well defined it’s often complex and hard to reason about as its structure isn’t as self descriptive as REST. A major difference is REST is typically resource driven, whereas SOAP is action driven. For instance if I want to get user 123 with rest I can typically say /api/user/123. With SOAP I’ll have to create an xml object that corresponds to some getUser() method the api exposes. There is a lot more overhead with SOAP and isn’t great for a lot of modern applications though some companies still prefer it in distributed enterprise scenarios.
6
u/mulletlaw Feb 14 '19
SOAP is almost always way more trouble than it's worth. Finding an API in the wild that only accepts SOAP will ruin your day. It could turn a one to two day implementation into a week or more depending on how well they designed their WSDL.
1
u/Redtitwhore Feb 15 '19
That hasn't been my experience at all using WCF. WSDLs are automatically generated which can be imported to generate all the client code for you. I'm not sure how it can be any easier.
1
u/mulletlaw Feb 15 '19
What if the WSDL is outdated or Malformed? I've had to reimplement WSDLs from scratch on the client side just to get the damn service to work because the auto generated WSDL was trash.
1
u/Redtitwhore Feb 15 '19
Never heard of that happening, but yeah, that would be a nightmare. Wsdls are complex but humans should never have to deal with them directly. Tooling should create them and consume them.
4
u/venuswasaflytrap Feb 14 '19
Specifically - SOAP is a specific protocol, while REST is more of a philosophy for a protocol (though most "well-made" REST APIs almost all look similar to my example above).
SOAP explicitly uses XML, and a number of other things.
https://en.wikipedia.org/wiki/SOAP#SOAP_building_blocks
Soap doesn't explicitly have to be stateless, while the REST philosophy explicitly advocates for that.
https://stackoverflow.com/questions/19884295/soap-vs-rest-differences
On a functional level, SOAP generally means some sort of session key and a handshake (though SOAP doesn't have to be that), and it means that you're dealing with XML.
REST generally means fairly human readable API endpoints, standard HTTP methods and JSON.
4
u/codeforces_help Feb 14 '19
Hi.
it's stateless.
When you say stateless does the following scenario hold?
I am querying for a movie database and I ended up voting up the movie. Now if I query for the movie again it will show that its state has changed with my one vote added.
Does this qualify strictly as REST?
4
u/PM_ME_YOUR_REPO Feb 14 '19
Yes, because the vote action is a POST. You're adding a record with your vote.
(Sometimes voting may be done with ajax in some other manner)
1
u/codeforces_help Feb 14 '19
So only the
GETmethod needs be stateless?7
u/PM_ME_YOUR_REPO Feb 14 '19
You are conflating state with persistence. "State" approximately means it remembers in memory what you're doing and saves it specifically for you. "Persistence" means that your data is written to and read from a database of some sort. REST and persistence go hand in hand. It's a general storage of information, completely disconnected from who you are or whether you continue interacting with the API.
2
u/venuswasaflytrap Feb 14 '19
The data has a state, but you can't be halfway through a transaction.
E.g. an API where the client says
"Okay I'm the client here's my credentials, validate me and wait for my request"
And the server says
"Okay, we've validated you, we're waiting on your request"
Then the client says
"I'd like some resource please"
Would be not stateless.
Basically, after any API call, the client should be able to walk away without closing anything, or terminating anything.
Affecting the state of the data itself, by POSTing something or DELETE ING something, is not what stateless refers to.
1
u/FabianRo Feb 18 '19
This doesn't really explain what it is. You start with "it is stateless", which doesn't tell me anything, because I wouldn't even know what would be meant with "states" if there were any.
It's like when I once asked an SAP employee what SAP really is and he starting telling me that it's great, that you can use it for managing a company and so on. But that wasn't the question, I wanted to know what it is.
2
u/venuswasaflytrap Feb 18 '19
Hopefully you know what an API, or specifically an API over HTTP/HTTPS is. If not, here's a very quick background.
When you type "https://old.reddit.com/r/AskComputerScience/comments/aqip26/what_is_a_rest_api_explain_it_like_im_5/egq0hb5/?context=3" into your browser, you're telling your browser to contact the server at "old.reddit.com" (through DNS and routing and all that) - and asking it for "r/AskComputerScience/comments/aqip26/what_is_a_rest_api_explain_it_like_im_5/egq0hb5/" with the parameters "?context=3". Additionally, your browser is also sending other details in the request as "headers", for example my browser sends "user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36" as one of it's headers, so that the server knows what browser it is.
I'm not entirely clear on whether this interaction could be considered an API on it's own, but REST apis work very similarly.
Some client - a browser, a command line curl request, a javaascript call, whatever - sends a request to a server through HTTP, with parameters, headers and possibly a body too. The server responds with some content. In the case of normal webpages, HTML comes back (e.g. view source on any web page). Browsers will generally parse that, and make more requests (requesting and getting the CSS, JS, images, and other resources from the server).
In a JSON REST API, all you get back is JSON.
e.g. if you browse
You are sending parameters "q=London,UK" and "appid=b6907d289e10d714a6e88b30761fae22" to the server at "https://samples.openweathermap.org" and asking for the resource "/data/2.5/weather", (and doing so with a GET request).
And what you get back is just text, in the form of JSON, rather than getting a whole web page back
That's a JSON API, over HTTP, (that happens to be RESTful too).
So REST specifically:
By "Stateless" I mean that you shouldn't need to worry about 'opening' or 'closing' connections.
With every request, it should be totally fine if your client magically disappears after it makes the request. The server shouldn't be waiting for something. You can obviously modify the resources on the server. E.g. Create a new review, on the server as in above, but that's considered persisting the data rather than creating a state for the server.
Also, the server can have resources that expire. E.g. The client can create a security token against it's credentials that lasts half a day or something, and it can use that security token to access other resources, so it can accomplish similar goals as a sessions. But there shouldn't be a case when the server returns "You're already logged in", or anything like that.
The point is that if your client crashes or something, or you log on from a different client, it shouldn't matter what state the server is in. With some protocols you'd get stuff like "You're already logged in somewhere else", and you'd have to terminate sessions elsewhere or something. REST is philosophically against this.
In practice, the other thing, which I don't think is technically part of the REST philosophy, but pretty much should be, is using HTTP methods correctly.
Many amateur coders tend to think of "GET" as "The one where the parameters are in the URL" and "POST" as the "secure one", because a lot of their familiarity is through the method attribute on html forms - at least, this was my experience. When making larger systems, this makes a big ol mess.
There is a concept called "Idempotence" which can basically be summed up as "If you do the action 1, or 100, or any number of times (more than 0), the outcome will be the same". A good example of this is pressing save on a text document (without modifying the text in between). Pressing save once, is different than not pressing save at all, but if you accidentally save twice, it makes no difference. Imagine if every time you pressed save, it made a copy. If you accidentally ctrl-s twice, you'll have two exact copies of the same thing. If you pressed it 10 times, you'd get 10 copies. If you pressed it 10 thousand times, you'd run out of drive space. That wouldn't be idempotent.
Luckily you can just ctrl-s all the time knowing that whatever you have in front of you will just update, and if the text hasn't changed pressing it 100 times won't make any difference. That's idempotent.
In HTTP REST:
GET requests should be idempotent - you should be able to get a resource 1000 times and not modify the data
PUT requests should be idempotent - you should be able to put the same data into a resource 1000 times and that resource should end up with that same data (like saving over and over)
PATCH requests should be idempotent - you should be able to modify a single part of a resource over and over again, e.g. if you rename it 'TheName' 100 times, it should still be 'TheName' at the end
DELETE requests should be idempotent - you should be able to delete the same resource 1000 times, and it will be just as deleted
However
POST will not be idempotent. POST should create something new (or try to anyway), so if you run it 1000 times, you'll have 1000 things.
Idempotency is good, because when performing idempotent operations (e.g. all but post) you don't have to worry about whether they got sent twice (user presses refresh 10 times or something), and you inherently protect against lots of async issues.
This is all in the spec in better detail than I can provide of course:
https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
If you understand the above and can implement an API that follows those rules, it will be more than enough to convince an employer that you "know REST APIs". There might be some pedantic discussion with other developers about the details about whether something is 'truly' RESTful due to some variation that you put in the API, but you can go down a huge rabbit hole with that.
8
u/N0N-Available Feb 14 '19 edited Feb 14 '19
RESTFul APIs are really a design philosophy/ architectural style. An API is just a set of rules to interface with a system. You can say a user manual is for a phone is just a set of apis for this phone. It tells you if you want the phone to turn on, press this button, want to make call? Input this number into this program/app. An API is just a way for the system to expose its services.
A RESTFul API is the same thing but in the context of communicating between clients (web or apps) and server. The general architecture is that server holds data and offers some services. It exposes apis that let's anyone (client- websites or apps) who follow the rules get the data or use its services.
This is a way to standardize communication methods but keeping things simple and relatively secure. It's very much like how post office determines how you fill out your envelope so they can deliver your mail. You don't need to know how they plan the route or which state your letter actually passes through,but they pretty much guarantee that if you give them address and zip code on your mail, they will get it to the receiver. REST API is the same thing. Using Twitter for example. One of its APIs could say give me user ID and I'll give you all the tweets this user has ever posted ( simplified for the sake of eli5). So Twitter app creates http request, and make sure that the user ID is in there, formatted as the API states ( typically in json). They send this to the Twitter server, and Twitter server sees the request, able to understand the data (cuz it knows how JSON works), so it knows hey this app is asking for all the Tweets for this person, let me check my database for all the tweets made by this person. I can do that because I know the user ID, it's in the request formatted in such way that i can read without contacting the sender. So the server finds all the tweets and packages into JSON, send it back to the Twitter app.
In case you were wondering, json is basically just a format for message. It's just a standard so that everyone knows how to decode the message. Back to the tweet example. Let's say it was 20 tweets that the server returned to the app. JSON simply says if it's a list of things, use [] for the whole list, surround the individual tweet with {} , etc. So when the app gets the tweets, it knows how to parse it, turn it into an array, and display it in a table. This way there's a standard form of communication and both sender and receiver knows how to read the data.
You've probably heard of the phrase open API gets thrown around. In the Twitter example, let say it wasn't open, so only Twitter apps can communicate with Twitter server following the API. Open api simply means if you made an app, you can also access the Twitter database as long as you follow its APIs. And this is how apps do integration with other apps. Doing it this way allows the server to expose its data and services in a controlled / safe manner, cuz obvs ppl can't just be like yo Twitter server, give me all the passwords.
In short, REST API is a standard/protocol for applications to exchange data/communicate.
Disclaimer: this is my personal understanding of it. Feel free to add or correct so I can learn too.
Edit: stupid autocorrects.
1
Feb 15 '19
How is REST API related to http?
2
u/Poddster Feb 15 '19
How is REST API related to http?
Quality homework question this. Let us know the marks you get, please.
3
u/larrylenny Feb 14 '19
It's an approach to helping people solve problems by being able to perform actions based on a URL. GET data from a server POST data to a server PUT updated data on a server DELETE data from a server.
There are many other things you can do but these are the most basic and commonly used.
Your URL can be designed to identify some thing you want to perform an action on e.g http://website.com/customers/{id}
If you send a request to your server with any of those actions - they should follow the agreed upon actions.
0
Feb 14 '19
So how Different website's API differ from each other?
4
u/yazalama Feb 14 '19
Just think of an API as an agreed upon way for exchanging data between a client and server. If you are getting location data from say Google maps API, it is not important for you to understand the exact details and implementation of how they got that data, you just need to know how to request it, and what the data will look like. There are endless possibilities of how you can handle/process data with API's and do whatever you need, but the important thing is that whatever API you are working with, to understand it's conventions and how to interact with it. What all REST API's have in common is that they typically communicate over HTTP and can handle different operations (GET, POST, PUT, DELETE etc.) for whoever on the internet desires to send/receive data to the api.
1
0
7
u/og-cheeselover97 Feb 14 '19
It's a bucket where you ask a server hey you pls give me database data given these requirements and it'll return you a query result in either xml or json .
PS it's more than that but this is the main idea