A simple RESTful API built with Node.js, Express, and PostgreSQL that allows users to shorten long URLs, retrieve the original URLs, update or delete short URLs, and track statistics for short URLs.
- Create Short URL: Shorten a long URL into a unique short code.
- Retrieve Original URL: Retrieve the original URL using the short code.
- Update Short URL: Update an existing short URL.
- Delete Short URL: Delete an existing short URL.
- Get Statistics: Track the number of times a short URL has been accessed.
Ensure you have the following installed:
-
Clone the Repository
git clone https://github.com/ProdiGeeZ/url-shortener.git cd url-shortener
-
Install Dependencies
npm install
-
Configure Environment Variables Create a
.env
file in the project root and configure the following variable (requires pgpass configuration):PGDATABASE=url_shortener
-
Setup PostgreSQL Database
npm run setup
-
Start the Server
npm start
The server will be available at
http://localhost:3000
.
POST /api/shorten
Request Body:
{
"url": "https://www.example.com/some/long/url"
}
Response:
- 201 Created
{ "id": "1", "url": "https://www.example.com/some/long/url", "shortCode": "abc123", "descriptor": "description of shortened link", "createdAt": "2021-09-01T12:00:00Z", "updatedAt": "2021-09-01T12:00:00Z" }
- 400 Bad Request: Validation errors.
GET /api/shorten/:shortCode
Response:
- 200 OK
{ "id": "1", "url": "https://www.example.com/some/long/url", "shortCode": "abc123", "descriptor": "description of shortened link", "createdAt": "2021-09-01T12:00:00Z", "updatedAt": "2021-09-01T12:00:00Z" }
- 404 Not Found: If the short code does not exist.
PUT /api/shorten/:shortCode
Request Body:
{
"url": "https://www.example.com/some/updated/url"
}
Response:
- 200 OK
{ "id": "1", "url": "https://www.example.com/some/updated/url", "shortCode": "abc123", "descriptor": "description of shortened link", "createdAt": "2021-09-01T12:00:00Z", "updatedAt": "2021-09-01T12:30:00Z" }
- 400 Bad Request: Validation errors.
- 404 Not Found: If the short code does not exist.
DELETE /api/shorten/:shortCode
Response:
- 204 No Content: If the short URL was successfully deleted.
- 404 Not Found: If the short code does not exist.
GET /shorten/:shortCode/stats
Response:
- 200 OK
{ "id": "1", "url": "https://www.example.com/some/long/url", "shortCode": "abc123", "descriptor": "description of shortened link", "accessCount": 10 "createdAt": "2021-09-01T12:00:00Z", "updatedAt": "2021-09-01T12:00:00Z", }
- 404 Not Found: If the short code does not exist.
Table: urls
Column | Type | Description |
---|---|---|
id | SERIAL | Primary key |
url | TEXT | Original long URL |
short_code | VARCHAR(10) | Unique short code |
descriptor | VARCHAR(100) | Optional description for the URL |
access_count | INTEGER | Number of times the short URL is accessed |
created_at | TIMESTAMP | Timestamp when the URL was created |
updated_at | TIMESTAMP | Timestamp when the URL was last updated |