Merge pull request #592 from metosin/openapi-fixes

misc. fixes for openapi3 support
This commit is contained in:
Joel Kaasinen 2023-03-15 17:47:44 +02:00 committed by GitHub
commit 8bf4b5c6a6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 203 additions and 197 deletions

View file

@ -39,148 +39,148 @@
(def app
(http/ring-handler
(http/router
[["/swagger.json"
{:get {:no-doc true
:swagger {:info {:title "my-api"
:description "swagger-docs with reitit-http"
:version "0.0.1"}
;; used in /secure APIs below
:securityDefinitions {"auth" {:type :apiKey
:in :header
:name "Example-Api-Key"}}}
:handler (swagger/create-swagger-handler)}}]
["/openapi.json"
{:get {:no-doc true
:openapi {:info {:title "my-api"
:description "openap-docs with reitit-http"
:version "0.0.1"}
;; used in /secure APIs below
:components {:securitySchemes {"auth" {:type :apiKey
:in :header
:name "Example-Api-Key"}}}}
:handler (openapi/create-openapi-handler)}}]
(http/router
[["/swagger.json"
{:get {:no-doc true
:swagger {:info {:title "my-api"
:description "swagger-docs with reitit-http"
:version "0.0.1"}
;; used in /secure APIs below
:securityDefinitions {"auth" {:type :apiKey
:in :header
:name "Example-Api-Key"}}}
:handler (swagger/create-swagger-handler)}}]
["/openapi.json"
{:get {:no-doc true
:openapi {:info {:title "my-api"
:description "openapi3-docs with reitit-http"
:version "0.0.1"}
;; used in /secure APIs below
:components {:securitySchemes {"auth" {:type :apiKey
:in :header
:name "Example-Api-Key"}}}}
:handler (openapi/create-openapi-handler)}}]
["/files"
{:tags ["files"]}
["/files"
{:tags ["files"]}
["/upload"
{:post {:summary "upload a file"
:parameters {:multipart {:file multipart/temp-file-part}}
:responses {200 {:body {:name string?, :size int?}}}
:handler (fn [{{{:keys [file]} :multipart} :parameters}]
{:status 200
:body {:name (:filename file)
:size (:size file)}})}}]
["/upload"
{:post {:summary "upload a file"
:parameters {:multipart {:file multipart/temp-file-part}}
:responses {200 {:body {:name string?, :size int?}}}
:handler (fn [{{{:keys [file]} :multipart} :parameters}]
{:status 200
:body {:name (:filename file)
:size (:size file)}})}}]
["/download"
{:get {:summary "downloads a file"
:swagger {:produces ["image/png"]}
:handler (fn [_]
["/download"
{:get {:summary "downloads a file"
:swagger {:produces ["image/png"]}
:handler (fn [_]
{:status 200
:headers {"Content-Type" "image/png"}
:body (io/input-stream
(io/resource "reitit.png"))})}}]]
["/async"
{:get {:tags ["async"]
:summary "fetches random users asynchronously over the internet"
:parameters {:query (s/keys :req-un [::results] :opt-un [::seed])}
:responses {200 {:body any?}}
:handler (fn [{{{:keys [seed results]} :query} :parameters}]
(d/chain
(aleph/get
"https://randomuser.me/api/"
{:query-params {:seed seed, :results results}})
:body
(partial m/decode "application/json")
:results
(fn [results]
{:status 200
:headers {"Content-Type" "image/png"}
:body (io/input-stream
(io/resource "reitit.png"))})}}]]
:body results})))}}]
["/async"
{:get {:tags ["async"]
:summary "fetches random users asynchronously over the internet"
:parameters {:query (s/keys :req-un [::results] :opt-un [::seed])}
:responses {200 {:body any?}}
:handler (fn [{{{:keys [seed results]} :query} :parameters}]
(d/chain
(aleph/get
"https://randomuser.me/api/"
{:query-params {:seed seed, :results results}})
:body
(partial m/decode "application/json")
:results
(fn [results]
{:status 200
:body results})))}}]
["/math"
{:tags ["math"]}
["/math"
{:tags ["math"]}
["/plus"
{:get {:summary "plus with data-spec query parameters"
:parameters {:query {:x int?, :y int?}}
:responses {200 {:body {:total pos-int?}}}
:handler (fn [{{{:keys [x y]} :query} :parameters}]
{:status 200
:body {:total (+ x y)}})}
:post {:summary "plus with data-spec body parameters"
:parameters {:body {:x int?, :y int?}}
:responses {200 {:body {:total int?}}}
:handler (fn [{{{:keys [x y]} :body} :parameters}]
{:status 200
:body {:total (+ x y)}})}}]
["/plus"
{:get {:summary "plus with data-spec query parameters"
:parameters {:query {:x int?, :y int?}}
:responses {200 {:body {:total pos-int?}}}
:handler (fn [{{{:keys [x y]} :query} :parameters}]
["/minus"
{:get {:summary "minus with clojure.spec query parameters"
:parameters {:query (s/keys :req-un [::x ::y])}
:responses {200 {:body (s/keys :req-un [::total])}}
:handler (fn [{{{:keys [x y]} :query} :parameters}]
{:status 200
:body {:total (- x y)}})}
:post {:summary "minus with clojure.spec body parameters"
:parameters {:body (s/keys :req-un [::x ::y])}
:responses {200 {:body (s/keys :req-un [::total])}}
:handler (fn [{{{:keys [x y]} :body} :parameters}]
{:status 200
:body {:total (- x y)}})}}]]
["/secure"
{:tags ["secure"]
:openapi {:security [{"auth" []}]}
:swagger {:security [{"auth" []}]}}
["/get"
{:get {:summary "endpoint authenticated with a header"
:responses {200 {:body {:secret string?}}
401 {:body {:error string?}}}
:handler (fn [request]
;; In a real app authentication would be handled by middleware
(if (= "secret" (get-in request [:headers "example-api-key"]))
{:status 200
:body {:total (+ x y)}})}
:post {:summary "plus with data-spec body parameters"
:parameters {:body {:x int?, :y int?}}
:responses {200 {:body {:total int?}}}
:handler (fn [{{{:keys [x y]} :body} :parameters}]
{:status 200
:body {:total (+ x y)}})}}]
:body {:secret "I am a marmot"}}
{:status 401
:body {:error "unauthorized"}}))}}]]]
["/minus"
{:get {:summary "minus with clojure.spec query parameters"
:parameters {:query (s/keys :req-un [::x ::y])}
:responses {200 {:body (s/keys :req-un [::total])}}
:handler (fn [{{{:keys [x y]} :query} :parameters}]
{:status 200
:body {:total (- x y)}})}
:post {:summary "minus with clojure.spec body parameters"
:parameters {:body (s/keys :req-un [::x ::y])}
:responses {200 {:body (s/keys :req-un [::total])}}
:handler (fn [{{{:keys [x y]} :body} :parameters}]
{:status 200
:body {:total (- x y)}})}}]]
["/secure"
{:tags ["secure"]
:openapi {:security [{"auth" []}]}
:swagger {:security [{"auth" []}]}}
["/get"
{:get {:summary "endpoint authenticated with a header"
:responses {200 {:body {:secret string?}}
401 {:body {:error string?}}}
:handler (fn [request]
;; In a real app authentication would be handled by middleware
(if (= "secret" (get-in request [:headers "example-api-key"]))
{:status 200
:body {:secret "I am a marmot"}}
{:status 401
:body {:error "unauthorized"}}))}}]]]
{;:reitit.interceptor/transform dev/print-context-diffs ;; pretty context diffs
;;:validate spec/validate ;; enable spec validation for route data
;;:reitit.spec/wrap spell/closed ;; strict top-level validation
:exception pretty/exception
:data {:coercion reitit.coercion.spec/coercion
:muuntaja m/instance
:interceptors [;; swagger feature
swagger/swagger-feature
;; openapi feature
openapi/openapi-feature
;; query-params & form-params
(parameters/parameters-interceptor)
;; content-negotiation
(muuntaja/format-negotiate-interceptor)
;; encoding response body
(muuntaja/format-response-interceptor)
;; exception handling
(exception/exception-interceptor)
;; decoding request body
(muuntaja/format-request-interceptor)
;; coercing response bodys
(coercion/coerce-response-interceptor)
;; coercing request parameters
(coercion/coerce-request-interceptor)
;; multipart
(multipart/multipart-interceptor)]}})
(ring/routes
(swagger-ui/create-swagger-ui-handler
{:path "/"
:config {:validatorUrl nil
:urls [{:name "swagger", :url "swagger.json"}
{:name "openapi", :url "openapi.json"}]
:urls.primaryName "openapi"
:operationsSorter "alpha"}})
(ring/create-default-handler))
{:executor sieppari/executor}))
{;:reitit.interceptor/transform dev/print-context-diffs ;; pretty context diffs
;;:validate spec/validate ;; enable spec validation for route data
;;:reitit.spec/wrap spell/closed ;; strict top-level validation
:exception pretty/exception
:data {:coercion reitit.coercion.spec/coercion
:muuntaja m/instance
:interceptors [;; swagger feature
swagger/swagger-feature
;; openapi feature
openapi/openapi-feature
;; query-params & form-params
(parameters/parameters-interceptor)
;; content-negotiation
(muuntaja/format-negotiate-interceptor)
;; encoding response body
(muuntaja/format-response-interceptor)
;; exception handling
(exception/exception-interceptor)
;; decoding request body
(muuntaja/format-request-interceptor)
;; coercing response bodys
(coercion/coerce-response-interceptor)
;; coercing request parameters
(coercion/coerce-request-interceptor)
;; multipart
(multipart/multipart-interceptor)]}})
(ring/routes
(swagger-ui/create-swagger-ui-handler
{:path "/"
:config {:validatorUrl nil
:urls [{:name "swagger", :url "swagger.json"}
{:name "openapi", :url "openapi.json"}]
:urls.primaryName "openapi"
:operationsSorter "alpha"}})
(ring/create-default-handler))
{:executor sieppari/executor}))
(defn start []
(jetty/run-jetty #'app {:port 3000, :join? false, :async true})

View file

@ -107,40 +107,39 @@
(if (:schema $)
(update $ :schema #(coercion/-compile-model this % nil))
$))]))})))
:openapi (openapi/openapi-spec
(merge
(when (seq (dissoc parameters :body :request))
{::openapi/parameters
(into (empty parameters)
(for [[k v] (dissoc parameters :body :request)]
[k (coercion/-compile-model this v nil)]))})
(when (:body parameters)
{:requestBody (openapi/openapi-spec
{::openapi/content (zipmap content-types (repeat (coercion/-compile-model this (:body parameters) nil)))})})
(when (:request parameters)
{:requestBody (openapi/openapi-spec
{::openapi/content (merge
(when-let [default (get-in parameters [:request :body])]
(zipmap content-types (repeat (coercion/-compile-model this default nil))))
(into {}
(for [[format model] (:content (:request parameters))]
[format (coercion/-compile-model this model nil)])))})})
(when responses
{:responses
(into
(empty responses)
(for [[k {:keys [body content] :as response}] responses]
[k (merge
(select-keys response [:description])
(when (or body content)
(openapi/openapi-spec
{::openapi/content (merge
(when body
(zipmap content-types (repeat (coercion/-compile-model this (:body response) nil))))
(when response
(into {}
(for [[format model] (:content response)]
[format (coercion/-compile-model this model nil)]))))})))]))})))
:openapi (merge
(when (seq (dissoc parameters :body :request))
(openapi/openapi-spec {::openapi/parameters
(into (empty parameters)
(for [[k v] (dissoc parameters :body :request)]
[k (coercion/-compile-model this v nil)]))}))
(when (:body parameters)
{:requestBody (openapi/openapi-spec
{::openapi/content (zipmap content-types (repeat (coercion/-compile-model this (:body parameters) nil)))})})
(when (:request parameters)
{:requestBody (openapi/openapi-spec
{::openapi/content (merge
(when-let [default (get-in parameters [:request :body])]
(zipmap content-types (repeat (coercion/-compile-model this default nil))))
(into {}
(for [[format model] (:content (:request parameters))]
[format (coercion/-compile-model this model nil)])))})})
(when responses
{:responses
(into
(empty responses)
(for [[k {:keys [body content] :as response}] responses]
[k (merge
(select-keys response [:description])
(when (or body content)
(openapi/openapi-spec
{::openapi/content (merge
(when body
(zipmap content-types (repeat (coercion/-compile-model this (:body response) nil))))
(when response
(into {}
(for [[format model] (:content response)]
[format (coercion/-compile-model this model nil)]))))})))]))}))
(throw
(ex-info
(str "Can't produce Spec apidocs for " specification)

View file

@ -408,20 +408,23 @@
(get-in [:paths "/parameters" :post :parameters])
normalize))))
(testing "body parameter"
(is (match? {:schema {:type "object"
:properties {:b {:type "string"}}
#_#_:additionalProperties false ;; not present for spec
:required ["b"]}}
(is (match? (merge {:type "object"
:properties {:b {:type "string"}}
:required ["b"]}
;; spec outputs open schemas
(when-not (#{#'spec/coercion} coercion)
{:additionalProperties false}))
(-> spec
(get-in [:paths "/parameters" :post :requestBody :content "application/json"])
(get-in [:paths "/parameters" :post :requestBody :content "application/json" :schema])
normalize))))
(testing "body response"
(is (match? {:schema {:type "object"
:properties {:ok {:type "string"}}
#_#_:additionalProperties false ;; not present for spec
:required ["ok"]}}
(is (match? (merge {:type "object"
:properties {:ok {:type "string"}}
:required ["ok"]}
(when-not (#{#'spec/coercion} coercion)
{:additionalProperties false}))
(-> spec
(get-in [:paths "/parameters" :post :responses 200 :content "application/json"])
(get-in [:paths "/parameters" :post :responses 200 :content "application/json" :schema])
normalize))))
(testing "spec is valid"
(is (nil? (validate spec))))))))
@ -458,34 +461,38 @@
app
:body)]
(testing "body parameter"
(is (match? {:schema {:type "object"
:properties {:b {:type "string"}}
#_#_:additionalProperties false ;; not present for spec
:required ["b"]}}
(is (match? (merge {:type "object"
:properties {:b {:type "string"}}
:required ["b"]}
(when-not (#{#'spec/coercion} coercion)
{:additionalProperties false}))
(-> spec
(get-in [:paths "/parameters" :post :requestBody :content "application/json"])
(get-in [:paths "/parameters" :post :requestBody :content "application/json" :schema])
normalize)))
(is (match? {:schema {:type "object"
:properties {:c {:type "string"}}
#_#_:additionalProperties false ;; not present for spec
:required ["c"]}}
(is (match? (merge {:type "object"
:properties {:c {:type "string"}}
:required ["c"]}
(when-not (#{#'spec/coercion} coercion)
{:additionalProperties false}))
(-> spec
(get-in [:paths "/parameters" :post :requestBody :content "application/edn"])
(get-in [:paths "/parameters" :post :requestBody :content "application/edn" :schema])
normalize))))
(testing "body response"
(is (match? {:schema {:type "object"
:properties {:ok {:type "string"}}
#_#_:additionalProperties false ;; not present for spec
:required ["ok"]}}
(is (match? (merge {:type "object"
:properties {:ok {:type "string"}}
:required ["ok"]}
(when-not (#{#'spec/coercion} coercion)
{:additionalProperties false}))
(-> spec
(get-in [:paths "/parameters" :post :responses 200 :content "application/json"])
(get-in [:paths "/parameters" :post :responses 200 :content "application/json" :schema])
normalize)))
(is (match? {:schema {:type "object"
:properties {:edn {:type "string"}}
#_#_:additionalProperties false ;; not present for spec
:required ["edn"]}}
(is (match? (merge {:type "object"
:properties {:edn {:type "string"}}
:required ["edn"]}
(when-not (#{#'spec/coercion} coercion)
{:additionalProperties false}))
(-> spec
(get-in [:paths "/parameters" :post :responses 200 :content "application/edn"])
(get-in [:paths "/parameters" :post :responses 200 :content "application/edn" :schema])
normalize))))
(testing "validation"
(let [query {:request-method :post