Routing and Request Handling
Define routes and handle HTTP requests.
Routing and Request Handling is a free Swift Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is Vapor?
Vapor is a popular server-side Swift web framework built on SwiftNIO. It lets you write HTTP backends — APIs, websites — entirely in Swift, sharing language and even models with your iOS app.
import Vapor
let app = try await Application.make(.detect())The Application and Routes
The Application object is the heart of a Vapor server. You register routes on it: mappings from an HTTP method and path to a handler closure that returns a response.
app.get("hello") { req in
"Hello, world!"
}HTTP Method Helpers
Vapor exposes a helper per HTTP verb: app.get, app.post, app.put, app.patch, and app.delete. Each takes path components and a handler.
app.post("users") { req in
"Created a user"
}
app.delete("users") { req in
"Deleted a user"
}Path Segments
Pass multiple string segments to build nested paths. The call below responds to GET /api/v1/status.
app.get("api", "v1", "status") { req in
"OK"
}Route Parameters
Use a colon-prefixed segment to capture a dynamic value. Read it from the request with req.parameters.get(_:). Below, requesting /users/42 captures 42.
app.get("users", ":id") { req -> String in
let id = req.parameters.get("id") ?? "unknown"
return "User id is " + id
}Typed Parameters
You can convert a parameter to a concrete type by passing the type to get. If conversion fails, Vapor automatically returns a 404, keeping handlers clean.
app.get("posts", ":id") { req -> String in
let id = try req.parameters.require("id", as: Int.self)
return "Post number " + String(id)
}Query Parameters
Read URL query items via req.query. For /search?term=swift, you can decode the term directly. Missing optional values simply come back as nil.
app.get("search") { req -> String in
let term = try req.query.get(String.self, at: "term")
return "Searching for " + term
}Route Groups
Group related routes under a shared prefix with app.grouped(...). This avoids repeating path components and keeps related endpoints together.
let users = app.grouped("users")
users.get { req in "List users" } // GET /users
users.post { req in "Create user" } // POST /usersReturning Different Response Types
A handler can return a String, an HTTPStatus, a custom Content type, or a fully built Response. Vapor knows how to encode each into an HTTP reply.
app.delete("cache") { req -> HTTPStatus in
// clear something
return .noContent // 204
}Throwing Errors with Abort
Throw Abort(_:) to short-circuit a request with a specific HTTP status and optional reason. Vapor turns it into a clean JSON error response.
app.get("secret") { req -> String in
guard req.headers.first(name: "X-Key") == "open" else {
throw Abort(.forbidden, reason: "Missing key")
}
return "Welcome"
}Async Handlers
Vapor 4+ fully supports async/await. Mark the handler closure async and use try await inside for database or network work.
app.get("ping") { req async throws -> String in
try await Task.sleep(for: .milliseconds(10))
return "pong"
}Quick Check: Routing
Confirm your routing knowledge.
Recap: Routing and Request Handling
You can now wire up a Vapor server:
- Register routes with
app.get/post/put/patch/deleteand path segments. - Capture dynamic values with
:paramand read them viareq.parameters(typed withrequire(_:as:)). - Read query items from
req.query, group routes withgrouped. - Return strings, statuses, or content; throw
Abortfor errors; use async handlers.
Frequently asked questions
Is the “Routing and Request Handling” lesson free?
Yes — the full text of “Routing and Request Handling” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.
What will I learn in “Routing and Request Handling”?
Define routes and handle HTTP requests. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Routing and Request Handling” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Routing and Request Handling
- Content and JSON Encoding
- Fluent ORM and Models
- Middleware and Authentication