Skip to content

Ujjwalpaliwal/Spotify_Backend_API

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🎡 Spotify Clone Backend API

A robust backend REST API built using Node.js, Express, and MongoDB that powers a Spotify clone. It supports user registration, role-based authorization (Users & Artists), file uploads (via Multer and ImageKit), and album creation.


πŸ› οΈ Technology Stack & Badges

JavaScript Node.js Express.js MongoDB Mongoose JWT Multer ImageKit


πŸ“‚ Project Structure

Backend/
β”œβ”€β”€ node_modules/           # Node.js dependencies
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ controllers/        # Request controllers (auth, music)
β”‚   β”œβ”€β”€ db/                 # Database connection logic
β”‚   β”œβ”€β”€ middleware/         # Custom authentication/role middlewares
β”‚   β”œβ”€β”€ models/             # Mongoose schemas (user, music, album)
β”‚   β”œβ”€β”€ routes/             # API routes definition
β”‚   β”œβ”€β”€ services/           # External integrations (storage service)
β”‚   └── app.js              # Express app setup and middleware configuration
β”œβ”€β”€ .env                    # Environment variables (local-only)
β”œβ”€β”€ package.json            # Project manifest & dependencies
β”œβ”€β”€ server.js               # Entry point of the server
└── README.md               # API Documentation

βš™οΈ Setup & Installation

1. Clone the repository

Ensure you are in the Backend directory:

cd spotify/Backend

2. Install dependencies

npm install

3. Setup Environment Variables

Create a .env file in the root of the Backend directory and populate it with your credentials:

PORT=3000
MONGODB_URI=your_mongodb_connection_string
JWT_SECRET=your_jwt_secret_key
IMAGEKIT_PUBLIC_KEY="your_imagekit_public_key"
IMAGEKIT_PRIVATE_KEY="your_imagekit_private_key"
IMAGEKIT_URL_ENDPOINT="https://ik.imagekit.io/your_endpoint_id"

4. Run the Server

  • Development mode (with nodemon):
    npm run dev
  • Production mode:
    npm start

πŸ—„οΈ Database Schemas

πŸ‘€ User Model

  • username: String (Required, Unique)
  • email: String (Required, Unique)
  • password: String (Required, Hashed)
  • role: String (Enum: ["user", "artist"], Default: "user")

🎡 Music Model

  • uri: String (Required) - CDN URL pointing to the uploaded audio file
  • title: String (Required) - Track title
  • artist: ObjectId (Required) - Reference to User (must be an artist)

πŸ’Ώ Album Model

  • title: String (Required) - Album title
  • musics: Array of ObjectIds - References to Music tracks
  • artist: ObjectId (Required) - Reference to User (must be an artist)

πŸ›‘οΈ Authentication & Authorization

All secure endpoints check for a valid JSON Web Token (JWT) in two locations:

  1. HTTP-only Cookie: Named token.
  2. Authorization Header: Bearer token (Bearer <JWT>).

Middleware Roles:

  • authUser: Checks if the token is valid and if the role is either "user" or "artist".
  • authArtist: Checks if the token is valid and if the role is "artist" (or "admin" if applicable).

🌐 API Endpoints Reference

πŸ” Authentication (/api/auth)

1. Register User / Artist

Registers a new account. Setting "role": "artist" allows the user to upload music and create albums.

  • Method & Path: POST /api/auth/register
  • Request Body (JSON):
    {
      "username": "johndoe",
      "email": "johndoe@example.com",
      "password": "securepassword",
      "role": "artist" 
    }
    (Note: role defaults to "user" if not specified)
  • Responses:
    • 201 Created: Returns user details and sets token in an HTTP-only cookie.
      {
        "user": {
          "_id": "603d7b42f63e411bf88f34bc",
          "username": "johndoe",
          "email": "johndoe@example.com",
          "role": "artist"
        }
      }
    • 400 Bad Request: User or email already exists.
      {
        "error": "User already exists"
      }

2. User Login

Logs in an existing user or artist.

  • Method & Path: POST /api/auth/login
  • Request Body (JSON):
    {
      "email": "johndoe@example.com",
      "password": "securepassword"
    }
    (Can also login with "username" instead of "email")
  • Responses:
    • 200 OK: Returns user details and sets token in an HTTP-only cookie (expiring in 1 hour).
      {
        "user": {
          "_id": "603d7b42f63e411bf88f34bc",
          "username": "johndoe",
          "email": "johndoe@example.com",
          "role": "artist"
        }
      }
    • 404 Not Found: User not found.
      {
        "error": "User not found"
      }
    • 401 Unauthorized: Password is incorrect.
      {
        "error": "Invalid password"
      }

3. User Logout

Logs out the current session by clearing the token cookie.

  • Method & Path: POST /api/auth/logout
  • Responses:
    • 200 OK: Clears the cookie.
      {
        "message": "User logged out successfully"
      }

4. Get Current User Profile

