Home >Web Front-end >JS Tutorial >What Is a REST API?
Detailed explanation of REST API: Easy to understand the most commonly used network service technologies
REST, which stands for "Representational State Transfer", is the most widely used network service technology at present. Although its name is a bit abstract, the REST API is essentially a way for two computer systems to communicate using HTTP technology common in web browsers and servers.
In software development, data sharing between systems is always a basic requirement. For example, when purchasing auto insurance, the insurance company needs to obtain your personal information and vehicle information, so it needs to request data from vehicle registration agencies, credit agencies, banks and other systems. All of this is done transparently in real time to determine whether an insurer can offer a competitive policy.
API (Application Programming Interface) realizes such inter-system communication by providing an interface for inter-system communication. REST is just a widely adopted API style, and we use it to communicate with internal and external parties in a consistent and predictable way. This can be likened to how we used to send letters with stamps, addresses and envelopes in some way to ensure they were delivered and read.
REST is often used for people interactions in network systems, such as retrieving and updating account information in social media applications.
Open the following link in your browser to request a random computer problem from the open trivia database:
https://www.php.cn/link/bf13848f7f02f488b2e12e009a8b0df3
This is a public API implemented as a RESTful web service (it follows the REST convention). Your browser will display a single JSON format quiz question with answers, such as:
<code>{ "response_code": 0, "results": [ { "category": "Science: Computers", "type": "multiple", "difficulty": "easy", "question": "What does GHz stand for?", "correct_answer": "Gigahertz", "incorrect_answers": [ "Gigahotz", "Gigahetz", "Gigahatz" ] } ] }</code>
You can use any HTTP client (such as curl) to request the same URL and get the response:
<code>curl "https://www.php.cn/link/bf13848f7f02f488b2e12e009a8b0df3"</code>
HTTP client libraries are available in all popular languages and runtime environments, including Fetch in JavaScript, Node.js, and Deno, and file_get_contents()
in PHP. JSON responses are machine readable, so they can be parsed and used before outputting HTML or other formats.
Over the years, various data communication standards have been continuously developed. You may have encountered options like CORBA, SOAP, or XML-RPC. Most have strict information rules.
REST was defined in 2000 by Roy Fielding and is much simpler than other technologies. It is not a standard, but a set of suggestions and constraints about RESTful web services. These include:
RESTful Web Service Requests include:
Endpoint URL. An application that implements the RESTful API will define one or more URL endpoints, including domain names, ports, paths, and/or query strings—for example, https://mydomain/user/123?format=json
.
HTTP method. Different HTTP methods can be used for any endpoint, which correspond to the application's creation, read, update, and delete (CRUD) operations:
HTTP method
CRUD
Operation
GET
Read
Return requested data
POST
Create
Create a new record
PUT or PATCH
Update
Update existing records
Delete existing recordsDELETE
Delete
Delete
/user/
/user/
/user/123
/user/123
/user/123
HTTP header. Information such as authentication tokens or cookies can be included in the HTTP request header.
<script> fetch('http://localhost:8888/hello/') .then((response) => { return response.json(); }) .then((json) => { console.log(json); }); </script> Subject data. Data is usually transmitted over the HTTP body in the same way as HTML commits, or by sending a single JSON-encoded data string.Response payload can be any practical content: data, HTML, images, audio files, etc. Data responses are usually JSON-encoded, but can also be used in XML, CSV, simple strings, or any other format. You can allow you to specify the return format in the request - for example, /user/123?format=json
or /user/123?format=xml
.
The appropriate HTTP status code should also be set in the response header. 200 OK is used for successful requests, although 201 Created can also be returned when the record is created. Errors should return appropriate codes such as 400 Bad Request, 404 Not Found, 401 Unauthorized, etc.
Other HTTP headers, including Cache-Control or Expires directives, can be set to specify how long it can be cached before the response is considered "stale".
However, there are no strict rules. Endpoint URLs, HTTP methods, body data, and response types can be implemented according to your preferences. For example, POST, PUT, and PATCH are often used interchangeably, so either will create or update records as needed.
The following Node.js code uses the Express framework to create a RESTful web service. A single /hello/
endpoint responds to an HTTP GET request.
Make sure Node.js is installed and create a new folder named restapi
. Create a new package.json
file in this folder, with the following content:
<code>{ "response_code": 0, "results": [ { "category": "Science: Computers", "type": "multiple", "difficulty": "easy", "question": "What does GHz stand for?", "correct_answer": "Gigahertz", "incorrect_answers": [ "Gigahotz", "Gigahetz", "Gigahatz" ] } ] }</code>
Run npm install
from the command line to get the dependencies and create a index.js
file with the following code:
<code>curl "https://www.php.cn/link/bf13848f7f02f488b2e12e009a8b0df3"</code>
Use npm start
to start the application from the command line and open http://localhost:8888/hello/
in your browser. The following JSON will be displayed in response to a GET request:
<code>{ "name": "restapi", "version": "1.0.0", "description": "REST test", "scripts": { "start": "node ./index.js" }, "dependencies": { "express": "4.18.1" } }</code>
API also allows custom names, so http://localhost:8888/hello/everyone/
Return:
<code class="language-javascript">// simple Express.js RESTful API 'use strict'; // initialize const port = 8888, express = require('express'), app = express(); // /hello/ GET request app.get('/hello/:name?', (req, res) => res.json( { message: `Hello ${req.params.name || 'world'}!` } ) ); // start server app.listen(port, () => console.log(`Server started on port ${port}`); );</code>
Consider the following HTML pages launched with URL http://localhost:8888/
in your browser:
<code class="language-json">{ "message": "Hello world!" }</code>The
fetch call performs the same API request and the browser console will display Object { message: "Hello world!" }
as you expected.
However, suppose your RESTful web service is now online on the http://mydomain.com/hello/
domain name on the web. The page JavaScript fetch()
URL changes accordingly, but opening http://localhost:8888/
in the browser now returns the console error Cross-Origin Request Blocked
.
For security reasons, the browser only allows client XMLHttpRequest and Fetch API calls to be hosted in the same domain as the call page.
Luckily, Cross-origin Resource Sharing (CORS) allows us to circumvent this security restriction. Settings Access-Control-Allow-Origin
HTTP response header tells the browser to allow requests. It can be set to a specific domain name or *
(representing all domain names) (as shown in the quiz API above).
The Web Service API code can be changed to allow access to any client script that runs on any domain name:
<code>{ "response_code": 0, "results": [ { "category": "Science: Computers", "type": "multiple", "difficulty": "easy", "question": "What does GHz stand for?", "correct_answer": "Gigahertz", "incorrect_answers": [ "Gigahotz", "Gigahetz", "Gigahatz" ] } ] }</code>
Alternatively, you can use the Express.js middleware function to attach the header to each endpoint request:
<code>curl "https://www.php.cn/link/bf13848f7f02f488b2e12e009a8b0df3"</code>
Please note that the browser will make two requests to the REST API:
Access-Control-Allow-Origin
HTTP response header and return a virtual empty response to ensure that no duplicate work is done. Access-Control-Allow-Origin
Endpoint consistency
/user/123
/user/id/123
/user/?id=123
Ultimately, it doesn't matter how you format the URL, but the consistency of the API is very important. This can be a challenge for a large code base with many developers.
REST API Version Control
APIs usually adopt version control to avoid compatibility issues. For example,
replaces /2.0/user/123
. Both new and old endpoints can remain active. Unfortunately, this then requires maintaining multiple historical APIs. Older versions can eventually be discarded, but this process requires careful planning. /user/123
Open: any system can get jokes without authorization. This is not feasible for APIs that access private data or allow updates and delete requests.
Client applications that are in 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 setting the initialization option.) Therefore, the API request can be verified to ensure that the user is logged in and has the appropriate permissions. credentials
API authentication will vary depending on the usage environment:
RESTful API provides another way to access and operate applications. Even if it is not a highly-watched hacker target, a poorly behaved client can send thousands of requests per second and crash your server.
Security is not within the scope of this article, but common best practices include:
RESTful API is limited by its implementation. The response may contain more data than you need, or further requests are required to access all data.
Consider a RESTful API that provides access to author and book data. To display data from the top ten bestsellers, the client can:
/book/
details. The response contains a list of books with each author ID. /author/{id}
requests to get detailed information for each author. This is called an N 1 problem; for each result in the parent request, N API requests must be issued.
If this is a common use case, you can change the RESTful API so that each returned book contains full author details such as their name, age, country, biography, and more. It can even provide full details of its other books – although this can significantly increase the response payload!
To avoid unnecessary large responses, the API can be adjusted to make the author details optional—for example, ?author_details=full
. The number of options that API authors need to deal with can be dazzling.
REST puzzle led Facebook to create GraphQL, a web service query language. Think of it as a web service SQL: a single request defines the data you need and how you want to return it.
GraphQL solves some of the challenges brought by the RESTful API, although it introduces others. For example, caching GraphQL responses becomes difficult.
Your client is unlikely to have a similar problem with Facebook, so it may be worth considering GraphQL after the RESTful API exceeds its actual limit.
There are many tools in all languages that can help with RESTful API development. Notable options include:
There are also many public REST APIs for jokes, currency conversions, geocodes, government data, and every topic you can think of. Many are free, although some require you to register an API key or use other authentication methods. Category list includes:
Before implementing your own web service, try using some RESTful API in your own project. Or, you can follow Facebook, GitHub, Google, and many other giants to build your own RESTful API.
REST API (Detailed State Transfer Application Programming Interface) is a set of rules and conventions that allow software applications to communicate and interact with each other over the Internet using the principles of REST architectural style.
What are the main characteristics of the REST API? The REST API is characterized by the use of resources, stateless client-server communication, standard HTTP methods (GET, POST, PUT, DELETE), and unified interfaces that usually involve accessing and manipulating resources using URLs.
REST API (Detailed State Transport Application Programming Interface) is named after the architectural style it follows, called REST (Detailed State Transport). The term "REST" was proposed by Roy Fielding in his 2000 PhD thesis, in which he outlined the principles and constraints of this architectural style. The name "REST" represents the concept of transferring a representation of resource status from the server to the client.
What are the benefits of using REST API? The REST API provides many benefits, including simplicity, scalability, ease of integration, platform independence, and separation of concerns. They also leverage existing HTTP infrastructure, which is ideal for web and mobile applications.
Is the REST API limited to web applications? No, the REST API is not limited to web applications. They can be used to facilitate communication between various types of software applications, including web applications, mobile applications, and even server-to-server communication.
REST API consists of four main components, commonly known as the "four pillars" of REST. These components help define the structure, behavior, and interaction of APIs in the REST architectural style. The four components are resources, HTTP methods (verbs), representations and general interfaces.
What tools or libraries can I use to build the REST API? There are many tools and frameworks for building REST APIs, including Express.js (Node.js), Flask (Python), Ruby on Rails (Ruby), Django (Python), Spring Boot (Java), and more.
This response maintains the original image formatting and placement. The text has been rewriteten to provide a paraphrased version of the original article while preserve the core meaning and flow.
The above is the detailed content of What Is a REST API?. For more information, please follow other related articles on the PHP Chinese website!