RESTful API Tutorial

In modern web development, RESTful APIs have become the standard way for applications to communicate with each other.

REST (Representational State Transfer) is a software architectural style proposed by Dr. Roy Fielding in 2000.

REST defines a set of constraints and principles for creating scalable, loosely coupled web services.

A RESTful API is an API designed following the REST architectural style. It leverages the characteristics of the HTTP protocol to locate resources via URLs and uses HTTP methods (GET, POST, etc.) to describe operations, enabling interaction between client and server.


Who should read this tutorial?

Whether you are a front-end developer who needs to interact with back-end APIs, or a back-end developer who needs to design API interfaces, mastering RESTful APIs is an essential skill.


Features of RESTful API?

Key Features:

  • Stateless: Each request contains all the information needed for processing
  • Uniform Interface: Uses standard HTTP methods for operations
  • Resource-Oriented: Everything is abstracted as resources
  • Cacheable: Responses should explicitly indicate whether they are cacheable

Core Principles of RESTful API

1. Resources and URIs

In REST, everything is abstracted as a resource, and each resource has a unique identifier (URI).

URI Design Guidelines:

  • Use nouns rather than verbs to represent resources
  • Use plural forms for collections
  • Use lowercase letters and hyphens (-)
  • Avoid file extensions

Example:

/users          # 用户集合
/users/123      # ID为123的用户
/users/123/orders  # 用户123的订单集合

2. Use of HTTP Methods

RESTful APIs make full use of HTTP method semantics:

HTTP Method Description Idempotency Safety
GET Retrieve resource Yes Yes
POST Create resource no no
PUT Completely update resource Yes no
PATCH Partially update resource no no
DELETE Delete resource Yes no

3. Statelessness

Each request must contain all the information needed for processing, and the server does not store client state. This makes the API easy to scale and load balance.

4. Representation Forms

Resources can have multiple representation forms (e.g., JSON, XML), and the client specifies the desired format via the Accept header.

Other Extensions