Currently in Beta - View old docs

What is routing?

Routing is the way in which requests (the combination of a URL and a HTTP method) are routed to the code that handles them.

When you navigated to www.kitura.io in your browser you were requesting the HTML file that is located there. The server hosting the files will respond with the requested file, if it exists, and you will see the file rendered in your browser. This means that under the covers there’s a server hosting the files for the Kitura.io website. In this server there is a route defined that states if we receive a GET request on “/” then respond with the home page that we see.

Here we mentioned a GET request being made on "/" but what does that mean? In the next section we will look at GET, which is an HTTP Method, in more detail.

REST APIs

Representational state transfer (REST) or RESTful APIs are a way of building web services to allow clients and servers to communicate using standard HTTP protocols. Essentially it’s an architectural and design pattern for building an API using HTTP methods, URI paths, and request and response body data.

HTTP Methods

An HTTP method is the part that defines what type of REST API we are calling. For example: A GET request gets a resource from the specified location, hence the name GET.

Below is a table of the main HTTP methods used in REST, listing their primary usage, what the request body should contain and what response we should expect from a call of that type.

HTTP Method Usage Request Body Response Body
GET The GET method is used to retrieve resources only No request body needed Reponds with resource
POST The POST method is used to create a new resource The resource to be created Reponds with the created resource
PUT The PUT method updates an existing resource The new version of a resource Responds with the updated resource
DELETE The DELETE method deletes an existing resource No request body needed No reponse body
PATCH The PATCH method makes a partial update to a resource The partially updated resource Responds with the updated resource

URI Paths

A URI path is the path upon which this route is linked. That is to say when a request is made to the specified path we know this is the code block to execute. Here is an example:

router.get("/hello")

Above is an example of registering a GET method on the "/hello" path. Let's assume our server is running at localhost:8080, then if I want to make a call to this endpoint I could open http://localhost:8080/hello in my browser and view the response.

Kitura provides two 'types' of routing, Raw Routing and Codable Routing. Over the next couple of sections we will dicuss them and highlight their differences.

Raw Routing

Raw routing is where the route handlers were called with RouterRequest and RouterResponse objects with which to handle the client request and build the response, along with a next completion handler. This approach provides great flexibility and control, but requires you to understand the structure of requests, how to interpret HTTP request headers correctly, how to verify data, and to manually carry out things like JSON parsing.

The following is an example of a Raw Route:

router.get("/") { request, response, next in
      response.send("Hello world")
      next()
    }

Router Request

The RouterRequest class is used to interact with incoming HTTP requests to the Router. It contains and allows access to the request’s Headers and Body as well as other properties of the request. It can also perform content negotiation based on the request’s Accept header.

Router Response

The RouterResponse class is used to define and work with the response that will be sent by the Router. It contains and allows access to the HTTP response code (e.g. 404 Not Found), the HTTP Headers and the body of the response. It can also render template files, using a template engine registered to the router.

Next

In Kitura you can register multiple handlers on a single route.

For example:

router.get("/") {request, response, next in
      response.send("Hello from the 1st route!")
      next()
    }

    router.get("/") {request, response, next in
      response.send("Hello from the 2nd route!")
      next()
    }

If a request comes into the server on `"/"` then the following would be returned to the client:

"Hello from the 1st route!"
    "Hello from the 2nd route!"

As you can see one route is called immediately after the other and this is made possible because of `next()`. Next is a closure that should be called after all the logic in a handler has successfully completed, this tells the server to go ahead and execute the 'next' handler in the list. It's important to note this should only be called on successful completion, in cases of an error `next()` should not be called.

Codable Routing

Codable routing is where the router handlers are just normal functions you might define elsewhere in your code; they take struct or class types as parameters, and respond with stuct or class types via a completion handler. The only requirement is that those types conform to the Codable protocol introduced in Swift 4 (hence the name).

func getHandler(completion: ([String]?, RequestError?) -> Void) {
        completion(["Hello World!"], nil)
    }

    router.get("/", handler: getHandler)

Any type that conforms to Codable can be used as a parameter in Codable routing, including your own custom structs and classes

Throughout these guides we will use a Codable Book model:

struct Book: Codable {
    let id: Int
    let title: String
    let price: Double
    let genre: String

    init(id: Int, title: String, price: Double, genre: String) {
        self.id = id
        self.title = title
        self.price = price
        self.genre = genre
    }
  }

Conclusion

Codable routing is a simpler approach to building RESTful APIs, particularly if you are new to REST. Codable routing also takes advantage of the inherent type safety of the Codable protocol provided by Swift. Codable routing will also feel more natural to Swift developers as defining routes is simply just defining functions.

Raw Routing is more more flexible and provides greater control over your RESTful API implementation but has a much higher learning curve, particularly for those new to REST and server-side coding.

Codable Routing isn’t suitable for every use case and scenario, so Raw Routing is still available where you need the power and flexibility.

Next steps

Add Codable Routing: Get useful feedback from your server about startup and errors

Add Raw Routing: Add REST APIs, such as HTTP GET, to your server

Back to top