Skip to content

Instantly share code, notes, and snippets.

@unoexperto
Created March 2, 2022 19:37
Show Gist options
  • Save unoexperto/4c448655bf64e2031c78647240fa642f to your computer and use it in GitHub Desktop.
Save unoexperto/4c448655bf64e2031c78647240fa642f to your computer and use it in GitHub Desktop.

Goal

Create simple url shortener. In first version it will be unauthenticated service which means that anyone can use API to shorted URL without registration.

Requirements

API endpoints

/url/shorten

Given a full URL, returns a short URL. Currently, the API only supports shortening a single URL per API call.

Method: GET

Request Params: longUrl

Response: Returns short url data on success

Example Call:

http://localhost/url/shorten?longUrl=https://www.imdb.com/title/tt8690918/episodes

Example Response:

{
  "longUrl": "https://www.imdb.com/title/tt8690918/episodes",
  "shortUrl": "http://localhost/u/924"
}

/url/expand

Given a short URL, returns the original full URL.

Method: GET

Request Params: shortUrl

Response: Returns original url data on success

Example Call:

http://localhost/url/expand?shortUrl=http://localhost/u/924

Example Response:

{
  "longUrl": "https://www.imdb.com/title/tt8690918/episodes",
  "shortUrl": "http://localhost/u/924"
}

Short URL handler

Service must handle GET requests to /u/XXX endpoint and redirect client to long url using HTTP 301 code. There are several redirection codes, but we should use 301 which is permanent redirect. It means user's browser will remember where to redirect next time user opens short url without calling our service.

Suggested frameworks and technologies

  1. Build system: Gradle (how to create new project: https://docs.gradle.org/current/samples/sample_building_java_applications.html)
  2. RESTful API framework: Spring Boot. Looks like it's easier to create sample project using https://start.spring.io/ like this sdfdsf
  3. Use H2 local database to store information about URLs (it will be dependency in your Gradle script)
  4. Use Jdbi framework to connect and work with H2 DB (https://jdbi.org/).
  5. Use JUnit for unit-tests.

Suggested steps of implementation

  1. Create skeleton Spring Boot project;
  2. Add two endpoints with hardcoded responses;
  3. Change endpoint handlers to generate shortened URLs but store them in local HashMap<String, String> object. Create such storage in separate class that implement your UrlStore interface;
  4. For simplicity use increasing number for short URL (contrary to using hash values such as 8PSW);
  5. Implement H2 storage class that implements UrlStore interface from item 3 so that data can survive restart of your service;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment