Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Routing and Requests

Status Codes and Headers

Use the right HTTP status codes and headers in Ktor: HttpStatusCode, 201 with Location, 204, 304 and ETag, 405 with Allow, redirects, and caching headers.

Status codes and headers are the vocabulary of HTTP. A client library, a browser, a cache and a monitoring dashboard all decide what to do by reading them, not by parsing your response text. Choosing them carefully is one of the cheapest ways to make an API feel professional. This lesson covers Ktor's HttpStatusCode, the codes an API uses daily, and the headers that go with them.

HttpStatusCode

Ktor represents status codes as HttpStatusCode constants:

Kotlin
call.respond(HttpStatusCode.OK, "fine")
call.respond(HttpStatusCode.Created, book)
call.respond(HttpStatusCode.NoContent)
call.respond(HttpStatusCode.NotFound, "no such book")
call.respond(HttpStatusCode(418, "I'm a teapot"), "short and stout")   // a custom one

The classes of status codes:

Range Meaning Examples
1xx Informational 101 Switching Protocols (WebSockets)
2xx Success 200 OK, 201 Created, 202 Accepted, 204 No Content
3xx Redirect or not modified 301, 302, 304 Not Modified
4xx The client made a mistake 400, 401, 403, 404, 405, 409, 415, 422, 429
5xx The server failed 500, 502, 503

The codes an API uses daily

Situation Code
Read succeeded 200 OK
Created a resource 201 Created + Location header
Accepted for later processing 202 Accepted
Success, nothing to return (delete, update) 204 No Content
Malformed request, invalid parameter 400 Bad Request
Not logged in or bad credentials 401 Unauthorized + WWW-Authenticate
Logged in but not allowed 403 Forbidden
Unknown resource 404 Not Found
Method not supported on this path 405 Method Not Allowed + Allow
Conflict, e.g. duplicate username 409 Conflict
Wrong content type 415 Unsupported Media Type
Valid JSON but invalid values 422 Unprocessable Content (or 400)
Rate limit exceeded 429 Too Many Requests + Retry-After
Bug or crash on the server 500 Internal Server Error
Dependency down 503 Service Unavailable

Be careful with the pair 401/403: 401 means "I do not know who you are" (authenticate), 403 means "I know who you are and you may not do this". The authentication chapter uses both.

Creating resources: 201 and Location

After POST /books, the standard answer is 201 Created with a Location header that points at the new resource, and usually the created object in the body:

Kotlin
post("/books") {
    val input = call.receive<NewBook>()
    val book = repository.add(input)
    call.response.header(HttpHeaders.Location, "/books/${book.id}")
    call.respond(HttpStatusCode.Created, book)
}
delete("/books/{id}") {
    val removed = repository.remove(call.parameters.getOrFail<Int>("id"))
    if (removed) call.respond(HttpStatusCode.NoContent) else call.respond(HttpStatusCode.NotFound)
}

Redirects

call.respondRedirect("/books") sends 302 Found. Use permanent = true for 301 Moved Permanently (browsers and search engines cache this). For a redirect after a POST, the pattern POST then 303 See Other then GET prevents the form from being re-submitted on refresh; use call.response.status(HttpStatusCode.SeeOther) plus a Location header.

Caching with ETag and 304

Clients and CDNs can avoid re-downloading unchanged data. The server sends an ETag (a fingerprint of the current version). Next time the client sends If-None-Match: <etag>; if it still matches, the server answers 304 Not Modified with no body. Ktor's ConditionalHeaders plugin does this for static content. For API data you can do it by hand, as the stand-in shows.

Stand-in: statuses, headers, 405 and 304 on a real server

The program starts a loopback HTTP server and exercises the codes above. The client does not follow redirects, so you see the raw 302.

Kotlin Stand-in: status codes, Location, Allow, ETag

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.

Compare each line to the tables above: 201 carries a Location, the 405 carries Allow, the 304 has no body, and 204 has none either.

Headers worth knowing

Header Direction Use
Content-Type both Media type of the body
Accept request Which types the client can read
Authorization request Credentials (authentication)
Location response Where the new or moved resource is
Cache-Control response Caching rules, e.g. max-age=60
ETag / If-None-Match both Conditional requests
WWW-Authenticate response How to authenticate (with 401)
Retry-After response When to try again (429, 503)

In Ktor, use the constants in HttpHeaders (HttpHeaders.Location) to avoid typos, and call.response.header(name, value) to set them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A client calls POST /books and the book is created. Which response is the usual choice?

    201 Created, ideally with a Location header for the new resource.
  2. 2. What is the difference between 401 and 403?

    401: who are you? 403: I know you, but no.
  3. 3. What header should accompany a 405 Method Not Allowed?

    The Allow header tells the client which methods the resource supports.
  4. 4. When does a server answer 304 Not Modified?

    A matching conditional request lets the server skip the body.

Summary

  • Use HttpStatusCode constants; 2xx success, 3xx redirect, 4xx client error, 5xx server error.
  • 201 Created + Location after creation, 204 when there is nothing to return, 404 for unknown resources.
  • 401 = not authenticated, 403 = not allowed, 405 + Allow for wrong methods.
  • ETag with If-None-Match gives cheap 304 Not Modified responses.
  • Prefer the HttpHeaders constants for header names.

Next: Structured Routing and Resources