Home >Web Front-end >JS Tutorial >Beginners Guide to Structuring APIs in Node.js: Clean & Scalable
This guide will help you learn how to build a clearly structured Node.js REST API. Includes folder organization, best practices, and tips for building scalable, maintainable APIs.
APIs are the cornerstone of modern web applications, connecting front-ends and servers. However, a poorly structured API can lead to code that is cluttered and difficult to maintain. For those new to Node.js, understanding how to organize projects from the beginning is crucial to building scalable, clean applications.
This guide will walk you through the basic architecture of the Node.js REST API. We'll cover the essentials, best practices, and provide a practical folder structure you can apply to your projects. Read more about folder structure
When starting out, many developers put everything into a single file. While this works for small projects, as the code base grows it can become a nightmare. Good API structure helps:
Before we dive into the folder structure, let’s understand some basic principles:
This is a simple structure for small projects, perfect for absolute beginners:
<code>my-api/ ├── server.js # 入口点 ├── package.json # 项目元数据和依赖项 ├── .env # 环境变量 ├── /routes # API 路由定义 │ └── userRoutes.js # 示例:用户相关的路由 ├── /controllers # 请求处理逻辑 │ └── userController.js ├── /models # 数据库模型或模式 │ └── userModel.js └── /config # 配置文件 └── db.js # 数据库连接设置</code>
Entry point to the application:
<code>my-api/ ├── server.js # 入口点 ├── package.json # 项目元数据和依赖项 ├── .env # 环境变量 ├── /routes # API 路由定义 │ └── userRoutes.js # 示例:用户相关的路由 ├── /controllers # 请求处理逻辑 │ └── userController.js ├── /models # 数据库模型或模式 │ └── userModel.js └── /config # 配置文件 └── db.js # 数据库连接设置</code>
Use .env files to store sensitive data:
<code class="language-javascript">require('dotenv').config(); const express = require('express'); const userRoutes = require('./routes/userRoutes'); const connectDB = require('./config/db'); const app = express(); const PORT = process.env.PORT || 5000; // 中间件 app.use(express.json()); // 数据库连接 connectDB(); // 路由 app.use('/api/users', userRoutes); app.listen(PORT, () => console.log(`服务器运行在端口 ${PORT}`));</code>
Install dotenv to load these variables into process.env:
<code>PORT=5000 MONGO_URI=mongodb+srv://username:password@cluster.mongodb.net/myDatabase</code>
Routes handle HTTP requests and direct them to the appropriate controller.
/routes/userRoutes.js:
<code class="language-bash">npm install dotenv</code>
Controller contains the logic to handle the request.
/controllers/userController.js:
<code class="language-javascript">const express = require('express'); const { getAllUsers, createUser } = require('../controllers/userController'); const router = express.Router(); // 获取所有用户 router.get('/', getAllUsers); // POST 创建新用户 router.post('/', createUser); module.exports = router;</code>
Models define the structure of database documents. In this example, we use MongoDB and Mongoose.
/models/userModel.js:
<code class="language-javascript">const User = require('../models/userModel'); // 获取所有用户 const getAllUsers = async (req, res) => { try { const users = await User.find(); res.status(200).json(users); } catch (error) { res.status(500).json({ message: error.message }); } }; // POST 创建新用户 const createUser = async (req, res) => { try { const { name, email } = req.body; const newUser = await User.create({ name, email }); res.status(201).json(newUser); } catch (error) { res.status(500).json({ message: error.message }); } }; module.exports = { getAllUsers, createUser };</code>
The configuration folder contains files that connect to external resources such as databases.
/config/db.js:
<code class="language-javascript">const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true } }); module.exports = mongoose.model('User', userSchema);</code>
Here are some practice ideas:
Starting with a clean, structured API is the foundation of a maintainable project. By separating concerns and organizing your code logically, you'll prepare your application for growth.
Remember, this is just a starting point! As your experience grows, you can adapt and expand this structure to accommodate larger, more complex projects.
Do you have any specific challenges or ideas you’d like us to explore in a future article? Let us know in the comments!
Thank you for taking the time to read this! I hope it helps you simplify the topic and provides valuable insights. If you found it useful, follow me for more digestible content on web development and other technical topics.
Your feedback is important! Please share your thoughts in the comments section - whether it's a suggestion, a question, or something you'd like me to improve. Feel free to use emojis to let me know how this post made you feel. ?
I’d love to connect with you! Let’s continue to exchange ideas, learn from each other, and grow together.
Follow me on social media and let’s stay connected:
Looking forward to hearing from you and growing this community of curious people! ?
The above is the detailed content of Beginners Guide to Structuring APIs in Node.js: Clean & Scalable. For more information, please follow other related articles on the PHP Chinese website!