Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 38 ยท Projects and Practice

Project: Build a URL Shortener with Ktor

Build a URL shortener step by step: design the API, generate Base62 codes, validate URLs, redirect with 302, count clicks, store links with Exposed and test the routes. Includes a runnable core.

In this project you build a URL shortener, the classic small service that touches almost everything you have learned: routing, JSON, validation, status codes, redirects, a database and tests. A user posts a long URL, gets back a short code, and anyone who visits /{code} is redirected to the original address. You will also count clicks.

About the examples. The Ktor and Exposed code is real and read-only (the site cannot run Gradle or Ktor). The core logic (code generation, validation, storage, redirect decisions) is implemented as plain Kotlin you can run and change right here. In your own project you would put the same functions behind the routes shown below.

1. Design the API first

Method and path Purpose Success Errors
POST /api/links Create a short link from {"url": "..."} 201 with {code, shortUrl} 400 invalid URL
GET /{code} Redirect to the target 302 with Location 404 unknown code
GET /api/links/{code} Show details and click count 200 404
DELETE /api/links/{code} Remove a link 204 404

Two decisions are worth making deliberately. First, 302 Found (temporary) or 301 Moved Permanently? Browsers cache a 301 aggressively, so clicks may never reach your server and your counter stays at 1. Use 302 (or 307) when you want to count visits or change targets later. Second, the codes: short, URL-safe and hard to guess in bulk.

2. Generating short codes

A simple scheme: give every link a numeric id from the database, then encode the id in Base62 (digits, lowercase and uppercase letters: 62 symbols). Id 125 becomes 21, a million becomes 4c92. It is short, needs no collision checks (ids are unique), and decodes back to the id. The downside is that codes are sequential and therefore guessable; to hide the order, add a secret offset or shuffle the alphabet.

Kotlin Core: Base62 encoding and decoding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

3. Validating the target URL

Never redirect to just anything. Accept only http and https, require a host, and limit the length. Rejecting javascript: and file: schemes matters: an open redirect to a scripting scheme is a security hole. Also refuse links that point back to your own domain, or you can create redirect loops.

In Ktor, request validation can do this once for every CreateLink body; below, the same rules are a plain function.

4. The service: create, resolve, count

Keep the logic out of the routes in a service class so it is easy to test. The version below uses an in-memory store, with the same interface your Exposed-backed repository would implement. It also demonstrates reusing the existing code when the same URL is submitted twice.

Kotlin Core: the shortener service

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

5. The real Ktor application

Now put the service behind routes. First the models and the plugins you need (ContentNegotiation, StatusPages):

Kotlin
@Serializable data class CreateLink(val url: String)
@Serializable data class LinkResponse(val code: String, val shortUrl: String, val clicks: Int)

fun Application.module() {
    install(ContentNegotiation) { json() }
    install(StatusPages) {
        exception<InvalidUrl> { call, e ->
            call.respond(HttpStatusCode.BadRequest, mapOf("error" to e.message))
        }
    }

    val baseUrl = environment.config.property("app.baseUrl").getString()
    val shortener = Shortener(LinkRepository(), ownHost = URI(baseUrl).host)

    routing {
        route("/api/links") {
            post {
                val body = call.receive<CreateLink>()
                val link = shortener.create(body.url)
                call.respond(HttpStatusCode.Created, LinkResponse(link.code, "$baseUrl/${link.code}", link.clicks))
            }
            get("/{code}") {
                val link = shortener.details(call.parameters["code"]!!)
                    ?: return@get call.respond(HttpStatusCode.NotFound)
                call.respond(LinkResponse(link.code, "$baseUrl/${link.code}", link.clicks))
            }
            delete("/{code}") {
                val removed = shortener.delete(call.parameters["code"]!!)
                call.respond(if (removed) HttpStatusCode.NoContent else HttpStatusCode.NotFound)
            }
        }

        get("/{code}") {
            val target = shortener.resolve(call.parameters["code"]!!)
            if (target == null) call.respond(HttpStatusCode.NotFound)
            else call.respondRedirect(target, permanent = false)   // 302
        }
    }
}

