Search code examples
f#f#-giraffesaturn-framework

How to get a query parameter in F# Saturn Framework?


Say we have this web server to handle requests:

let webApp = scope {
    get  "/api/zoo/animals/"    (getAllAnimals())
    getf "/api/zoo/animals/%s"  getAnimalInfo
}

This syntax is described in docs and demoed in the example.

Now, what if I want to have a param in the url query, e.g. to filter the results?

http://localhost:8080/api/zoo/animals?type=mammals

This does not do anything:

getf "/api/zoo/animals?type=%s" getAnimalsByType

Solution

  • A way to go is to use function GetQueryStringValue of the context. It returns Result, a struct DU.

    So you stay with initial signature (just remove the trailing slash):

    get "/api/zoo/animals" (getAnimals())
    

    And you have

    let getAnimals() : HttpHandler =
        fun _ ctx -> task { 
            let animalTypeFromQuery = ctx.GetQueryStringValue "type"
            let animalType =
                match animalTypeFromQuery with
                | Ok t    -> Some t
                | Error _ -> None
            ...
        }
    

    I do not know if this is the official practice, I found this practice in some F# github repos.