Search code examples
curlclojuregithub-apibabashka

Replicating curl command in babaska


I have the following curl command from the github api that I wish to replicate in babashka:

curl \
  -X POST \
  -H "Accept: application/json" \
  -H "Authorization: Bearer <YOUR-TOKEN>" \
  https://api.github.com/user/repos \
  -d '{"name":"test"}'

Currently, I have tried:

(ns bb-test
 (require [environ.core :refer [env]]
          [babashka.curl :as curl])

(def url "https://api.github.com/user/repos")
(def token (env :token))
(def headers {"Accept" "application/json" "Authorization" (str "Bearer " token)})
(def body "{'name:' 'test'}")

(curl/post url {:headers headers :body body})

I get back a 400 http status code. Any help appreciated!


Solution

  • In the bash example, you're sending a body with {"name":"test"} as the literal data sent over the wire to the server.

    With the babashka example, you're sending a body with {'name:' 'test'} as the literal data sent over the wire to the server.

    Only one of these things is valid JSON.

    The Clojure syntax to describe a literal string containing data {"name":"test"} is "{\"name\":\"test\"}", so the smallest change is to modify the line where you run def body:

    (def body "{\"name\":\"test\"}")
    

    Alternately, you can use a JSON library such as Cheshire to encode a native Clojure structure into a JSON string:

    (ns bb-test
     (require [environ.core :refer [env]]
              [cheshire.core :as json]
              [babashka.curl :as curl])
    
    (def url "https://api.github.com/user/repos")
    (def token (env :token))
    (def headers {"Accept" "application/json"
                  "Authorization" (str "Bearer " token)})
    (def body {"name" "test"})
    
    (curl/post url {:headers headers
                    :body (json/generate-string body)})