Skip to content

anoopcodehack/Smart-Parking-API

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

8 Commits
Β 
Β 
Β 
Β 

Repository files navigation

πŸ…ΏοΈ Smart Parking Lot API

A production-ready backend REST API for managing parking lots β€” automated slot allocation, real-time availability tracking, vehicle entry/exit workflow, duration calculation, and complete parking history.


πŸ“¦ Tech Stack

Layer Technology
Runtime Node.js
Framework Express.js
Database MongoDB
ODM Mongoose
Config dotenv
Dev server nodemon

πŸ—‚οΈ Project Structure

smart-parking/
β”œβ”€β”€ .env                        # Environment variables
β”œβ”€β”€ .env.example                # Template for environment setup
β”œβ”€β”€ .gitignore
β”œβ”€β”€ package.json
β”œβ”€β”€ README.md
└── src/
    β”œβ”€β”€ server.js               # Entry point β€” starts server
    β”œβ”€β”€ app.js                  # Express app, middleware, routes
    β”œβ”€β”€ config/
    β”‚   └── db.js               # MongoDB connection
    β”œβ”€β”€ models/
    β”‚   β”œβ”€β”€ ParkingSlot.js      # Slot schema
    β”‚   └── ParkingHistory.js   # History schema
    β”œβ”€β”€ controllers/
    β”‚   β”œβ”€β”€ slotController.js   # Slot CRUD logic
    β”‚   β”œβ”€β”€ vehicleController.js# Entry/exit logic
    β”‚   └── historyController.js# History retrieval
    β”œβ”€β”€ routes/
    β”‚   β”œβ”€β”€ slotRoutes.js
    β”‚   β”œβ”€β”€ vehicleRoutes.js
    β”‚   └── historyRoutes.js
    β”œβ”€β”€ middleware/
    β”‚   β”œβ”€β”€ logger.js           # Custom request logger
    β”‚   └── errorHandler.js     # 404 + global error handler
    └── utils/
        β”œβ”€β”€ response.js         # Standardized API responses
        └── duration.js         # Duration calculation helpers

βš™οΈ Setup Instructions

Prerequisites

  • Node.js v18+
  • MongoDB running locally or MongoDB Atlas URI

1. Clone the repository

git clone https://github.com/your-username/smart-parking-api.git
cd smart-parking-api

2. Install dependencies

npm install

3. Configure environment

cp .env.example .env

Edit .env:

PORT=3000
MONGODB_URI=mongodb://localhost:27017/smart_parking
NODE_ENV=development

4. Start the server

# Development (auto-reload)
npm run dev

# Production
npm start

Server runs at: http://localhost:3000


πŸ“‘ API Endpoints

Base URL: http://localhost:3000/api


πŸ”² Slot Management

Initialize Parking Lot

POST /api/slots/initialize

Body:

{ "totalSlots": 50 }

Response:

{
  "success": true,
  "message": "Parking lot initialized with 50 slots",
  "data": { "totalSlots": 50, "availableSlots": 50, "occupiedSlots": 0 }
}

Get All Slots

GET /api/slots
GET /api/slots?status=available
GET /api/slots?status=occupied

Get Slot by Number

GET /api/slots/:slotNumber

Reset Parking Lot

DELETE /api/slots/reset

⚠️ Clears all slots AND parking history. Use for testing/demo only.


πŸš— Vehicle Management

Vehicle Entry

POST /api/vehicles/entry

Body:

{ "numberPlate": "MH12AB1234" }
  • Automatically assigns the nearest available slot (lowest slot number)
  • Prevents duplicate entry
  • Records entry time

Response:

{
  "success": true,
  "message": "Vehicle MH12AB1234 has entered. Assigned Slot #3",
  "data": {
    "slotNumber": 3,
    "vehicleNumberPlate": "MH12AB1234",
    "entryTime": "2024-06-01T10:30:00.000Z",
    "recordId": "664abc..."
  }
}

Vehicle Exit

POST /api/vehicles/exit

Body:

