0Pricing
Node.js Backend Development Bootcamp · レッスン

RESTful APIエンドポイントを設計する

RESTの基本原則を学び、さまざまなリソース向けに明確で効率的なAPIエンドポイントを設計します。

「RESTful APIエンドポイントを設計する」はCoddyKit上の無料Node.js Backend Development Bootcampレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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エンドポイントを設計する」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Node.js Backend Development Bootcampコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Node.js Backend Development Bootcampコースには全4レッスンが含まれています。

「RESTful APIエンドポイントを設計する」で何を学びますか?

RESTの基本原則を学び、さまざまなリソース向けに明確で効率的なAPIエンドポイントを設計します。 ブラウザで直接実行するハンズオンコードでNode.js Backend Development Bootcampを演習し、24時間対応の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. リクエストデータの処理:Body、Query、Params
← Node.js Backend Development Bootcampに戻る