SaturnFramework / Saturn

Opinionated, web development framework for F# which implements the server-side, functional MVC pattern
https://saturnframework.org
MIT License
708 stars 108 forks source link

API routing isn't working -- using Saturn template #225

Closed MarneeDear closed 4 years ago

MarneeDear commented 4 years ago

I am trying to make the "api" code work using the Saturn template. I uncommented the API route code in the the router and made a few minor changes to get it to compile. When I make a request to that route, I get the 404 page.

Am I doing something wrong?

Here is my router:

module Router

open Saturn
open Giraffe.Core
open Giraffe.ResponseWriters

let browser = pipeline {
    plug acceptHtml
    plug putSecureBrowserHeaders
    plug fetchSession
    set_header "x-pipeline-type" "Browser"
}

let defaultView = router {
    get "/" (htmlView Index.layout)
    get "/index.html" (redirectTo false "/")
    get "/default.html" (redirectTo false "/")
}

let browserRouter = router {
    not_found_handler (htmlView NotFound.layout) //Use the default 404 webpage
    pipe_through browser //Use the default browser pipeline

    forward "" defaultView //Use the default view
}

//Other scopes may use different pipelines and error handlers

let api = pipeline {
    plug acceptJson
    set_header "x-pipeline-type" "Api"
}

let apiRouter = router {
    // error_handler (text "Api 404")
    pipe_through api
    get "/default" (setStatusCode 200 >=> text "API 200") //Use the default view
}

let appRouter = router {
    forward "/api" apiRouter
    forward "" browserRouter
}
Krzysztof-Cieslak commented 4 years ago

Hey,

From the top of my head - api pipeline plugs acceptJson which means you need to specify application/json in the Content-Type header on your request

MarneeDear commented 4 years ago

Thanks, @Krzysztof-Cieslak

Maybe I'm still doing this wrong. In Postman I set the Content-Type header to application/json like this:

curl --location --request GET 'https://localhost/mspe/cohorts/2020/students' \
--header 'X-API-Key: APIKeySecret' \
--header 'Content-Type: application/json'

And I get 404 not found. If I comment out the acceptJson plug, it does work.

MarneeDear commented 4 years ago

I had to use the Accept header:

curl --location --request GET 'https://localhost/mspe/cohorts/2020/students' \
--header 'X-API-Key: APIKeySecret' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json'
64J0 commented 2 years ago

I had this same problem recently.

Why would the API router demands this header Accept: application/json after all? I did not get this.