Skip to content

zayed31/URL-Shortener

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

URL Shortener Backend

A Spring Boot application that provides URL shortening functionality with RESTful APIs.

Features

  • Create short URLs from long URLs
  • Custom short URL support
  • URL expiration functionality
  • Click tracking
  • User-based URL management
  • Automatic cleanup of expired URLs
  • H2 database for development
  • RESTful API endpoints

Prerequisites

  • Java 17 or higher
  • Maven 3.6 or higher
  • IDE (IntelliJ IDEA, Eclipse, or VS Code)

Project Setup

Option 1: Using Spring Initializr (Recommended)

  1. Go to https://start.spring.io/

  2. Configure your project:

    • Project: Maven
    • Language: Java
    • Spring Boot: 3.2.x
    • Group: com.example
    • Artifact: urlshortener
    • Name: urlshortener
    • Description: URL Shortening Service
    • Package name: com.example.urlshortener
    • Packaging: Jar
    • Java: 17
  3. Dependencies to add:

    • Spring Web
    • Spring Data JPA
    • H2 Database
    • Spring Boot DevTools
    • Spring Boot Validation
    • Spring Boot Actuator
  4. Click "Generate" and download the project

  5. Extract and open in your IDE

Option 2: Manual Setup

The project structure is already created in this workspace. You can run it directly.

Running the Application

Using Maven Command Line

# Navigate to project directory
cd urlshortener

# Clean and compile
mvn clean compile

# Run the application
mvn spring-boot:run

Using IDE

  1. Open the project in your IDE
  2. Run the UrlShortenerApplication.java class
  3. The application will start on http://localhost:8080

API Endpoints

1. Create Short URL

POST /api/v1/urls

Request Body:

{
  "originalUrl": "https://www.example.com/very-long-url",
  "customShortUrl": "custom123",  // Optional
  "expiresAt": "2024-12-31T23:59:59",  // Optional
  "createdBy": "user123"  // Optional
}

Response:

{
  "shortUrl": "abc12345",
  "originalUrl": "https://www.example.com/very-long-url",
  "fullShortUrl": "http://localhost:8080/abc12345",
  "createdAt": "2024-01-15T10:30:00",
  "expiresAt": null,
  "clickCount": 0,
  "createdBy": "user123"
}

2. Redirect to Original URL

GET /{shortUrl}

Redirects to the original URL and increments click count.

3. Get URL Information

GET /api/v1/urls/{shortUrl}

Returns detailed information about a short URL.

4. Get All URLs

GET /api/v1/urls

Returns all active URLs.

5. Get URLs by User

GET /api/v1/urls/user/{createdBy}

Returns all URLs created by a specific user.

6. Delete URL

DELETE /api/v1/urls/{shortUrl}

Deletes a specific short URL.

7. Cleanup Expired URLs

POST /api/v1/urls/cleanup

Removes all expired URLs from the database.

Database

H2 Console (Development)

  • URL: http://localhost:8080/h2-console
  • JDBC URL: jdbc:h2:mem:testdb
  • Username: sa
  • Password: password

Production Database

To use PostgreSQL or MySQL in production, update application.properties:

# PostgreSQL
spring.datasource.url=jdbc:postgresql://localhost:5432/urlshortener
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

# MySQL
spring.datasource.url=jdbc:mysql://localhost:3306/urlshortener
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect

Configuration

Application Properties

Key configuration options in application.properties:

  • app.base-url: Base URL for generating short URLs
  • app.short-url-length: Length of generated short URLs (default: 8)
  • server.port: Server port (default: 8080)

Testing the Application

Using cURL

  1. Create a short URL:
curl -X POST http://localhost:8080/api/v1/urls \
  -H "Content-Type: application/json" \
  -d '{
    "originalUrl": "https://www.google.com",
    "createdBy": "testuser"
  }'
  1. Get URL information:
curl http://localhost:8080/api/v1/urls/abc12345
  1. Get all URLs:
curl http://localhost:8080/api/v1/urls

Using Postman

  1. Import the following collection or create requests manually
  2. Test each endpoint with appropriate request bodies

Project Structure

src/
├── main/
│   ├── java/
│   │   └── com/example/urlshortener/
│   │       ├── controller/
│   │       │   ├── UrlShortenerController.java
│   │       │   └── RedirectController.java
│   │       ├── dto/
│   │       │   ├── CreateUrlRequest.java
│   │       │   └── UrlResponse.java
│   │       ├── entity/
│   │       │   └── UrlMapping.java
│   │       ├── exception/
│   │       │   └── GlobalExceptionHandler.java
│   │       ├── repository/
│   │       │   └── UrlMappingRepository.java
│   │       ├── service/
│   │       │   └── UrlShortenerService.java
│   │       └── UrlShortenerApplication.java
│   └── resources/
│       └── application.properties
└── test/
    └── java/
        └── com/example/urlshortener/
            └── UrlShortenerApplicationTests.java

Monitoring

Actuator Endpoints

  • Health check: http://localhost:8080/actuator/health
  • Application info: http://localhost:8080/actuator/info
  • Metrics: http://localhost:8080/actuator/metrics

Security Considerations

For production deployment, consider adding:

  1. Authentication & Authorization

    • Spring Security
    • JWT tokens
    • OAuth2
  2. Rate Limiting

    • Implement rate limiting per IP/user
  3. Input Validation

    • URL validation
    • Malicious URL detection
  4. HTTPS

    • Enable HTTPS in production

Deployment

Docker

Create a Dockerfile:

FROM openjdk:17-jdk-slim
COPY target/urlshortener-0.0.1-SNAPSHOT.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app.jar"]

Build and run:

mvn clean package
docker build -t urlshortener .
docker run -p 8080:8080 urlshortener

Cloud Deployment

  • AWS: Deploy to EC2 or use AWS Elastic Beanstalk
  • Google Cloud: Deploy to App Engine or Cloud Run
  • Azure: Deploy to Azure App Service

Troubleshooting

Common Issues

  1. Port already in use: Change server.port in application.properties
  2. Database connection issues: Check database credentials and connectivity
  3. Validation errors: Ensure request body matches expected format

Logs

Check application logs for detailed error information:

tail -f logs/application.log

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

License

This project is licensed under the MIT License.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published