3. Routing¶
WebApi supports the following HTTP verbs GET, POST, PUT, DELETE, PATCH, HEAD
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 purpose let’s consider a API service that would allow you to create and get users. We need two URIs. One to create an user 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 asStatic "user"
to wrap user inStatic
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 SocialNetworkApi where
-- Route <Method <Route Name
type Apis SocialNetworkApi = '[ Route '[POST] User
, Route '[GET, PUT, DELETE] UserId
]
In the above code snippet, we are delcaring that our route type
User
ie (/user
) acceptsPOST
UserId
acceptsGET
,PUT
,DELETE
.- Let’s say the user Id is 9,
GET /user/9
to get the user,PUT /user/9
to edit the user andDELETE user/9
to delete the user. You could read about implementation instances under the section Implementation
- Let’s say the user Id is 9,
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"
- Please note that when two route format overlaps, for example
user/posts
anduser/brian
WebApi’s routing system would take the first route that matches the pattern.