Mock API for Frontend Development is essential in the age of modern web development. When it comes to modern web development, the front end and back end are often created separately. In addition, both of them are developed by different teams. This issue can lead to a blocked factor where one team is dependent on another team.
For example, frontend developers are always stuck when a backend team is working because they require those APIs in order to display data and complete their features. This interdependence might slow down the process of overall software development.
Dependency-free Mock APIs can help you to come out from block factors. Frontend developers can eliminate the dependency and waiting time in modern web development through dependency-free Mock APIs. Today, we will teach you the way to create a dependency-free Mock API for front-end development. However, you can also develop this API with the help of faux api.
Mock API solutions
There are numerous Mock API solutions that you can use to develop a dependency-free Mock API for Frontend Development projects. However, choosing the best Mock API solution is essential to create a successful API. We have found the top three Mock API solutions that you can use to develop a dependency-free Mock API:
1. JSON-Server
Json-server is an excellent library that provides you with everything you need to begin experimenting with a new front-end project. If you are an expert frontend developer, you may find this tool simple but it is a powerful tool that lets you create Mock API for the purpose of development and testing purpose. You can also develop a full fake REST API without any coding in a just few seconds.
2. Connect API Mocker
Connect API Mocker is a connect.js middleware that fakes Rest API server with a file system. When you attempt to test the application without the real REST API, it would be helpful. You can use this with a wide range of servers, including Connect, Lite-Server, Browser-Sync, and more.
This solution lets you create a mock using your file system. Rather than creating many routes within Express, you are allowed to structure your mock API with the utilization of directories and files. It was somewhat difficult to develop Mock API for front-end developers, but Connect API Mocker has made it easier to create and maintain them.
3. Creating a simple Express Server
You can also consider spinning up a simple Node or Express server. Remember, you have to develop a “replica” for each route in the Express server, which would focus on mimicking the data or logic of the real backend endpoint.
This option needs the most work to get up along with running, but it gives you the most control over the Mock API for Frontend Development. Indeed, you have read it right! You can get control over the logic within the endpoint and help in creating the endpoint instantly.
Take a look at the steps of how you can develop a mock an API using an app router with the simple express server.
What are the steps to develop a Dependency-Free Mock API for Frontend Development using Javascript?
When you decide to create an API dependency-free Mock API, you should get ready to perform a few steps with minimal coding. We have listed the necessary steps you must follow to develop this API for Frontend Development in js below:
1. Create the mock data file
Initially, you should create the mock data file named Mockdata.js in order to store your mock data. The following is the code you need to create a mock data file:
const mockDataMain = {
usersInfo: [
{ id: 1, name: "Tabitha H. Perez", email: "john@example.com" },
{ id: 2, name: "John Jane", email: "jane@example.com" },
],
articles: [
{ id: 1, title: "First Article", content: "This is the first article." },
{ id: 2, title: "Second Article", content: "This is the second article." },
],
};
export default mockDataMain;
2. Create the mock API server
After creating the mock data file, you should move forward to develop another file named mockApiServerMain.js in order to simulate the API server. We have provided the code you need to create this below:
import mockDataMain from './ mockDataJSON.js';
const apiEndpoints = {
"/api/usersInfo": mockDataMain.usersInfo,
"/api/articles": mockDataMain.articles,
};
function mockApi(endpoint, method = 'GET', payload = null) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (method === 'POST' && endpoint === '/api/usersInfo') {
const newUser = { id: mockDataMain.usersInfo.length + 1, ...payload };
mockDataMain.usersInfo.push(newUser);
resolve({ status: 201, data: newUser });
} else if(method === 'DELETE' && endpoint) {
apiEndpoints[endpoint].map((item, index)=>{
if(item.id == payload) {
apiEndpoints[endpoint].splice(index, 1);
resolve({ status: 200, data: apiEndpoints[endpoint] });
} else {
resolve({ status: 404, data: 'Endpoint not found' });
}
})
}else if (apiEndpoints[endpoint]) {
resolve({ status: 200, data: apiEndpoints[endpoint] });
} else {
reject({ status: 404, message: 'Endpoint not found' });
}
}, 500); // Simulate network latency
});
}
export default mockApi;
3. Integrate your Mock API with the frontend
Lastly, you should integrate your Mock API in your main JavaScript file, like main.js. Let us do this:
import mockApi from './ mockApiServerMain.js';
async function fetchusersInfo() {
try {
const response = await mockApi('/api/usersInfo');
console.log('usersInfo:', response.data);
} catch (error) {
console.error('Error fetching usersInfo:', error.message);
}
}
async function fetcharticles() {
try {
const response = await mockApi('/api/articles');
console.log('articles:', response.data);
} catch (error) {
console.error('Error fetching articles:', error.message);
}
}
// Example of adding a new user
async function addUser() {
try {
const newUser = { name: 'Alice Johnson', email: 'alice@example.com' };
const response = await mockApi('/api/usersInfo', 'POST', newUser);
console.log('New User Added:', response.data);
} catch (error) {
console.error('Error adding user:', error.message);
}
}
// Example of adding a new user
async function delUser(id) {
try {
const response = await mockApi('/api/usersInfo', 'DELETE', id);
console.log('New User Delete:', response.data);
} catch (error) {
console.error('Error adding user:', error.message);
}
}
// Call the functions to fetch data
fetchusersInfo();
fetcharticles();
addUser();
delUser(1);
4. Running the example
If you want to run this example, you must set up a basic HTML file to include the Javascript file. Let us look at the example to get started:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mock API JS</title>
<script type="module" src="./main.js"></script>
</head>
<body>
<h1>Mock API JS EXAMPLE</h1>
</body>
</html>
Conclusion
Creating a Dependency-Free Mock API for Frontend Development is an excellent way to ignore any delay while building a project because of dependency. With this API, front-end developers can work on a project more efficiently. We have tried to help you create it with easy steps. You can connect with faux api to get help in creating Mock APIs.
FAQ
1. What are the benefits of mocking API?
Isolation, parallel developments, privacy, cost-effectiveness, load testing, better debugging, and more are the benefits of mocking API.
2. Why do we require mock services?
Mock services, like Faux API, can help you develop more strong by simulating dependencies during the process of testing.
3. What is the best reason for mocking data for testing?
Mocking data assist isolate the unit under test from its dependencies.