Building REST API is a basic skill for back -end development. This article will guide you how to use Node.js
and Express.js Create a simple REST API. This guide will provide a clear, step -by -step process to build your first API.
Note:
This tutorial does not integrate any database, but uses memory array.
What is REST API?
REST API (Similar state transmission application programming interface) is a set of rules and agreement for building and interactive web services. It uses the HTTP method (such as Get, Post, PUT, and Delete) to perform operations, and usually returns data in JSON format.
Prerequisite conditions
Before starting, make sure you have installed the following content:
node.js
: Download and install it from nodejs.org.
code editor : Use any editor you like, such as Visual Studio Code, Sublime Text or Atom. -
Postman (optional): tools used to test your API end point. Download it from postman.com.
-
Step 1: Set your project
- 1. Create the project directory
Open your terminal and create a new directory for your project:
2. Initialize the node.js project
Run the following commands to create a package.json file:
-y logo will automatically fill in your project default value.
<code>mkdir my-rest-api
cd my-rest-api</code>
Step 2: Install the required bag
1. Install Express.js
<code>npm init -y</code>
Express.js is a lightweight web framework of Node.js. Use the following command to install it:
2. Install nodemon (optional)
Whenever you change the code, Nodemon will automatically restart your server. Install it as a development dependencies:
Step 3: Create the basic server <code>npm install express</code>
1. Create the index.js file
In your project directory, create a file called index.js:
<code>npm install --save-dev nodemon</code>
2. Set the server
Open Index.js and add the following code:
3. Run the server
<code>touch index.js</code>
Use the following command to start the server:
If you install nodemon, please use:
<code class="language-javascript">// 导入 express 模块
const express = require('express');
// 创建 express 实例
const app = express();
// 定义端口号
const PORT = 3000;
// 解析 JSON 主体的中间件
app.use(express.json());
// 定义一个简单的路由
app.get('/', (req, res) => {
res.send('Hello, World!');
});
// 启动服务器并在指定的端口上监听
app.listen(PORT, () => {
console.log(`服务器正在运行在 http://localhost:${PORT}`);
});</code>
In the browser, visit
https://www.php.cn/link/8cad09283d1d6c5FB08DAEC8A576A72D , World! ".
<code>node index.js</code>
Step 4: Add CRUD operation
<code>npx nodemon index.js</code>
Let's create a simple REST API to manage the list of projects. We will use memory array to store data.
1. Create memory array
Add this trip after :
<code>mkdir my-rest-api
cd my-rest-api</code>
2. Define CRUD routing
get /items : Get all the projects
<code>npm init -y</code>
get /items /: ID : Obtain a single item by ID
Post /items <code>npm install express</code>
: Create a new project
put /items /: ID
: Update the project through the ID <code>npm install --save-dev nodemon</code>
Delete /items /: ID : Delete the project through ID
<code>touch index.js</code>
Step 5: Test your API
Use POSTMAN <code class="language-javascript">// 导入 express 模块
const express = require('express');
// 创建 express 实例
const app = express();
// 定义端口号
const PORT = 3000;
// 解析 JSON 主体的中间件
app.use(express.json());
// 定义一个简单的路由
app.get('/', (req, res) => {
res.send('Hello, World!');
});
// 启动服务器并在指定的端口上监听
app.listen(PORT, () => {
console.log(`服务器正在运行在 http://localhost:${PORT}`);
});</code>
or
CURL Test your API endpoint:
get https://www.php.cn/link/8A701B176CC140888936DAD15D046A -retrieve all projects.
Post - https://www.php.cn/link/8a701b176cc140888936dad15d046a - Create a new project. Send a JSON main body similar to .
get
- https://www.php.cn/link/8A701B176CC140888936DAD15D046A/1 —— retrieve a single item through ID.
Put
{"name": "项目 1"}
https://www.php.cn/link/8A701B176CC140888936DAD15D046A/1 Update project. Send a JSON main body similar to . -
DELETE https://www.php.cn/link/8A701B176CC140888936DAD15D046A/1 - Delete items through ID.
-
Step 6: Add error treatment (optional)
To deal with errors globally, add this middleware at the end of the index.js file:
{"name": "已更新的项目 1"}
-
Step 7: Organize your code (optional)
With the development of the project, you can organize the code into a separate file and folder. For example:
Routes/
: Define the route.
Controller/: Processing business logic.
<code>node index.js</code>
Models/
: Define the data structure.
The final code
This is the complete index.js file: -
Conclusion
- Congratulations! You have built a simple REST API with Node.js and Express.js. This is just the beginning -you can also do more things, such as integrating databases, adding identity verification or deploying your API to the cloud.
Continue to try, I wish you a happy coding!
The above is the detailed content of How to Create a REST API with Node.js and Express.js (for Beginners). For more information, please follow other related articles on the PHP Chinese website!
Statement: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