Route order matters little here: Ktor prefers the more specific route, so /api/links is not mistaken for a code. (Remember to reserve words like api so nobody gets a code that clashes with a route; with Base62 codes that never happens beyond a certain size, but custom aliases would need a check.)

Kotlin
object Links : LongIdTable("links") {
    val code = varchar("code", 16).uniqueIndex().nullable()
    val url = varchar("url", 2000).uniqueIndex()
    val clicks = integer("clicks").default(0)
    val createdAt = timestamp("created_at").defaultExpression(CurrentTimestamp)
}

class LinkRepository {
    suspend fun create(url: String): LinkRow = dbQuery {
        val existing = Links.selectAll().where { Links.url eq url }.singleOrNull()
        if (existing != null) return@dbQuery existing.toLink()
        val id = Links.insertAndGetId { it[Links.url] = url }
        val code = encode(id.value)
        Links.update({ Links.id eq id }) { it[Links.code] = code }
        LinkRow(id.value, code, url, 0)
    }

    suspend fun resolve(code: String): String? = dbQuery {
        val updated = Links.update({ Links.code eq code }) { it[clicks] = clicks + 1 }
        if (updated == 0) null
        else Links.selectAll().where { Links.code eq code }.single()[Links.url]
    }
}

Two points. The click increment is a single SQL update (clicks = clicks + 1) rather than "read, add one, write", which would lose clicks under concurrent requests. And the unique index on url backs up the "reuse existing" logic, so two simultaneous identical requests cannot create duplicates; handle the unique-violation error by reading the winner. See Exposed: Querying with the DSL and Connection Pooling and Migrations for the details behind these calls.

7. Test the routes

Kotlin
@Test
fun createsAndRedirects() = testApplication {
    application { module() }
    val client = createClient { install(ContentNegotiation) { json() }; followRedirects = false }

    val created = client.post("/api/links") {
        contentType(ContentType.Application.Json)
        setBody(CreateLink("https://example.com/a"))
    }
    assertEquals(HttpStatusCode.Created, created.status)
    val code = created.body<LinkResponse>().code

    val redirect = client.get("/$code")
    assertEquals(HttpStatusCode.Found, redirect.status)
    assertEquals("https://example.com/a", redirect.headers[HttpHeaders.Location])
}

Note followRedirects = false: the test client follows redirects by default, which would hide the 302 you want to assert. More patterns are in Testing Ktor Applications.

Ideas to extend it

  • Custom aliases (/my-link) with a reserved-word list.
  • Expiry dates and a cleanup job (see coroutines for background work).
  • Per-IP rate limiting on POST /api/links.
  • Authentication for owners to list and delete their own links (Authentication Basics).
  • A click log table (time, referrer) for analytics, written asynchronously so redirects stay fast.
  • A cache in front of resolve, since reads vastly outnumber writes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a click-counting shortener usually redirect with 302 instead of 301?

    A permanent redirect can be cached by the browser, bypassing your counter.
  2. 2. Why validate that the scheme is http or https?

    Restricting schemes prevents open-redirect and script-injection abuse.
  3. 3. Why increment clicks with one SQL update (clicks = clicks + 1)?

    An atomic update lets the database serialize concurrent increments.
  4. 4. What does Base62 encoding of a database id give you?

    Unique ids map to unique codes; the trade-off is that the codes are sequential.

Summary

  • Design the API and status codes first; use 302 to keep counting visits.
  • Base62-encode unique ids for short, collision-free codes; validate schemes, hosts and length.
  • Keep logic in a service class behind a repository so routes stay thin and tests are easy.
  • Use atomic SQL updates for counters and unique indexes for duplicates.
  • Test redirects with a client that does not follow them.

Next: Project: A Real-Time Chat Room