Beruflich Dokumente
Kultur Dokumente
— SitePoint
(https://www.sitepoint.com/)
JavaScript (Https://Www.Sitepoint.Com/Javascript/) > February 05, 2020 > By Craig Buckler (https://www.sitepoint.com/author/craig-buckler/)
REST is an acronym for Representational State Transfer — an almost meaningless description of the most-used web
service technology! REST is a way for two computer systems to communicate over HTTP in a similar way to web browsers
and servers.
Sharing data between two or more systems has always been a fundamental requirement of software development. For
example, consider buying motor insurance. Your insurer must obtain information about you and your vehicle so they request
data from car registration authorities, credit agencies, banks, and other systems. All this happens transparently in real-time to
determine whether a policy can be offered.
This popular article was updated in 2020 to accurately explain modern REST APIs. For more on REST APIs, read RESTful Web
API Design with Node.js (https://www.sitepoint.com/premium/books/restful-web-api-design-with-node-js-10-third-edition?
utm_source=blog&utm_medium=articles).
REST Example
Open the following link in your browser to request a random programming joke:
This is a public API implemented as RESTful web service (it follows REST conventions). Your browser will show an awful
JSON-formatted programming joke, such as:
[
{
"id": 29,
"type": "programming",
"setup": "There are 10 types of people in this world...",
"punchline": "Those who understand binary and those who don't"
}
]
https://www.sitepoint.com/developers-rest-api/
1/11
3/15/2020
You Dousing
(https://www.sitepoint.com/)
could request the same URL and get a response You Know
anyWhat
HTTPa REST API
client, Is? —as
such SitePoint
curl (https://curl.haxx.se/):
curl "https://official-joke-api.appspot.com/jokes/programming/random"
HTTP client libraries are available in all popular languages and runtimes including Fetch in JavaScript
(https://developer.mozilla.org/docs/Web/API/Fetch_API) and le_get_contents() in PHP
(https://www.php.net/manual/en/function. le-get-contents.php). A JSON response is machine-readable so it can be parsed
and output in HTML or any other format.
REST was de ned in 2000 by Roy Fielding and is considerably simpler. It’s not a standard but a set of recommendations and
constraints for RESTful web services. These include:
1 Client-Server. SystemA makes an HTTP request to a URL hosted by SystemB, which returns a response.
It’s identical to how a browser works. The application makes a request for a speci c URL. The request is routed to a web
server that returns an HTML page. That page may contain references to images, style sheets, and JavaScript, which incur
further requests and responses.
2 Stateless. REST is stateless: the client request should contain all the information necessary to respond to a request. In
other words, it should be possible to make two or more HTTP requests in any order and the same responses will be
received.
4 Layered. The requesting client need not know whether it’s communicating with the actual server, a proxy, or any other
intermediary.
1 An Endpoint URL. An application implementing a RESTful API will de ne one or more URL endpoints with a domain, port,
path, and/or querystring — for example, https://mydomain/user/123?format=json.
https://www.sitepoint.com/developers-rest-api/
2/11
2
3/15/2020 Dobe
(https://www.sitepoint.com/)
The HTTP method. Differing HTTP methods can Youused
Knowon
What
anya REST API Is?
endpoint — SitePoint
which map to application create, read, update,
and delete (CRUD) operations:
Examples:
4 Body Data. Data is normally transmitted in the HTTP body in an identical way to HTML <form> submissions or by
sending a single JSON-encoded data string.
The Response
The response payload can be whatever is practical: data, HTML, an image, an audio le, and so on. Data responses are
typically JSON-encoded, but XML, CSV, simple strings, or any other format can be used. You could allow the return format to
be speci ed in the request — for example, /user/123?format=json or /user/123?format=xml.
An appropriate HTTP status code (https://developer.mozilla.org/docs/Web/HTTP/Status) should also be set in the response
header. 200 OK is most often used for successful requests, although 201 Created may also be returned when a record is
created. Errors should return an appropriate code such as 400 Bad Request, 404 Not Found, 401 Unauthorized, and so
on.
However, there are no strict rules. Endpoint URLs, HTTP methods, body data, and response types can be implemented as you
like. POST, PUT, and PATCH are often
For example,
https://www.sitepoint.com/developers-rest-api/
used interchangeably so anywill create or update a record. 3/11
REST “Hello World” Example
3/15/2020 (https://www.sitepoint.com/) Do You Know What a REST API Is? — SitePoint
The following code creates a RESTful web service using the Node.js Express framework (https://expressjs.com/). A single
/hello/ endpoint responds to GET requests.
Ensure you have Node.js (https://nodejs.org/en/) installed, then create a new folder named restapi. Create a new
package.json le within that folder with the following content:
{
"name": "restapi",
"version": "1.0.0",
"description": "REST test",
"scripts": {
"start": "node ./index.js"
},
"dependencies": {
"express": "4.17.1"
}
}
Run npm install from the command line to fetch the dependencies, then create an index.js le with the following code:
// initialize
const
port = 8888,
express = require('express'),
app = express();
// start server
app.listen(port, () =>
console.log(`Server started on port ${port}`);
);
https://www.sitepoint.com/developers-rest-api/
4/11
3/15/2020the application from
Launch Donpm
(https://www.sitepoint.com/)
the command line using You Know What
start anda REST
openAPI Is? — SitePoint
http://localhost:8888/hello/ in a browser.
The following JSON is displayed in response to the GET request:
{
"message": "Hello world!"
}
{
"message": "Hello everyone!"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>REST test</title>
</head>
<body>
<script>
fetch('http://localhost:8888/hello/')
.then((response) => {
return response.json();
})
.then((json) => {
console.log(json);
});
</script>
</body>
</html>
The fetch call makes the same API request and browser console shows Object { message: "Hello world!" } as you
would expect.
https://www.sitepoint.com/developers-rest-api/
5/11
3/15/2020 presume your RESTful
However, Do You
(https://www.sitepoint.com/)
web service was now putKnow What
live on a REST
the Web API Is? —
at the SitePoint
domain http://mydomain.com/hello/.
The page JavaScript fetch() URL is changed accordingly, but opening http://localhost:8888/ in the browser now
returns the console error Cross-Origin Request Blocked.
The web service API code can therefore be changed to allow access from any client-side script running on any domain:
Alternatively, an Express.js middleware function could append the header to every endpoint request:
// enable CORS
app.use((req, res, next) => {
res.append('Access-Control-Allow-Origin', '*');
next();
});
REST Challenges
The success of REST owes much to its simplicity. Developers are free to implement RESTful APIs as they like, but that can
lead to further challenges.
Endpoint Consensus
Consider the following endpoints:
https://www.sitepoint.com/developers-rest-api/
6/11
3/15/2020 Do You Know What a REST API Is? — SitePoint
/user/123 (https://www.sitepoint.com/)
/user/id/123
/user/?id=123
All are valid options to fetch data for user 123. The number of combinations increase further when you have more complex
operations. For example, return ten users whose surnames start with ‘A’ and work for companyX starting at record 51 when
ordered by date of birth in reverse chronological order.
Ultimately, it doesn’t matter how you format URLs, but consistency across your API is important. That can be di cult to
achieve on large codebases with many developers.
API Versioning
API changes are inevitable, but endpoint URLs should never be invalidated when they’re being used internally and/or by third-
party applications.
APIs are often versioned to avoid compatibility issues — such as /2.0/user/123 supersedes /user/123 — but the old
endpoint remains active. However, this increases the workload, as multiple APIs are maintained. Older APIs can eventually be
scrapped, but the process requires careful planning.
Authentication
The Joke API shown above is open: any system can fetch a joke without authorization. This is not viable for APIs which access
private data or permit update and delete requests.
Client-side applications on the same domain as the RESTful API will send and receive cookies just like any other HTTP
request. (Note that Fetch() in older browsers requires the credentials init option
(https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) to be set.) An API request
can therefore be validated to ensure a user is logged in and has appropriate rights.
Third-party applications must use alternative methods of authorization. Common authentication options
(https://swagger.io/docs/speci cation/authentication/) include:
API authentication will vary depending on the use context. In some cases, the third-party application is considered to be
another logged-in user with speci c rights and permissions — for example, when generating directions from a map API. In
other cases, the third-party application is being used by a registered user and can only access their data — for example, when
fetching email content or documents.
Security
A RESTful API provides another route to access and manipulate your application. Even if it’s not an interesting hacking target,
a badly behaved client could send thousands of requests every second and crash your server.
Security is beyond the scope of this article, but common best practises include:
use HTTPS
use a robust authentication method
use CORS to limit client-side calls to speci c domains
provide minimum functionality — that is, don’t create a DELETE options which are
not required
validate all endpoint URLs and body data
avoid exposing API tokens in client-side JavaScript
block access from unknown domains or IP addresses
block unexpectedly large payloads
consider rate limiting — that is, requests using the same API token or IP address
are limited to N per minute
respond with an appropriate HTTP status code
(https://developer.mozilla.org/docs/Web/HTTP/Status) and caching
(https://developer.mozilla.org/docs/Web/HTTP/Headers/Cache-Control) header
log requests and investigate failures.
Consider a RESTful API which provides access to author and book data. To show data for the top 10 selling books, the client
will:
1 Request the rst 10 /book/ details ordered by number of sales (top seller rst).
The response contains a list of books with each author ID.
2 Make up to 10 /author/{id} requests to fetch each author’s name.
https://www.sitepoint.com/developers-rest-api/
8/11
3/15/2020
This Do Yoube
is known as the N+1(https://www.sitepoint.com/)
problem; N API requests must Know What
made fora REST
each API Is? —
result in SitePoint
the parent request.
If this is a common use case, the RESTful API could be changed so that every returned book contained the full author details
such as their name, age, country, biography, and so on. It could also provide full details of their other books — although this
would considerably increase the response payload!
To avoid massive responses, the API could be adjusted so author details can be controlled — for example, ?
author_details=basic — but the number of options can quickly become bewildering.
GraphQL addresses many of the challenges posed by RESTful APIs. That said, few companies have problems comparable to
Facebook. It’s worth considering GraphQL once your RESTful API evolves beyond its simple starting point.
There are numerous tools to help with RESTful API development in all languages. Notable options include:
There are also plenty of public REST APIs catering for jokes, currency conversion, geocoding, government data, and every topic
you can think of. Many are free, although some require you to sign up for an API key or use other authentication methods.
Categorized lists include: