Creating and Accessing APIs in Android

When I started coding in Android, I often wondered how to create my own API and use it in my Android applications during development.

After extensive research, I discovered while using React that I could access a website from my mobile device if connected to the same network. This realization led me to think, "If I can access the frontend, I should be able to access the backend too."

So, after further research, I created a route and tested it on my mobile phone. To my delight, I was able to successfully access it.

Here is a sample code:

const express = require('express');
// Required for getting network interfaces
const os = require('os');  
const app = express();

app.use(express.json());

app.get('/', (req, res) => {
    return res.json({ message: 'hello' });
});

// Function to get the local IP address
const getLocalIP = () => {
    const interfaces = os.networkInterfaces();
    for (const interfaceName in interfaces) {
        for (const iface of interfaces[interfaceName]) {
            if (iface.family === 'IPv4' && !iface.internal) {
                return iface.address;
            }
        }
    }
    return 'localhost';
}

const port = 8080;

app.listen(port, '0.0.0.0', () => {
    const localIP = getLocalIP();
    console.log(`App live on http://${localIP}:${port}`);
});

and here is attached snapshot of my terminal

Hope this can help you.