Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[New API] : URL Shortener API Added #294

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Existing_API_Collection/NasaAPI/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
</head>
<body>
<div class="container">
<h1>NASA Astronomy Picture of The Day</h1>
<h1>NASA Astronomy Picture of The Day</h1>git@github.com:sivaprasath2004/APIVerse.git
<div class="slideshow-container">
<div class="slideshow">
<div class="image-container">
Expand Down
65 changes: 65 additions & 0 deletions New_APIs/URL_shorten/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# URL Shortener API

This API allows you to shorten URLs and redirect users from shortened URLs to their original long URLs.

## Prerequisites

- Node.js and npm installed on your machine
- MongoDB installed and running locally or accessible remotely

## Installation

1. Clone the repository:
```bash
git clone https://github.com/dishamodi0910/APIVerse.git
cd APIVerse/New_APIs/URL_shorten
```

2. Install dependencies:
```bash
npm install
```

3. Set up environment variables:
- Create a `.env` file in the root directory
- Add the following variables:
```
DB=<your-mongodb-uri>
```

4. Start the server:
```bash
npm start
```

## API Endpoints

### POST /api/shorten

Shortens a long URL.

**Request Body**
```json
{
"originalUrl": "https://example.com/very-long-url-to-shorten"
}
```

**Response**
```json
{
"shortUrl": "http://your-domain.com/abc123"
}
```

### GET /:shortUrl

Redirects to the original long URL associated with the provided short URL.

## Usage

1. Send a POST request to `/api/shorten` with a JSON body containing `originalUrl`.
2. The API responds with a `shortUrl`.
3. Use the `shortUrl` to redirect users to the original `originalUrl`.


16 changes: 16 additions & 0 deletions New_APIs/URL_shorten/controller/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
let data=[]
const saveData=(originalUrl,shortUrlWithBase)=>{
let datas={originalUrl:originalUrl,time:new Date().toISOString(),shortUrl: shortUrlWithBase}
data.push(datas)
console.log(data)
return datas
}
const filterData=(url)=>{
let datas=data.find(item=>item. shortUrl===url)
return datas
}
const filterOriginalURL=(url)=>{
let datas=data.find(item=>item.originalUrl===url)
return datas
}
module.exports={saveData,filterData,filterOriginalURL}
68 changes: 68 additions & 0 deletions New_APIs/URL_shorten/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
const express = require('express');
const mongoose = require('mongoose');
const shortid = require('shortid');
const validUrl = require('valid-url');
const {saveData,filterData,filterOriginalURL}=require('./controller/db')
const app = express();

// Body parser middleware
app.use(express.json());

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));



// Routes
// API route to shorten URL
app.post('/api/shorten', async (req, res) => {
const { originalUrl } = req.body;

// Check if URL is valid
if (!validUrl.isUri(originalUrl)) {
return res.status(400).json('Invalid URL');
}

try {
let url = filterOriginalURL(originalUrl);

if (url) {
res.json(url);
} else {
const shortUrl = shortid.generate();
const datas=saveData(originalUrl,shortUrl)
res.json(datas);
}
} catch (err) {
console.error(err);
res.status(500).json('Server error');
}
});

// Route to redirect to original URL
app.get('/:shortUrl', async (req, res) => {
const { shortUrl } = req.params;

try {
const url = filterData(shortUrl)

if (url) {
return res.redirect(url.originalUrl);
} else {
console.log(`Short URL ${shortUrl} not found in database.`);
return res.status(404).json('URL not found');
}
} catch (err) {
console.error(`Error finding URL for short URL ${shortUrl}:`, err);
res.status(500).json('Server error');
}
});

// Serve static files if needed
// app.use(express.static('public'));

// Start server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Loading
Loading