Retrieves info about the currently logged-in user.

  • Method & Path: GET /api/auth/profile
  • Headers: Cookie: token=<token> or Authorization: Bearer <token>
  • Responses:
    • 200 OK:
      {
        "user": {
          "_id": "603d7b42f63e411bf88f34bc",
          "username": "johndoe",
          "email": "johndoe@example.com",
          "role": "artist",
          "__v": 0
        }
      }
    • 401 Unauthorized: No token provided or token invalid.
      {
        "message": "Unauthorized: No token provided"
      }

🎡 Music & Album Management (/api/music)

1. Upload Music

Uploads a track to ImageKit and registers the music track in the database.

  • Role required: artist
  • Method & Path: POST /api/music/upload
  • Headers: Cookie: token=<token> or Authorization: Bearer <token>
  • Request Body (Multipart Form-Data):
    • title: String (Required) - e.g., "Stairway to Heaven"
    • music: File (Required) - The audio file binary
  • Responses:
    • 201 Created:
      {
        "message": "Music created successfully",
        "music": {
          "id": "603d7e5af63e411bf88f34bd",
          "title": "Stairway to Heaven",
          "artist": "603d7b42f63e411bf88f34bc",
          "uri": "https://ik.imagekit.io/p3c8xt7ms/music/music_1614618202568.mp3",
          "image": "https://ik.imagekit.io/p3c8xt7ms/music/music_1614618202568.mp3"
        }
      }
    • 400 Bad Request: Missing title or missing music file.
      {
        "error": "Music file is required under field name 'music'"
      }
    • 403 Forbidden: Logged-in user is not an artist.
      {
        "message": "Unauthorized: Not an artist"
      }

2. Create Album

Creates an album containing multiple music tracks.

  • Role required: artist
  • Method & Path: POST /api/music/album
  • Headers: Cookie: token=<token> or Authorization: Bearer <token>
  • Request Body (JSON):
    {
      "title": "Classic Rock Hits",
      "musics": [
        "603d7e5af63e411bf88f34bd",
        "603d7e6cf63e411bf88f34be"
      ]
    }
  • Responses:
    • 201 Created:
      {
        "message": "Album created successfully",
        "album": {
          "id": "603d7eb8f63e411bf88f34bf",
          "title": "Classic Rock Hits",
          "artist": "603d7b42f63e411bf88f34bc",
          "musics": [
            "603d7e5af63e411bf88f34bd",
            "603d7e6cf63e411bf88f34be"
          ]
        }
      }
    • 400 Bad Request: Missing title or musics array empty.
      {
        "error": "Musics is required"
      }

3. Get All Music Tracks

Fetches all uploaded tracks with artist details populated.

  • Role required: user or artist
  • Method & Path: GET /api/music/
  • Headers: Cookie: token=<token> or Authorization: Bearer <token>
  • Responses:
    • 200 OK:
      {
        "message": "Musics fetched successfully",
        "musics": [
          {
            "_id": "603d7e5af63e411bf88f34bd",
            "uri": "https://ik.imagekit.io/p3c8xt7ms/music/music_1614618202568.mp3",
            "title": "Stairway to Heaven",
            "artist": {
              "_id": "603d7b42f63e411bf88f34bc",
              "username": "johndoe",
              "email": "johndoe@example.com"
            },
            "__v": 0
          }
        ]
      }

4. Get All Albums

Fetches all albums (populated with general artist info).

  • Role required: user or artist
  • Method & Path: GET /api/music/album
  • Headers: Cookie: token=<token> or Authorization: Bearer <token>
  • Responses:
    • 200 OK:
      {
        "message": "Albums fetched successfully",
        "albums": [
          {
            "_id": "603d7eb8f63e411bf88f34bf",
            "title": "Classic Rock Hits",
            "artist": {
              "_id": "603d7b42f63e411bf88f34bc",
              "username": "johndoe",
              "email": "johndoe@example.com"
            }
          }
        ]
      }

5. Get Album By ID

Retrieves details of a single album, fully populating both the artist info and all nested tracks.

  • Role required: user or artist
  • Method & Path: GET /api/music/album/:albumId
  • Headers: Cookie: token=<token> or Authorization: Bearer <token>
  • Responses:
    • 200 OK:
      {
        "message": "Album fetched successfully",
        "album": {
          "_id": "603d7eb8f63e411bf88f34bf",
          "title": "Classic Rock Hits",
          "artist": {
            "_id": "603d7b42f63e411bf88f34bc",
            "username": "johndoe",
            "email": "johndoe@example.com"
          },
          "musics": [
            {
              "_id": "603d7e5af63e411bf88f34bd",
              "uri": "https://ik.imagekit.io/p3c8xt7ms/music/music_1614618202568.mp3",
              "title": "Stairway to Heaven",
              "artist": "603d7b42f63e411bf88f34bc",
              "__v": 0
            }
          ],
          "__v": 0
        }
      }
    • 404 Not Found: Album not found.
      {
        "error": "Album not found"
      }

About

A robust backend REST API built using Node.js, Express, and MongoDB that powers a Spotify clone. It supports user registration, role-based authorization (Users & Artists), file uploads (via Multer and ImageKit), and album creation.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors