Mobile

Using JSON Server for API Mocking in React Native

December 5, 20204 min readBy JSON Formatter Team

Learn how to use JSON Server for API mocking in React Native mobile app development. Create realistic APIs, build test cases, and accelerate development with mock data.

API Mocking Made Simple: JSON Server provides a simple, easy, and fast way to create realistic API endpoints for frontend development. It's perfect for React Native mobile applications where backend and frontend teams work concurrently.

The Backend and Frontend Dilemma

When building API-driven mobile applications, the backend and frontend teams often need to work on the same feature simultaneously. Even with Agile-Scrum methodology, frontend developers need payload data ready from the backend to start and test their development work.

This situation can hinder fast-paced and agile mobile app development. To catch up with planning, creating, testing, and deploying, we need data! The solution is API mocking.

Why Use JSON Server?

Developers have been using mocking tools since the beginning of web development. JSON Server provides a modern, simple approach to API mocking with these benefits:

Simple

Create realistic APIs for development, testing, and edge case handling

Easy

Simple setup and configuration for edge cases and failure scenarios

Fast

Quick setup for testing, reducing dependencies on unavailable backend services

Setting Up JSON Server

Setting up JSON Server is incredibly straightforward. You only need three simple steps:

Step 1: Installation

npm install json-server --save-dev

Step 2: Create db.json

Create a db.json file that contains your mock data. This file will expose REST API endpoints automatically.

{
  "products": [
    {
      "id": 1,
      "name": "Product 1",
      "price": 29.99,
      "description": "A great product"
    },
    {
      "id": 2,
      "name": "Product 2",
      "price": 39.99,
      "description": "Another great product"
    }
  ],
  "users": [
    {
      "id": 1,
      "username": "john_doe",
      "email": "john@example.com"
    }
  ]
}

Step 3: Run the Server

json-server --watch db.json

That's it! Your mock API is now running on http://localhost:3000 with automatic CRUD endpoints.

Advanced Setup with Custom Server

For more control over routing, authentication, validation, and other behaviors, you can create a custom server.js file:

const db = require('./db.json');
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router(db);
const middlewares = jsonServer.defaults();
const port = process.env.PORT || 3000;

// Use default middlewares (logger, static, cors, no-cache)
server.use(middlewares);

// Use body parser to parse JSON
server.use(jsonServer.bodyParser);

// Custom routes and rewrites
server.use(
  jsonServer.rewriter({
    '/api/products': '/products',
    '/api/users': '/users'
  })
);

// Custom middleware for authentication simulation
server.use((req, res, next) => {
  if (req.method === 'POST') {
    if (req.url === '/login') {
      // Simulate authentication logic
      const { username, password } = req.body;
      if (username === 'admin' && password === 'admin') {
        res.status(200).json({ token: 'fake-jwt-token' });
      } else {
        res.status(401).json({ error: 'Invalid credentials' });
      }
    } else {
      next();
    }
  } else {
    next();
  }
});

server.use(router);
server.listen(port, () => {
  console.log('JSON Server is running on port ' + port);
});

Using JSON Server with React Native

In your React Native app, you can now make API calls to your mock server just like you would with a real backend.

Example: Fetching Products

import React, { useEffect, useState } from 'react';
import { View, Text, FlatList } from 'react-native';

const ProductsScreen = () => {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetchProducts();
  }, []);

  const fetchProducts = async () => {
    try {
      const response = await fetch('http://localhost:3000/products');
      const data = await response.json();
      setProducts(data);
    } catch (error) {
      console.error('Error fetching products:', error);
    }
  };

  return (
    <View>
      <FlatList
        data={products}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => (
          <View style={{ padding: 10 }}>
            <Text style={{ fontSize: 18, fontWeight: 'bold' }}>
              {item.name}
            </Text>
            <Text>Price: $\{item.price}</Text>
          </View>
        )}
      />
    </View>
  );
};

export default ProductsScreen;

Example: Creating a Product

const createProduct = async (productData) => {
  try {
    const response = await fetch('http://localhost:3000/products', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(productData),
    });
    const data = await response.json();
    console.log('Product created:', data);
    return data;
  } catch (error) {
    console.error('Error creating product:', error);
  }
};

Benefits for Mobile Development

Work independently from backend team without blocking

Test edge cases and error scenarios easily

Create realistic data structures matching your backend

Simulate authentication and authorization flows

Test offline scenarios and network failures

Accelerate development and testing cycles

Best Practices

  • Keep your db.json file organized with realistic data structures
  • Use custom middleware to simulate authentication and error scenarios
  • Add delays to simulate network latency for more realistic testing
  • Version control your mock data alongside your code
  • Document your mock endpoints and expected responses

Conclusion

JSON Server is an invaluable tool for React Native developers working in agile environments. It provides a simple, fast, and realistic way to create mock APIs, allowing frontend teams to work independently while backend services are being developed.

By integrating JSON Server into your React Native development workflow, you can accelerate development cycles, test edge cases effectively, and reduce dependencies on unavailable backend services. Whether you're working with Redux, Redux-Saga, or simple React hooks, JSON Server integrates seamlessly with your existing architecture.

Format Your JSON Data

Use our free JSON formatter to ensure your db.json file is properly formatted and valid. Well-structured JSON files make JSON Server work more reliably.

Try JSON Formatter