Bess
Bess

Reputation: 476

Compojure - Making HTTP call when route is hit

I am new to Closure and trying out Ring and Compojure. I want to make an HTTP request when a user hits a route (to a third party API) and then use that response data in my HTML template . I know this is likely a very easy thing to pull off - but being new to language and the syntax I am a bit lost.

 (defroutes app
    (GET "/" request
      ; try to GET "https://third-party-api" and do something with the response
    )
 )

What is the best practice and format for this - It's possible I am missing some key concepts in routing / response expectations here. Thanks very much!

Upvotes: 1

Views: 282

Answers (1)

Psetmaj
Psetmaj

Reputation: 437

I recommend the library clj-http for making http requests. You can find many examples on the linked page for how to use it.

Your usage of clj-http may look something like this:

(ns my-app.core
  (:require [clj-http.client :as client]))

...

(defn get-api-data []
  (:body (client/get "https://third-party-api" {:as :json})))

Note that clj-http.client/get returns a map that includes things like the response status code and headers.

If you use the {:as :json} option to coerce the response into json, make sure to include cheshire in your project.clj (assuming you're using leiningen)

:dependencies [...
               [clj-http "3.9.0"]
               [cheshire "5.8.0"]]

Documentation on ring requests and responses can be found here.

A large portion of the power in ring is its concept of middlewares. Most of the "nice" features that you'd want in an http server can be found as middlewares in ring itself or other libraries. For example, if you want all of your responses to be serialized as json by default, you might use ring-json


If you're trying to get something "that just works", up and running quickly with a few examples present, Luminus may be useful. It's a curated collection of libraries that prove useful for most webservers. (Disclaimer: I've only minimally experimented with Luminus, opting to understand more explicitly my dependencies).

I personally use compojure sweet at the start of most of my webservice projects, it includes some nicer routing features (including path params) and a swagger UI for testing your endpoints. Unfortunately, it uses its own form of destructuring and includes a bit more magic and "just needing to know" than I'd like, but I'm yet to find something that works better for me.

Upvotes: 4

Related Questions