3. Routing

WebApi supports the following HTTP verbs GET, POST, PUT, DELETE, PATCH, HEAD

You can also use any Custom method as per your needs.

In WebApi we need to first write all the routes as types and then declare the valid HTTP verbs for each route type.

3.1. Routes as types

Each route is declared as a type. For demo purposes let’s consider a API service that would allow you to create and get users. We need two URIs. One to create a user and another one to get the user by her ID.

/user URI to create a user

type User = Static "user"

/user/9 URI to get a user

type UserId = "user" :/ Int
  • Note that /user is declared as Static "user" to wrap user in Static to make all the types of the same kind (*)

As you could see in the above examples, routes are defined as types. The next step is to write a WebApi instance for the route types along with the HTTP verbs they support.

instance WebApi MyApiService where
  -- Route <Method>  <Route Name>
   type Apis MyApiService = '[ Route '[POST]             User
                             , Route '[GET, PUT, DELETE] UserId
                             ]

In the above code snippet, we are declaring that our route type

  • User ie (/user) accepts POST
  • UserId accepts GET, PUT, DELETE.
    • Let’s say the user Id is 9, then GET /user/9 could be used to get the user, PUT /user/9 to edit the user and DELETE user/9 to delete the user.

3.2. More examples

/post/tech/why-i-like-web-api

type Post = "post" :/ Text :/ Text

/post/tech/why-i-like-web-api/edit

type EditPost = "post" :/ Text :/ Text :/ "edit"

/why-i-like-web-api/comments

type Comments = Text :/ "comments"

Note

Please note that when two route format overlaps, for example user/posts and user/brian WebApi’s routing system would take the first route that is declared first in the WebApi instance.