Guide to Rolling Your Own Custom API Service
Creating your own API system can be a valuable skill, whether you're building a web application or connecting various services together. In this guide, we'll walk through the steps to create a simple RESTful API using JavaScript, specifically with NodeJS and Express. This tutorial is aimed at college students with basic knowledge of JavaScript and web development.
Prerequisites
Before we start, make sure you have the following installed:
Basic understanding of JavaScript, HTTP protocols, and some familiarity with databases (we'll use MongoDB) will be helpful.
Step 1: Setting Up the Project
Initialize the Project: Open your terminal and create a new directory for your project. Navigate into it and run the following commands:
mkdir my-api
cd my-api
npm init -y
Install Dependencies: Install Express (for handling routes) and Mongoose (for MongoDB interactions):
npm install express mongoose
Create the Project Structure: Organize your project directory:
my-api/
├── node_modules/
├── src/
│ ├── models/
│ ├── routes/
│ └── app.js
├── package.json
└── .gitignore
Setting Up the Server
Create the app.js file: In the src directory, create an app.js file. This will be the entry point of your application.
const express = require('express');
const mongoose = require('mongoose');
const app = express();
// Middleware to parse JSON
app.use(express.json());
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Basic route
app.get('/', (req, res) => {
res.send('Hello, World!');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Run the Server: In your terminal, run the server:
node src/app.js
Open a browser or a tool like Postman, and go to http://localhost:3000. You should see "Hello, World!".
Define a Data Model
Create a Model: Let's create a simple model for a user. In the models directory, create a user.js file:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
});
const User = mongoose.model('User', userSchema);
module.exports = User;
Create API Routes
Create Routes: In the routes directory, create a user.js file:
const express = require('express');
const User = require('../models/user');
const router = express.Router();
// Create a new user
router.post('/users', async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.status(201).send(user);
} catch (error) {
res.status(400).send(error);
}
});
// Get all users
router.get('/users', async (req, res) => {
try {
const users = await User.find();
res.send(users);
} catch (error) {
res.status(500).send(error);
}
});
// Get a user by ID
router.get('/users/:id', async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).send();
}
res.send(user);
} catch (error) {
res.status(500).send(error);
}
});
module.exports = router;
Use the Routes in app.js: Update app.js to include the user routes:
const userRouter = require('./routes/user');
app.use(userRouter);
Test Your API
Run the Server: Ensure your server is running:
node src/app.js
Use Postman or curl: You can test your API using Postman or curl.
Create a new user:
curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"name": "John Doe", "email": "[email protected]", "password": "123456"}'
Get all Users:
curl http://localhost:3000/users
Get User by ID:
curl http://localhost:3000/users/<user_id>
The Conclusion
You've now created a simple RESTful API with NodeJS, Express, and MongoDB. This API can handle creating, retrieving, and managing all users. From here, you can expand it to include more features and models, implement authentication, and enhance error handling.