{ "numberPlate": "MH12AB1234" }
  • Releases the slot
  • Calculates parking duration
  • Updates history record

Response:

{
  "success": true,
  "message": "Vehicle MH12AB1234 has exited from Slot #3",
  "data": {
    "vehicleNumberPlate": "MH12AB1234",
    "slotNumber": 3,
    "entryTime": "2024-06-01T10:30:00.000Z",
    "exitTime": "2024-06-01T12:45:00.000Z",
    "durationMinutes": 135,
    "durationFormatted": "2 hours 15 minutes"
  }
}

Get Currently Parked Vehicles

GET /api/vehicles

Search Vehicle by Number Plate

GET /api/vehicles/:numberPlate

Returns current parking status + full visit history for that vehicle.


πŸ“‹ Parking History

Get All History

GET /api/history
GET /api/history?status=PARKED
GET /api/history?status=EXITED
GET /api/history?plate=MH12AB1234
GET /api/history?page=1&limit=20

Get History Record by ID

GET /api/history/:id

Clear All History

DELETE /api/history/clear

βœ… Validation Rules

Field Rule
totalSlots Positive integer, max 1000
numberPlate Alphanumeric + hyphens, 2–15 characters, required
slotNumber Positive integer, must exist in DB
status query Must be available or occupied

πŸͺ΅ Middleware

Request Logger (src/middleware/logger.js)

Logs every incoming request:

[2024-06-01T10:30:00.000Z] POST /api/vehicles/entry - IP: ::1
[2024-06-01T10:30:00.000Z] POST /api/vehicles/entry β†’ STATUS: 201

Error Handler (src/middleware/errorHandler.js)

  • 404 handler for undefined routes
  • Global error handler with stack trace in development

πŸ“Š Data Models

ParkingSlot

{
  slotNumber: Number,       // unique, 1-based
  isOccupied: Boolean,      // default: false
  vehicleNumberPlate: String, // null when empty
  entryTime: Date           // null when empty
}

ParkingHistory

{
  vehicleNumberPlate: String,
  slotNumber: Number,
  entryTime: Date,
  exitTime: Date,           // null until exit
  durationMinutes: Number,  // null until exit
  status: "PARKED" | "EXITED"
}

🌟 Bonus Features Implemented

  • Nearest slot allocation β€” always assigns lowest available slot number
  • Duplicate vehicle prevention β€” 409 Conflict response
  • Duration calculation β€” minutes + human-readable format
  • Filter by availability β€” ?status=available|occupied
  • Search by number plate β€” full history + current status
  • Paginated history β€” ?page=1&limit=20
  • Standardized API responses β€” consistent { success, message, data } format
  • Indexed MongoDB queries β€” fast lookups on plate, status, entryTime

πŸ§ͺ Testing with Postman

Import postman/Smart_Parking_API.postman_collection.json into Postman.

Recommended test flow:

  1. POST /api/slots/initialize β€” create 10 slots
  2. GET /api/slots β€” verify all available
  3. POST /api/vehicles/entry β€” park 3 vehicles
  4. GET /api/slots?status=occupied β€” see occupied slots
  5. GET /api/vehicles β€” view parked vehicles
  6. POST /api/vehicles/exit β€” exit one vehicle
  7. GET /api/history β€” view history with duration
  8. GET /api/vehicles/:plate β€” search by plate

⚠️ Known Limitations

  • No authentication / authorization system
  • No real-time sensor integration
  • No automated billing/payment system
  • No number plate recognition (ANPR)
  • No frontend dashboard

πŸš€ Possible Future Improvements

  • JWT-based Admin/User authentication
  • Billing system based on parking duration
  • WebSocket support for real-time slot updates
  • ANPR integration for automated entry
  • Live monitoring dashboard (React/Next.js)
  • IoT sensor integration

πŸ“„ License

MIT

About

πŸ…ΏοΈSmart Parking Lot API A production-ready backend REST API for managing parking lots β€” automated slot allocation, real-time availability tracking, vehicle entry/exit workflow, duration calculation, and complete parking history.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors