REST API for URL Shortener
Build a URL shortener API in Perl with Dancer2, a lightweight web framework: send it a long link and get a short code back, open the short link and get redirected, and ask for statistics such as the number of clicks. Codes are generated in base62 (letters and digits), links are stored in SQLite through DBI, clicks are counted safely, and the API validates input and returns clear JSON errors. It's a good introduction to web development in Perl: you'll learn routes and JSON serialization in Dancer2, DBI with prepared statements, generating unique codes, redirects and status codes, and testing web apps with Plack::Test.
- Estimate
- ~7.5h
- Steps
- 5
- Completed by
- 0
- Proposed by
- codeseed.app
Dancer2 · DBI · SQLite
Project roadmap
- 01
Set up the Dancer2 app
~1hInstall Dancer2 (with cpanm) and create an app with dancer2 gen. Configure the JSON serializer, and add GET /health returning {"status": "ok"}. Run it with plackup. Done when: curl localhost:5000/health returns the JSON.
- 02
Create the database
~1hWrite a schema creating a links table in SQLite: id, code (unique), target URL, created at and clicks (default 0). Connect with DBI (DBD::SQLite) using RaiseError, sharing one connection helper across routes, and create the table at startup if it doesn't exist. Done when: the app starts and the table exists.
- 03
Generate short codes
~1.5hWrite a function that makes a random 7-character code from the 62 letters and digits using a good source of randomness (such as Crypt::URandom or Math::Random::Secure), and another that encodes a number in base62 for comparison. Handle the rare collision by trying again when the insert fails on the unique constraint. Done when: tests show codes use only the allowed characters and collisions are retried.
- 04
Shorten and redirect
~2hAdd POST /links taking {"url": "..."}: validate it's an http or https URL with a host (with the URI module) and not too long, insert it, and return 201 with the code and the short URL. Add GET /:code, which increases the click count with a single UPDATE and redirects with 302, or returns 404 for unknown codes. Use prepared statements with placeholders for every query. Done when: shortening and redirecting work, and invalid URLs get 400 with a JSON error.
- 05
Add stats and tests
~2hAdd GET /links/:code/stats returning the target, creation date and clicks. Write tests with Test::More and Plack::Test (HTTP::Request::Common) using a temporary database: creating links, invalid URLs, redirects with the Location header, click counting, stats and unknown codes. Done when: prove -l t/ passes.
Resources
- DocsDancer2 manual
- DocsDBI on MetaCPAN
- DocsPlack::Test on MetaCPAN
- DocsURI on MetaCPAN
- ArticleBase62 encoding explained
Ready to build this?
Get a GitHub repo and start building. Your AI reviewer checks each step as you go.
Tech stack