![見出し画像](https://assets.st-note.com/production/uploads/images/46032509/rectangle_large_type_2_a4e7de53e8a6753aa7ae5637b311177e.png?width=1200)
犬好きのためのAPI+Pythonでの画像取得
みなさんこんにちはこんばんは。SKと申します。
みなさんは犬好きですか?僕は好きです。可愛いし、癒し。
ちなみに実家で飼ってる犬には懐かれてません。
犬画像API
見つけてしまいました。可愛い犬の画像を取得できるAPIです。
Webブラウザなどで以下のURLを叩いてみてください。ランダムな犬の画像のURLを返してくれます。
https://dog.ceo/api/breeds/image/random
以下のようなJSONが返ってきます。
{"message":"https:\/\/images.dog.ceo\/breeds\/beagle\/n02088364_11130.jpg","status":"success"}
上記messageにあるURLをWebブラウザでアクセスすると犬の画像が見れます。
Original dataset taken from the the Stanford Dogs Dataset.
とあり、こちらのデータセットを利用しているようです。
Pythonでの画像取得
さて、いちいちWebブラウザで見るのも面倒だと思うので、Python3.6で
(1) APIを実行
(2) 返ってきたJSONを処理
(3) 画像URLから画像表示
をやってみようと思います。
◆ソースコード◆
from PIL import Image
import io
import requests
url = "https://dog.ceo/api/breeds/image/random"
# (1)APIを実行
responce = requests.get(url)
# (2) 返ってきたJSONを処理
jsonObj= responce.json()
ImageUrl= jsonObj['message']
strImageURL = str(ImageUrl)
# (3) 画像URLから画像表示
file =io.BytesIO(requests.get(strImageURL).content)
img = Image.open(file)
img.show()
◆実行結果◆
以上です。
いいなと思ったら応援しよう!
![S.K](https://assets.st-note.com/production/uploads/images/36091824/profile_655d8afc4bdbcbd492ba3112d55bed49.jpeg?width=600&crop=1:1,smart)