Home > Web Front-end > JS Tutorial > What Is a REST API?

What Is a REST API?

尊渡假赌尊渡假赌尊渡假赌
Release: 2025-02-09 12:37:09
Original
403 people have browsed it

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.

Key Points

  1. REST API utilizes HTTP to facilitate communication between computer systems, enabling various services (such as vehicle registration agencies, credit agencies and banks) to share data in real time, thereby providing services such as car insurance quotations.
  2. REST API follows a set of suggestions for creating network services, including client-server architecture, statelessness, caching and hierarchical systems, making it a simple and effective way to interact with network systems.
  3. The implementation and use of REST APIs need to consider endpoint consistency, version control, authentication, security, and handling multiple requests or unnecessary data. Tools such as Swagger and Postman support development and testing.

REST API Example

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>
Copy after login
Copy after login
Copy after login

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>
Copy after login
Copy after login
Copy after login

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.

REST API and other technologies

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:

  • Client-Server: System A issues an HTTP request to the URL hosted by System B, and System B returns a response. This is the same way the browser works. The browser requests a specific URL. Requests are routed to the web server, which usually returns HTML pages. The page may contain references to images, stylesheets, and JavaScript, which will result in further requests and responses.
  • Stateless: REST is stateless: the client request should contain all the information required for the response. In other words, two or more HTTP requests should be made in any order and the same response will be received (...unless the API is designed to return a random response, as in the quiz example above).
  • Cachable: The response should be defined as cacheable or non-cacheable. Caching improves performance because there is no need to regenerate responses for the same URL. Private data for a specific user at a specific time is usually not cached.
  • Hydration: Requesting clients does not need to know whether they are communicating with the actual server, the proxy, or any other intermediary.

Create RESTful Web Service

RESTful Web Service Requests include:

  1. 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.

  2. 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 Delete Delete Delete existing records

      Example:
    • /user/
    • GET request for
    • returns to the list of registered users on the system/user/
    • Create a user with ID 123 using the principal data for the POST request of
    • (see 4. below). The response returns the ID. /user/123
    • Update user 123 using subject data for PUT requests for
    • (see 4. below) /user/123
    • Return the details of user 123 when the GET request for
    • /user/123
    • Delete user 123
    for DELETE request for
  3. 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.

What Is a REST API?

REST API Response

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.

REST API "Hello World" example

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>
Copy after login
Copy after login
Copy after login

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>
Copy after login
Copy after login
Copy after login

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>
Copy after login

API also allows custom names, so http://localhost:8888/hello/everyone/ Return:

// 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}`);
);
Copy after login

Client REST request and CORS

Consider the following HTML pages launched with URL http://localhost:8888/ in your browser:

{
  "message": "Hello world!"
}
Copy after login
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>
Copy after login
Copy after login
Copy after login

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>
Copy after login
Copy after login
Copy after login

Please note that the browser will make two requests to the REST API:

  1. An HTTP OPTIONS request pointing to the same URL to determine if the HTTP response header is validAccess-Control-Allow-Origin
  2. Actual REST call
When your server receives the OPTIONS request method, it can set the

HTTP response header and return a virtual empty response to ensure that no duplicate work is done. Access-Control-Allow-Origin

REST API Challenge

REST's success is largely due to its simplicity. Developers can implement RESTful APIs according to their preferences, but this can lead to further challenges. For an in-depth look at our 13 best practices on building a RESTful API.

Endpoint consistency

Consider the following endpoints:

  • /user/123
  • /user/id/123
  • /user/?id=123
All of these are valid options for getting user 123 data. The number of combinations increases further as you perform more complex operations. For example, returning ten last names that start with "A" and work in companyX, sort in reverse order by birth date, starting with record 51.

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

API changes are inevitable, but endpoint URLs should never fail, otherwise they will break the application that uses them.

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

REST API Authentication

The quiz API shown above is

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

A third-party application must use other authentication methods. Common authentication options include:

  • HTTP Basic Authentication. Pass the HTTP Authorization header containing the base64 encoding in the request header.
  • API key. Grant third-party applications permission to use the API by issuing keys that may have specific permissions or are limited to a specific domain only. The key is passed in every request in the HTTP header or query string.
  • OAuth. Before any request is made, the token must be obtained by sending the client ID and possible client key to the OAuth server. The OAuth token will then be sent with each API request until it expires.
  • JSON Web Token (JWT). Digitally signed authentication tokens are securely transmitted in request and response headers. JWT allows the server to encode access permissions, so there is no need to call a database or other authorized system.

API authentication will vary depending on the usage environment:

  • In some cases, a third-party application will be considered any other logged-in user with specific permissions. For example, the map API can return a route between two points to the calling application. It must confirm that the application is a valid client, but does not need to check the user credentials.
  • In other cases, third-party applications are requesting private data belonging to a single user, such as email content. The REST API must identify the user and its permissions, but it may not care which application is calling the API.

REST API Security

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:

  • Using HTTPS
  • Use powerful authentication methods
  • Use CORS to limit client calls to specific domains
  • Provides minimal functionality—that is, don't create unwanted DELETE options
  • Verify all endpoint URLs and principal data
  • Avoid exposing API tokens in client JavaScript
  • Block access from unknown domains or IP addresses
  • Stop unexpected large payloads
  • Consider rate limits—that is, requests using the same API token or IP address are limited to N per minute
  • Respond with appropriate HTTP status code and cache header
  • Record requests and investigate failures

Multiple requests and unnecessary data

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:

  • Request the top 10 by sales quantity (best sellers preferred) /book/ details. The response contains a list of books with each author ID.
  • Send up to 10 /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.

Can GraphQL solve the problem of REST API?

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.

REST API Links and Development Tools

There are many tools in all languages ​​that can help with RESTful API development. Notable options include:

  • Swagger: Various tools that help design, record, simulate, test and monitor REST APIs
  • Postman: RESTful API Test Application
  • Hoppscotch: Postman's open source, web-based alternative

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:

  • Any API
  • API list
  • Public APIs
  • Google APIs Explorer

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.

Frequently Asked Questions about REST API

What is REST 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.

Why is it called REST API?

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.

What are the four components of the REST API?

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template