美文网首页Clojure极简教程
Clojure basic tutorial - REST AP

Clojure basic tutorial - REST AP

作者: c8ac4dad76db | 来源:发表于2020-03-08 14:31 被阅读0次

    Add two library: clj-http cheshire .

    project.clj:

    (defproject http-request "0.1.0-SNAPSHOT"
      :description "FIXME: write description"
      :url "http://example.com/FIXME"
      :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0"
                :url  "https://www.eclipse.org/legal/epl-2.0/"}
      :dependencies [[org.clojure/clojure "1.10.0"]
                     [clj-http "3.10.0"]
                     [cheshire "5.10.0"]]
      :main ^:skip-aot http-request.core
      :target-path "target/%s"
      :profiles {:uberjar {:aot :all}})
    
    (ns http-request.core
      (:gen-class)
      (:require [clj-http.client :as client]
                [cheshire.core :as cheshire]
                [clojure.string :as str]))
    
    (defn -main
      "I don't do a whole lot ... yet."
      [& args]
      (println "Hello, World!"))
    
    (defn get-planet
      ([]
       (client/get "https://swapi.co/api/planets/"))
      ([n]
       (client/get (str "https://swapi.co/api/planets/" n "/"))))
    
    (def response
      (get-planet 1))
    
    (def responses
      (get-planet))
    
    (def body
      (cheshire/parse-string (:body response) true))
    
    (def bodys
      (cheshire/parse-string (:body responses) true))
    
    (comment
      (client/get (str "https://swapi.co/api/planets/" "1" "/")))
    
    (def planets (:results bodys))
    
    (def get-names
      (map #(:name %) planets))
    
    (def get-names-uppercase
      (map #(str/upper-case (:name %)) planets))
    
    (def get-climate
      (map #(:climate %) planets))
    
    (def get-residents-count
      (map #(count (:residents %)) planets))
    
    (def get-residents-sum
      (reduce + get-residents-count))
    
    (def name-residents
      (reduce #(let [name      (:name %2)
                     residents (count (:residents %2))]
                 (cons [name residents] %1))
    
              []
              planets))
    
    (def name-residents-map
      (reduce #(let [name      (:name %2)
                     residents (count (:residents %2))]
                 (assoc %1 name residents))
              {}
              planets))
    
    

    相关文章

      网友评论

        本文标题:Clojure basic tutorial - REST AP

        本文链接:https://www.haomeiwen.com/subject/tfbddhtx.html