:body-params vs :form-params in compojure-api - clojure

What's the difference between using :body-params and :form-params in practice when creating an API using compojure-api? For example:
(POST* "/register" []
:body-params [username :- String,
password :- String]
(ok)))
vs
(POST* "/register" []
:form-params [username :- String,
password :- String]
(ok)))
Which one should be used for an API that's going to be consumed by a single-page clojurescript app and/or native mobile apps?

It has to do with the supported content type:
form-params are intended to be used with content-type "application/x-www-form-urlencoded" (a form)
body-params are intended to use for parameters which are also going to be located in the body with other content-types (edn, json, transit, etc).
You'll want to use :body-params to consume it from your clojurescript or mobile apps.
Using form-params or body-params will affect how the parameters are validated, from which part of the request they are taken, and how the swagger.json file would be generated if you use the swagger extensions.
Many things in compojure-api are difficult to understand without mapping them to concepts in swagger. Looking into the code we find swagger terms like "consumes" or "formData" that can be found in the swagger parameter specs.

Related

How to make session data in http-kit

For my login system, I need to implement session data for different functionality when users are logged in or not.
I've only ever done sessions in flask, and google searches don't reveal a lot (or, more likely, I'm searching the wrong things). I have two questions:
Is there a canonical way to do session data in Clojure and can this specifically done in http-kit?
Is an atom enough, or would this be bad practice?
sessions will have to be managed via ring. http-kit is a server & will only use the ring spec for requests and responses.
To fetch the session
(get-in req [:session :auth-token])
To add a session to your ring response
(assoc res
:session {:auth-token auth-token
:userid (:id json-data)
:username (:username json-data)})

In ClojureScript, why can't I navigate to a URL entered by hand, but if I click a link it works?

(Note, I'm using Reagent, Secretary, and Compojure (among others))
I want to create a route /sectest/:id, and if I point my browser to that route, I get the following error:
Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:3449/sectest/css/site.css".
asdf:1
Refused to execute script from 'http://localhost:3449/sectest/js/app.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
But if I click on a link in the browser that navigates to that route, it works fine...
Here's the pertinent code:
Client Side:
(secretary/defroute "/sectest/:id" [id]
(do
(js/console.log (str "Hi " id))
(session/put! :current-page #'my-page)))
Server Side:
(defroutes routes
(GET "*" [] loading-page) ;this anticipates client-side routing only
(GET "/cards" [] cards-page)
(resources "/")
(not-found "Not Found"))
(def app (wrap-middleware #'routes))
So the following link takes me to my-page, and the console prints "Hi asdf" just fine:
[:div [:a {:href "/sectest/asdf"} "SECTEST"]]
But if I type in http://localhost:3449/sectest/asdf, I get an error, and I can't seem to trace it. I suspect it might have something to do with the code trying to find resources located at /sectest, (which it shouldn't), but I can't confirm this or figure out how to work with it... I am new to clojure, so forgive if I'm massively ignorant on some point, any thoughts?
Take a look at your server side routing, effectively you only have one route:
(GET "*" [] loading-page)
As it handles everything all following routes will never trigger. Order matters:
(defroutes routes
(GET "/cards" [] cards-page)
(resources "/")
(GET "*" [] loading-page) ;this anticipates client-side routing only
)
The above should do the trick, I removed the 404 route, as this should be handled by the frontend routing.
The reason it currently works when clicking on a page link in your SPA is that it will get handled by secretary. If you enter the url manually you are doing a page reload and the request is handled by compojure initially.
Edit:
After taking a closer look, relative links to your css/js files in your html template are most likely the culprit here:
/sectest/js/app.js
The compojure resources route won't match and the default catch all route loading-page is served as css/js file to your browser. Hence the error.
For my dev env I also had to correct the :asset-path of my boot cljs task as the source mapping files suffered from the problem. Should be similiar with lein-figwheel.

How to access a JSON webservice in Clojure?

What is the common way of accessing a web service and getting response JSON as Clojure maps ?
Do we have to use Java's java.net.URLConnection and Some JSON library like GSON ?
Is http-kit the most used library for this purpose, thats what I get via Google?
Take a look at clj-http. One of its dependencies is a JSON library called cheshire.
Here's an example of a basic GET request that parses the body as JSON.
(clj-http.client/get "http://example.com/foo.json" {:as :json})
For asynchronous HTTP you should look at http.async.client

Is there some sort of canonical edn response we can use for ring?

I've been reading the edn spec and want to integrate it into my application. However, I don't know how to transfer edn requests between clojure and client. Do we put a content-type application/edn in the response header and just send the prn output string?
Although it has not yet been accepted by IANA (June 14, 2013), the correct content-type is application/edn. To provide a valid string output of your clojure object, use (pr-str obj). For a web service, the method of encoding and decoding depends on your web framework and your needs.
Pedestal supports parsing of edn into an :edn-params key on its request map through the use of its body-params interceptor. Sending clojure objects as edn is handled automatically if your response bodies are not strings. For content-negotiation, see pedestal-content-negotiation.
For ring middleware, ring-edn parses edn into an :edn-params key, but does not do any outbound modification. ring-middleware-format provides parsing of a handful of different formats into the :body-params key, and has a collection of middlewares that can be helpful for responses as well. There are a handful of other ring middleware projects like this out there.

Put Clojure Ring middlewares in correct order

I'm having trouble with my Clojure server middlewares. My app has the following requirements:
Some routes should be accessible with no problems. Others require basic authentication, so I'd like to have an authentication function that sits in front of all the handler functions and makes sure the request is verified. I've been using the ring-basic-authentication handler for this, especially the instructions on how to separate your public and private routes.
However, I'd also like the params sent in the Authorization: header to be available in the route controller. For this I've been using Compojure's site function in compojure.handler, which puts variables in the :params dictionary of the request (see for example Missing form parameters in Compojure POST request)
However I can't seem to get both 401 authorization and the parameters to work at the same time. If I try this:
; this is a stripped down sample case:
(defn authenticated?
"authenticate the request"
[service-name token]
(:valid (model/valid-service-and-token service-name token)))
(defroutes token-routes
(POST "/api/:service-name/phone" request (add-phone request)))
(defroutes public-routes
controller/routes
; match anything in the static dir at resources/public
(route/resources "/"))
(defroutes authviasms-handler
public-routes
(auth/wrap-basic-authentication
controller/token-routes authenticated?))
;handler is compojure.handler
(def application (handler/site authviasms-handler))
(defn start [port]
(ring/run-jetty (var application) {:port (or port 8000) :join? false}))
the authorization variables are accessible in the authenticated? function, but not in the routes.
Obviously, this isn't a very general example, but I feel like I'm really spinning my wheels and just making changes at random to the middleware order and hoping things work. I'd appreciate some help both for my specific example, and learning more about how to wrap middlewares to make things execute correctly.
Thanks,
Kevin
AFAIK, ring.middleware.basic-authentication doesn't read anything from the :params in request and ring.core.request/site doesn't put anything authentication-related there either.
But in any ring handler, you can still access the headers. Something like:
(GET "/hello"
{params :params headers :headers}
(str "your authentication is " (headers "authentication")
" and you provided " params))
Similarly, you can use that to write your own middleware to put authentication-related stuff in params, if you really want to.