0

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!

Jack Gee
  • 136
  • 6
  • Did you try it with the same spelling of `Authorization`? – Dave Newton Oct 17 '22 at 20:10
  • @DaveNewton, ah yes sorry that was a typo - I have tried that – Jack Gee Oct 17 '22 at 20:11
  • In the bash syntax `'{"name":"test"}'`, bash isn't being given something it's expected to parse as a dictionary/map type before handoff to curl; instead, everything except those outer single quotes is _an exact string_ to send over the wire. The expectation for your Clojure code is the same: the content of your body isn't parsed by Clojure locally, it's sent over the wire exactly as-is and parsed by the remote server. – Charles Duffy Oct 17 '22 at 20:22

1 Answers1

3

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)})
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441