APIGit
2024-11-15
Creating mock APIs is a critical aspect of software development, whether for testing purposes or rapid prototyping. APIGIT MockServer offers a streamlined solution by wrapping around Express.js, providing a simplified environment to define mock server behavior without the need to manually set up and configure an Express application.
APIGIT MockServer operates within a Node.js sandbox, leveraging an Express.js app to simplify the creation of mock APIs. It enables rapid development and handling of various HTTP requests through straightforward definitions. In this introduction, we’ll explore MockServer’s features, highlight its capabilities, and demonstrate how you can quickly get started with practical examples.
lodash
, moment
, faker
, and more are pre-installed, streamlining the creation of dynamic mock responses.MockServer works by allowing you to define API routes using mock
object. The mock
object is a global instance that wraps an Express.js app and supports defining routes through the mock.define()
function. It provides the flexibility of Express.js, making it simple to create and manage APIs for testing and development purposes.
Here's an overview of how MockServer simplifies creating APIs:
mock.define()
to define routes and request handlers.req
and res
to handle HTTP requests and responses.The following example shows how easy it is to create routes using MockServer:
const { routeCallBackFunc } = require('./util.js');
// Define routes using mock.define(path, method, handler)
mock.define("/user/:name", "POST", function(req, res) {
// Handle the request
res.status(404).send("User not found");
});
mock.define("/user/:name", "DELETE", function(req, res) {
res.status(200).send("User deleted successfully");
});
// Use request handlers from separate files
mock.define("/user/:name", "POST", routeCallBackFunc);
This example demonstrates how to use mock.define()
to create POST and DELETE routes. The routes are defined similarly to standard Express.js applications, ensuring a familiar API structure.
Just like in Express.js, you can use middleware to process requests before they reach the final route handler:
function mw1(req, res, next) {
console.log("Middleware 1 executed");
next();
}
function mw2(req, res, next) {
console.log("Middleware 2 executed");
next();
}
mock.use(mw1);
mock.use(mw2);
// Define middleware for a specific path
mock.use('/specific-path', (req, res, next) => {
console.log('Middleware for /specific-path executed');
next();
});
The mock.use()
function can be used to define middleware for all routes or specific paths, just like in an Express app.
MockServer provides a simple way to interact with requests and responses using standard Express.js conventions. Below are some examples of common tasks:
mock.define('/repository/:user/:repo', 'GET', (req, res) => {
const { user, repo } = req.params;
res.json({
message: 'Repository Details',
user: user,
repo: repo
});
});
mock.define('/search', 'GET', (req, res) => {
const { keyword, page, limit } = req.query;
res.json({
message: 'Search Parameters Received',
keyword: keyword || 'none',
page: page ? parseInt(page, 10) : 1,
limit: limit ? parseInt(limit, 10) : 10
});
});
mock.define('/not-found', 'GET', (req, res) => {
res.status(404).json({
message: 'Resource not found',
code: 404
});
});
mock.define('/single-header', 'GET', (req, res) => {
res.set('Content-Type', 'application/json');
res.set('X-Custom-Header', ['value1', 'value2']);
res.json({ message: 'Headers set successfully!' });
});
MockServer comes with popular JavaScript libraries pre-installed, so you can use them directly in your mock definitions:
const _ = require('lodash');
const moment = require('moment');
const { faker } = require('@faker-js/faker');
mock.define('/test-libs', 'GET', (req, res) => {
const randomUser = {
id: faker.datatype.uuid(),
name: faker.name.findName(),
email: faker.internet.email()
};
res.json({
currentDate: moment().format(),
activeUsers: _.filter([{ active: true }, { active: false }], { active: true }),
randomUser: randomUser
});
});
These libraries help you create rich, dynamic responses easily without the need for additional installations. If you need a library that is not listed, please reach out to APIGIT, and we will evaluate and add it quickly. The supported libraries include:
MockServer provides a state
object, which allows you to store and retrieve data between requests, making it easy to simulate persistent state:
// Create a stateful list of users
state.users = state.users || [];
mock.define('/users', 'POST', (req, res) => {
if (!req.body.username) {
return res.status(400).json({ status: "error", details: "Missing username" });
}
state.users.push(req.body);
return res.status(200).json({ status: "ok" });
});
To maintain cleaner and more organized code, MockServer supports splitting mock scripts into multiple files in a modular way, similar to everyday development practices. Typically, you would have a main.js
file that defines all the routes, which then requires handler definitions from separate files. This allows you to create reusable, well-structured modules for route handlers, keeping your codebase maintainable.
For example:
module.exports
.// main.js
// Require handler modules at the top
const { userPostHandler, userDeleteHandler } = require('./handlers/userHandlers');
// Define routes
mock.define('/user/:name', 'POST', userPostHandler);
mock.define('/user/:name', 'DELETE', userDeleteHandler);
module.exports
to export them together.// handlers/userHandlers.js
function userPostHandler(req, res) {
res.status(404).send('User not found');
}
function userDeleteHandler(req, res) {
res.status(200).send('User deleted successfully');
}
module.exports = {
userPostHandler,
userDeleteHandler
};
This modular approach helps you organize routes logically and enables reusability across different mock projects.
MockServer simplifies the process of setting up mock APIs by leveraging the power of Express.js in a sandboxed environment. With built-in libraries, easy route definitions, middleware support, and stateful data management, it’s a convenient solution for developers looking to create mock APIs quickly and efficiently.
Whether you’re a beginner or an experienced developer, MockServer provides the tools you need to simulate API behavior without the overhead of setting up a full Express server. Give it a try, and make your API testing and prototyping smoother and more productive.
© 2024 APIGit Inc.