Code Examples

API Examples & Use Cases

Learn how to integrate Indian location data in your applications with real-world examples

API Examples

Get All States
GET/api/locations/states
Retrieve all Indian states and union territories
curl "https://india-location-hub.in/api/locations/states"
View Response
{
  "success": true,
  "data": {
    "states": [
      {
        "id": 1,
        "name": "Maharashtra",
        "code": "MH"
      },
      {
        "id": 2,
        "name": "Gujarat",
        "code": "GJ"
      }
    ]
  }
}
Get Districts by State
GET/api/locations/districts?state_id=1
Get all districts for a specific state
curl "https://india-location-hub.in/api/locations/districts?state_id=1"
View Response
{
  "success": true,
  "data": {
    "districts": [
      {
        "id": 1,
        "name": "Mumbai",
        "state_id": 1
      },
      {
        "id": 2,
        "name": "Pune",
        "state_id": 1
      }
    ]
  }
}
Search Locations
GET/api/search?q=mumbai&limit=10
Search across all location types with fuzzy matching
curl "https://india-location-hub.in/api/search?q=mumbai&limit=10"
View Response
{
  "success": true,
  "results": [
    {
      "name": "Mumbai",
      "state_name": "Maharashtra",
      "district_name": "Mumbai",
      "taluka_name": "Mumbai City",
      "full_path": "Maharashtra > Mumbai > Mumbai City > Mumbai"
    }
  ],
  "total": 1,
  "query": "mumbai"
}
Get Database Stats
GET/api/stats
Retrieve comprehensive database statistics
curl "https://india-location-hub.in/api/stats"
View Response
{
  "success": true,
  "data": {
    "totalStates": 36,
    "totalDistricts": 766,
    "totalTalukas": 6912,
    "totalVillages": 527635,
    "lastUpdated": "2025-08-27T10:30:00.000Z"
  }
}

Common Use Cases

E-commerce Address Forms
Build cascading dropdowns for delivery addresses
ReactVue.jsAngular
// React example
import { useState, useEffect } from 'react';

const AddressForm = () => {
  const [states, setStates] = useState([]);
  const [districts, setDistricts] = useState([]);
  const [selectedState, setSelectedState] = useState('');

  useEffect(() => {
    fetch('/api/locations/states')
      .then(res => res.json())
      .then(data => setStates(data.data.states));
  }, []);

  const handleStateChange = async (stateId) => {
    setSelectedState(stateId);
    const response = await fetch(`/api/locations/districts?state_id=${stateId}`);
    const data = await response.json();
    setDistricts(data.data.districts);
  };

  return (
    <form>
      <select onChange={(e) => handleStateChange(e.target.value)}>
        <option value="">Select State</option>
        {states.map(state => (
          <option key={state.id} value={state.id}>
            {state.name}
          </option>
        ))}
      </select>
      
      <select disabled={!selectedState}>
        <option value="">Select District</option>
        {districts.map(district => (
          <option key={district.id} value={district.id}>
            {district.name}
          </option>
        ))}
      </select>
    </form>
  );
};
Location-based Analytics
Analyze data distribution across Indian regions
PythonPandasMatplotlib
import requests
import pandas as pd
import matplotlib.pyplot as plt

# Get all states
response = requests.get('https://india-location-hub.in/api/stats')
stats = response.json()['data']

# Create visualization
data = {
    'Category': ['States', 'Districts', 'Talukas', 'Villages'],
    'Count': [
        stats['totalStates'],
        stats['totalDistricts'], 
        stats['totalTalukas'],
        stats['totalVillages']
    ]
}

df = pd.DataFrame(data)
df.plot(x='Category', y='Count', kind='bar', title='India Location Distribution')
plt.yscale('log')  # Use log scale for better visualization
plt.show()

# Get district-wise data for Maharashtra
mh_response = requests.get('https://india-location-hub.in/api/locations/districts?state_id=1')
mh_districts = mh_response.json()['data']['districts']
print(f"Maharashtra has {len(mh_districts)} districts")
Microservice Architecture
Integrate location data in distributed systems
Node.jsExpressDocker
// Node.js Express service
const express = require('express');
const axios = require('axios');
const app = express();

const LOCATION_API_BASE = 'https://india-location-hub.in/api';

// Middleware to cache location data
const cache = new Map();

const cacheMiddleware = (req, res, next) => {
  const key = req.originalUrl;
  if (cache.has(key)) {
    return res.json(cache.get(key));
  }
  next();
};

// Get user's location hierarchy
app.get('/user-location/:stateId/:districtId', cacheMiddleware, async (req, res) => {
  try {
    const { stateId, districtId } = req.params;
    
    // Get state info
    const stateResponse = await axios.get(`${LOCATION_API_BASE}/locations/states`);
    const state = stateResponse.data.data.states.find(s => s.id == stateId);
    
    // Get district info
    const districtResponse = await axios.get(
      `${LOCATION_API_BASE}/locations/districts?state_id=${stateId}`
    );
    const district = districtResponse.data.data.districts.find(d => d.id == districtId);
    
    const result = {
      state: state,
      district: district,
      hierarchy: `${state?.name} > ${district?.name}`
    };
    
    // Cache for 1 hour
    cache.set(req.originalUrl, result);
    setTimeout(() => cache.delete(req.originalUrl), 3600000);
    
    res.json(result);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch location data' });
  }
});

app.listen(3000, () => {
  console.log('Location service running on port 3000');
});
Integration Tips
Best practices for using the India Location Hub API

Performance

  • • Cache API responses to reduce latency
  • • Use pagination for large datasets
  • • Implement debouncing for search queries
  • • Use CDN for static location data

Error Handling

  • • Always check the 'success' field in responses
  • • Implement retry logic for network failures
  • • Provide fallback UI for API errors
  • • Log errors for monitoring and debugging

Security

  • • Validate and sanitize user inputs
  • • Use HTTPS for all API calls
  • • Implement rate limiting on your end
  • • Never expose API keys in client-side code

User Experience

  • • Show loading states during API calls
  • • Implement autocomplete for search
  • • Use progressive disclosure for nested data
  • • Provide clear error messages to users