Skip to content

Radhikaa-chauhan/socials-api-rails

Repository files navigation

Socials API

A secure RESTful API built with Ruby on Rails 8.1.2 that uses JSON Web Tokens (JWT) for authentication. This API serves as the backend for a social media platform where users can register, login, and create posts.

Live Demo

Base URL: https://socials-api-rails.onrender.com

Note: Hosted on Render free tier. First request may take 30-60 seconds to wake up.

Tech Stack

Technology Version Purpose
Ruby 4.0.1 Programming language
Rails 8.1.2 Web framework
PostgreSQL 18 Database
JWT - Authentication tokens
BCrypt - Password hashing
Puma 7.2.0 Web server
Rack-CORS - Cross origin requests

Features

  • User registration with secure password hashing
  • JWT based authentication
  • Protected routes — require valid token
  • Token expiry after 24 hours
  • User profile management
  • Posts creation and retrieval
  • RESTful API design
  • PostgreSQL database
  • Deployed on Render.com

API Endpoints

Authentication (No token required)

Method Endpoint Description Request Body
POST /users Register new user email, password, first_name, last_name, username
POST /auth Login and get JWT email, password

Users (Token required)

Method Endpoint Description
GET /users Get all users
GET /users/:id Get specific user

Posts (Token required)

Method Endpoint Description Request Body
GET /posts Get all posts -
GET /posts/:id Get specific post -
POST /posts Create new post content, user_id

Request & Response Examples

Register a User

Request:

curl -X POST https://socials-api-rails.onrender.com/users \
  -H "Content-Type: application/json" \
  -d '{
    "user": {
      "email": "radhika@example.com",
      "password": "123456",
      "first_name": "Radhika",
      "last_name": "Chauhan",
      "username": "radhika"
    }
  }'

Response 201 Created:

{
  "id": 1,
  "email": "radhika@example.com",
  "first_name": "Radhika",
  "last_name": "Chauhan",
  "username": "radhika"
}

Login

Request:

curl -X POST https://socials-api-rails.onrender.com/auth \
  -H "Content-Type: application/json" \
  -d '{
    "email": "radhika@example.com",
    "password": "123456"
  }'

Response 200 OK:

{
  "token": "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE3NDQwMzEyNTR9.abc123..."
}

Get All Users (Protected)

Request:

curl -X GET https://socials-api-rails.onrender.com/users \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

Response 200 OK:

[
  {
    "id": 1,
    "email": "radhika@example.com",
    "first_name": "Radhika",
    "last_name": "Chauhan",
    "username": "radhika"
  }
]

Create a Post (Protected)

Request:

curl -X POST https://socials-api-rails.onrender.com/posts \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{
    "post": {
      "content": "My first post!",
      "user_id": 1
    }
  }'

Response 201 Created:

{
  "id": 1,
  "content": "My first post!",
  "user_id": 1
}

Authentication

This API uses JWT (JSON Web Token) authentication.

How it works:

1. Register → POST /users
2. Login    → POST /auth → receive JWT token
3. Use token in every protected request header:
   Authorization: Bearer YOUR_TOKEN
4. Token expires after 24 hours → login again

Error Responses:

Status Error Reason
401 No token provided Missing Authorization header
401 Invalid token Token signature is wrong
401 Invalid or expired token Token expired or tampered
401 User not found User was deleted
401 Invalid email or password Wrong credentials

Local Setup

Prerequisites

  • Ruby 4.0.1
  • Rails 8.1.2
  • PostgreSQL
  • Bundler

Installation

1. Clone the repository

git clone https://github.com/Radhikaa-chauhan/socials-api-rails.git
cd socials-api-rails

2. Install dependencies

bundle install

3. Setup environment variables

cp .env.example .env

Edit .env with your values:

DB_USERNAME=postgres
DB_PASSWORD=your_postgres_password
SECRET_KEY_BASE=your_secret_key
JWT_SECRET_KEY=your_jwt_secret
RAILS_MASTER_KEY=your_master_key

4. Setup database

rails db:create
rails db:migrate

5. Start the server

rails server

API runs at http://localhost:3000


Project Structure

socials-api/
├── app/
│   ├── controllers/
│   │   ├── application_controller.rb  # JWT auth logic
│   │   ├── authentication_controller.rb # Login endpoint
│   │   ├── users_controller.rb        # User endpoints
│   │   └── posts_controller.rb        # Post endpoints
│   ├── models/
│   │   ├── user.rb                    # User model
│   │   └── post.rb                    # Post model
│   └── lib/
│       └── json_web_token.rb          # JWT encode/decode
├── config/
│   ├── routes.rb                      # API routes
│   ├── database.yml                   # DB config
│   └── puma.rb                        # Server config
├── db/
│   └── migrate/                       # Database migrations
├── Procfile                           # Render deploy config
├── .env.example                       # Environment template
└── README.md

Database Schema

Users Table

Column Type Description
id integer Primary key
email string Unique email
username string Unique username
first_name string First name
last_name string Last name
password_digest string Bcrypt hashed password
created_at datetime Timestamp
updated_at datetime Timestamp

Posts Table

Column Type Description
id integer Primary key
content text Post content
user_id integer Foreign key to users
created_at datetime Timestamp
updated_at datetime Timestamp

Deployment

Deployed on Render.com

Environment Variables on Render:

RAILS_ENV            = production
DATABASE_URL         = (Render PostgreSQL internal URL)
SECRET_KEY_BASE      = (generated with rails secret)
RAILS_MASTER_KEY     = (from config/master.key)
JWT_SECRET_KEY       = (random secret string)
RAILS_LOG_TO_STDOUT  = enabled

Testing with Postman

  1. Import the base URL: https://socials-api-rails.onrender.com
  2. Register a user via POST /users
  3. Login via POST /auth — copy the token
  4. Add token to Authorization header: Bearer YOUR_TOKEN
  5. Access protected routes

Security

  • Passwords hashed with BCrypt
  • Authentication via JWT tokens
  • Tokens expire after 24 hours
  • Strong parameters prevent mass assignment
  • Sensitive data excluded from API responses
  • Environment variables for all secrets

Known Limitations

  • Free tier on Render spins down after 15 mins inactivity
  • First request after inactivity takes 30-60 seconds
  • Free PostgreSQL on Render expires after 90 days

Author

Radhika Chauhan


License

MIT License

About

A RESTful API built with Ruby on Rails and JWT authentication for a social media platform

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors