Skip to content

Instantly share code, notes, and snippets.

@kolharsam
Last active March 3, 2021 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kolharsam/21c79daea3e6823a06c846cade042f1a to your computer and use it in GitHub Desktop.
Save kolharsam/21c79daea3e6823a06c846cade042f1a to your computer and use it in GitHub Desktop.
REST API in Clojure - Example for Hasura Actions
;; This app was made using the template provided via leiningen.
;; use lein new compojure <project-name> to create a similar project
;; This content's of this file can directly go into `handler.clj`
;; All necessary documentation can be found in these sources:
;; https://github.com/weavejester/compojure/wiki
;; https://github.com/ring-clojure/ring/wiki
(ns rest-hasura-api.handler
(:require [compojure.core :refer :all]
[compojure.route :as route]
[ring.middleware.defaults :refer [wrap-defaults site-defaults]]
[ring.middleware.json :refer [wrap-json-body wrap-json-response]]
[ring.util.response :refer [response]]
[clojure.string :as str]))
;; defining the smallest data-store, for the demo
(def contacts (atom []))
(defn create-contact [first-name last-name phone-number]
{:first_name (str/capitalize first-name)
:last_name (str/capitalize last-name)
:phone phone-number})
;; ! used to indicate that this function mutates data
(defn add-new-contact! [first-name last-name phone-number]
(swap! contacts conj (create-contact first-name last-name phone-number)))
;; In case you didn't know, these are not real.
(add-new-contact! "Steph" "curry" 108423893)
(add-new-contact! "LeBron" "james" 23232224)
;; Defining the API Handlers
;; AKA: the place could dispatch your business logic
(defn get-all-contacts-handler [req]
(response {:data @contacts}))
(defn add-contact-handler [req]
(let [{:keys [first_name last_name phone_number]} (:input (:body req))]
(add-new-contact first_name last_name phone_number))
(response {:id (count @contacts)}))
;; Defining the allowed routes for the API
(defroutes app-routes
(GET "/" [] (wrap-json-response get-all-contacts-handler))
(POST "/" [] (wrap-json-response add-contact-handler))
(route/not-found "Route not found!"))
;; Defining the app
;; This can be executed using `lein ring server`
;; and give it a spin from localhost:3000!
(def app
(->
;; This setting is not advisable for a production environment
(wrap-defaults app-routes (assoc-in site-defaults [:security :anti-forgery] false))
;; This is an optional setting
(wrap-json-body {:keywords? true})))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment