2017-07-25 107 views
0

我可以讀取郵寄請求的RAW JSON。但不知道我是否正確地做到了這一點?Clojure,Compojure:閱讀郵政請求RAW Json

CODE

(ns clojure-dauble-business-api.core 
    (:require [compojure.api.sweet :refer :all] 
      [ring.util.http-response :refer :all] 
      [clojure-dauble-business-api.logic :as logic] 
      [clojure.tools.logging :as log] 
      [clojure-dauble-business-api.domain.artwork]) 
    (:import [clojure_dauble_business_api.domain.artwork Artwork])) 

(defapi app 
    (GET "/hello" [] 
    (log/info "Function begins from here") 
    (ok {:artwork (logic/artwork-id 10)})) 
    (POST "/create" params 
    (log/info "Create - Function begins from here and body" (:name (:artwork (:params params)))) 
    (ok {:artwork (logic/create-city (:name (:artwork (:params params))))}))) 

RAW的JSON POST請求

{ 
    "artwork": { 
    "id": 10, 
    "name": "DEFAULT" 
    } 
} 

使用這條線(:name (:artwork (:params params)))抓取從上述原始JSON 「名稱」 的值。

如果我不是正確的方式,請指導我什麼是正確的方式?

回答

3

如果我正確理解你的問題,它看起來像你問是否有一個更「適當」的方式來獲取:name括號嵌套較少尷尬?

在嵌套關聯結構檢索值,如:name(哈希地圖),您可以使用get-in

(get-in params [:params :artwork :name]) 

這是整潔,更容易用較少的嵌套閱讀(左到右),但嘗試獲取值也是一種更安全的方法,因爲如果get-in在鍵序列中找不到密鑰,則get-in將返回nil

1

您似乎正在使用compojure-api,其中有助手輸入&輸出強制。您可以使用:body:body-params鍵來定義模型和驗證,請參閱文檔以瞭解詳細信息。

這裏的一個樣品虛設API與Leiningen

lein new compojure-api artwork 
cd artwork 

設置src/artwork/handler.clj內容到:

(ns artwork.handler 
    (:require [compojure.api.sweet :refer :all] 
      [ring.util.http-response :refer :all] 
      [schema.core :as s])) 

;; define a Schema for validation 
(s/defschema Artwork 
    {:id Long 
    :name String}) 

;; dummy ring-api with swagger-docs 
(def app 
    (api 
    {:swagger 
    {:ui "/" 
     :spec "/swagger.json" 
     :data {:info {:title "Artwork" 
        :description "Lovely artwork api"} 
      :tags [{:name "api", :description "some apis"}]}}} 

    (context "/api" [] 
     :tags ["api"] 

     ;; endpoint with Schema coercion 
     (POST "/create" [] 
     :return Artwork 
     :body [body Artwork] 
     :summary "creates artwork" 
     (ok body))))) 

並運行在命令行lein ring server。您應該看到帶有一個端點的swagger-ui,以客戶端定義的格式(JSON,EDN或Transit)使用Artwork

希望這會有所幫助。