0Pricing
Node.js Backend Development Bootcamp · 课时

设计 RESTful API 端点

学习 REST 的核心原则,为各种资源设计简洁高效的 API 端点。

设计 RESTful API 端点 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Intro to RESTful APIs

Welcome! In this lesson, we'll dive into designing clean and efficient API endpoints following REST principles. Understanding REST is crucial for building scalable web services.

REST stands for Representational State Transfer. It's an architectural style for networked applications, emphasizing a stateless client-server communication.

Resources: The Nouns of REST

At the heart of REST are resources. Think of resources as any information or data that your API can provide or manipulate. They are the 'things' your API manages.

  • A resource is identified by a unique URL (Uniform Resource Locator).
  • They are typically represented by nouns, like users, products, or orders.
  • Ideally, use plural nouns for collections of resources.

Actions with HTTP Methods

While resources are nouns, the actions you perform on them are indicated by standard HTTP methods (also called verbs). These methods correspond directly to common data operations:

  • GET: Retrieve data (Read)
  • POST: Create new data (Create)
  • PUT: Replace existing data (Update all)
  • PATCH: Partially update existing data (Update partial)
  • DELETE: Remove data (Delete)

Structuring Your API Endpoints

A well-designed endpoint URL should be intuitive and predictable. It typically follows a pattern:

/api/<version>/<resource_name>

Using a version (like v1) is good practice for future API changes. Always use plural nouns for resource names.

  • Good: /api/v1/users
  • Bad: /api/v1/getUsers

Collection and Item URLs

REST APIs distinguish between a collection of resources and a single resource within that collection:

  • Collection URL: Refers to a group of resources. E.g., /users (all users).
  • Item URL: Refers to a specific resource. E.g., /users/123 (user with ID 123).

The ID (:id in Express) is a unique identifier for that specific resource.

Speaking with Status Codes

HTTP status codes are crucial for your API to communicate the outcome of a request to the client. They tell the client if the request was successful, if there was an error, and why.

  • 200 OK: Request successful.
  • 201 Created: Resource successfully created.
  • 204 No Content: Request successful, but no content to return (e.g., DELETE).
  • 400 Bad Request: Client sent invalid data.
  • 404 Not Found: Resource not found.
  • 500 Internal Server Error: Server-side error.

User API Endpoint Design

Let's design endpoints for a User resource. Notice how HTTP methods and URLs combine to describe actions.

Try running this example to see the routes in action:

const express = require('express');
const app = express();
const port = 3000;

// Get all users
app.get('/api/v1/users', (req, res) => {
  res.status(200).send('GET /api/v1/users: Retrieve all users');
});

// Create a new user
app.post('/api/v1/users', (req, res) => {
  res.status(201).send('POST /api/v1/users: Create a new user');
});

// Get a specific user by ID
app.get('/api/v1/users/:id', (req, res) => {
  res.status(200).send(`GET /api/v1/users/${req.params.id}: Retrieve user ${req.params.id}`);
});

// Update a specific user by ID
app.put('/api/v1/users/:id', (req, res) => {
  res.status(200).send(`PUT /api/v1/users/${req.params.id}: Update user ${req.params.id}`);
});

// Delete a specific user by ID
app.delete('/api/v1/users/:id', (req, res) => {
  res.status(204).send(`DELETE /api/v1/users/${req.params.id}: Delete user ${req.params.id}`);
});

app.listen(port, () => {
  console.log(`User API running on http://localhost:${port}`);
});

Product API Endpoint Design

Here's another example for a Product resource. The patterns remain consistent, making your API easy to understand and use for developers.

Run this code to see a product-focused API:

const express = require('express');
const app = express();
const port = 3001; // Using a different port

// Get all products
app.get('/api/v1/products', (req, res) => {
  res.status(200).send('GET /api/v1/products: Retrieve all products');
});

// Create a new product
app.post('/api/v1/products', (req, res) => {
  res.status(201).send('POST /api/v1/products: Create a new product');
});

// Get a specific product by ID
app.get('/api/v1/products/:id', (req, res) => {
  res.status(200).send(`GET /api/v1/products/${req.params.id}: Retrieve product ${req.params.id}`);
});

// Delete a specific product by ID
app.delete('/api/v1/products/:id', (req, res) => {
  res.status(204).send(`DELETE /api/v1/products/${req.params.id}: Delete product ${req.params.id}`);
});

app.listen(port, () => {
  console.log(`Product API running on http://localhost:${port}`);
});

Clean URL Best Practices

To ensure your API is user-friendly and maintainable, follow these best practices:

  • Use Plural Nouns: For collections (e.g., /products, not /product).
  • Avoid Verbs in URLs: Let HTTP methods define actions (e.g., POST /users, not /createUser).
  • Use Hyphens: For readability in multi-word resource names (e.g., /order-items).
  • Keep URLs Simple: Avoid deep nesting; query parameters can handle filtering/sorting.

Test Your REST Knowledge

Which of the following endpoint designs correctly follows RESTful principles for creating a new product and retrieving a specific product?

Recap: Designing RESTful Endpoints

Great job! You've learned the fundamentals of designing RESTful API endpoints. Remember these key takeaways:

  • Resources are the nouns, identified by URLs.
  • HTTP Methods (GET, POST, PUT, DELETE) define actions.
  • Use plural nouns for collections and specific IDs for items.
  • Communicate outcomes using appropriate HTTP Status Codes.
  • Strive for clean, predictable URLs for a user-friendly API.

This foundation will help you build robust and intuitive APIs!

常见问题解答

「设计 RESTful API 端点」课时是免费的吗?

是的 — 「设计 RESTful API 端点」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 4 节课。

「设计 RESTful API 端点」这节课中我会学到什么?

学习 REST 的核心原则,为各种资源设计简洁高效的 API 端点。 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Node.js Backend Development Bootcamp 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「设计 RESTful API 端点」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?

能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Express.js 框架基础
  2. Express 中的路由与中间件
  3. 设计 RESTful API 端点
  4. 处理请求数据:正文、查询与参数
← 返回 Node.js Backend Development Bootcamp