4
1

More than 1 year has passed since last update.

【API】今すぐ遊べるAPI 5個!

Last updated at Posted at 2022-12-06

ezgif.com-gif-maker.gif

こんにちは。AMBL株式会社のR&D部のエイドリアンです。この記事はAMBLアドベントカレンダー2022の記事です。

APIとは

APIとは「Application Program Interface(アプリケーション プログラミング インターフェイス)」の略称で、2つのアプリケーションやソフトウェア同士が情報をやり取りする際に使用される窓口です。

APIの種類は複数ありますが、ここではインターネットを経由するWeb APIを紹介します。

パラメータ

APIにおいては基本的にPath Parameter(パスパラメータ)とQuery Parameter(クエリパラメータ)の2種類が存在します。どちらもURIで送信するものです。

例えば、Google検索の場合

https://www.google.com/search?q=hello

searchはパスパラメータであり、qがクエリパラメータになります。
つまり、?の前はパス、?の後はクエリです。

APIのやり取り

ここで簡単なAPIのやり取りを紹介したいと思います。

まず、APIの一般的な処理フローは下記の図で表しています。
Clientとはプログラミング言語に依存しない、インターネットにアクセスできるアプリケーションを指します。

ではPythonを用いて簡単にやり取りを見てみましょう!

app.py
# 必要なライブラリーをImportする
import requests

# 情報の依頼先アドレス
trivia_base_url = "https://opentdb.com/api.php"

# 依頼を送信する
res = requests.get(trivia_base_url)
print(res)
>>> <Response [200]>
# クエリパラメータに問題数を追加する
new_url = f"{trivia_base_url}?amount=2"

# 情報を依頼する
res = requests.get(new_url)
print(res)
>>> <Response [200]>

# データを読み込む
print(res.json())
>>> {'response_code': 0, 'results': [{...}]}

これで、Client(Pythonを実行するところ)がWeb service(The Trivia API)に対してデータ(クイズ問題)の依頼を送信し、Web serviceがDatabaseからデータをClientへ提供する、といった流れになります。

今すぐ使えるAPIx5

それでは、API Keyなど必要としない、ただただURLを"叩く"だけデータを取得できるAPIを紹介したいと思います。

1. The Trivia API

8000問以上の4択、◯✕問題を簡単に取得できるAPIです。
カテゴリーは{地理、一般知識、音楽}などの10科目があり、
難易度は{簡単、普通、困難}の3つが選ばれます。

クイズアプリケーションを試してみたい時にビッタリです!

quiz.py
url = "https://the-trivia-api.com/api/questions?categories=science&limit=2&difficulty=medium"
res = requests.get(url)
res.json()

>>> 
[{'category': 'Science',
  'correctAnswer': 'Shells and molluscs',
  'difficulty': 'medium',
  'id': '622a1c377cc59eab6f950572',
  'incorrectAnswers': ['The Weather',
                       'The origin and spread of diseases',
                       'Sex'],
  'question': 'What is conchology the study of?',
  'regions': [],
  'tags': ['science', 'words'],
  'type': 'Multiple Choice'},
 {'category': 'Science',
  'correctAnswer': 'Jack the Ripper and the crimes associated with him',
  'difficulty': 'medium',
  'id': '622a1c377cc59eab6f95049b',
  'incorrectAnswers': ['illness', 'gross and disgusting things', 'nerves'],
  'question': 'What is Ripperology the study of?',
  'regions': [],
  'tags': ['science'],
  'type': 'Multiple Choice'}]


2. TheCatApi🐱

「猫派?犬派?可愛いからいいじゃん!」と思います!
可愛いネコの写真を提供してくれるAPIです。ぜひ仕事
の合間にネコを写真を見てリラックスしましょう!

cat.py
cats_url = "https://api.thecatapi.com/v1/images/search"
res = requests.get(cats_url)
cat = res.json()[0]
cat

>>> 
{'id': 'MTcxNDE1Ng',
 'url': 'https://cdn2.thecatapi.com/images/MTcxNDE1Ng.jpg',
 'width': 4288,
 'height': 2848}
cat.py
with open('cat.jpg','wb') as f:
    f.write(requests.get(cat["url"]).content)

Image("cat.jpg")

にゃ〜
ネコ

3. TheDogApi🐕

「俺は犬派なんだ!!!」と思ったキミに紹介します。
可愛いイヌの写真を手軽に取得できるAPIです。

3のTheCatApiと同じ仕様となっております。

dog.py
url = "https://api.thedogapi.com/v1/images/search"
res = requests.get(url)
dog = res.json()[0]
dog

>>> 
{'id': 'kuvpGHCzm',
 'url': 'https://cdn2.thedogapi.com/images/kuvpGHCzm.jpg',
 'width': 1024,
 'height': 814}
dog.py
with open('dog.jpg','wb') as f:
    f.write(requests.get(dog["url"]).content)

Image("dog.jpg")

ナデナデを頼む...
イヌ

4. TheCocktailDB🍸

可愛いネコやイヌちゃんを眺めるにはカクテルが必要(?)です!
TheCocktailDBはカクテルに関する情報を提供してくれます。
検索、原材料、手順などの情報を取得できます。

cocktail.py
base_url = "https://www.thecocktaildb.com/api/json/v1/1"

# パスパラメータ
path_param = "search.php"

# クエリパラメータ
query_param = "s=margarita"

# データ取得
res = requests.get(f"{base_url}/{path_param}?{query_param}")
res.json()

>>> 
{'drinks': [{'idDrink': '11007',
   'strDrink': 'Margarita',
   'strDrinkAlternate': None,
   'strTags': 'IBA,ContemporaryClassic',
   'strVideo': None,
   'strCategory': 'Ordinary Drink',
   'strIBA': 'Contemporary Classics',
   'strAlcoholic': 'Alcoholic',
   'strGlass': 'Cocktail glass',
   'strInstructions': 'Rub the rim of the glass with the lime slice to make the salt stick to it. Take care to moisten only the outer rim and sprinkle the salt on it. The salt should present to the lips of the imbiber and never mix into the cocktail. Shake the other ingredients with ice, then carefully pour into the glass.',
   'strInstructionsES': None,
   'strInstructionsDE': 'Reiben Sie den Rand des Glases mit der Limettenscheibe, damit das Salz daran haftet. Achten Sie darauf, dass nur der äußere Rand angefeuchtet wird und streuen Sie das Salz darauf. Das Salz sollte sich auf den Lippen des Genießers befinden und niemals in den Cocktail einmischen. Die anderen Zutaten mit Eis schütteln und vorsichtig in das Glas geben.',
   'strInstructionsFR': None,
   'strInstructionsIT': 'Strofina il bordo del bicchiere con la fetta di lime per far aderire il sale.\r\nAvere cura di inumidire solo il bordo esterno e cospargere di sale.\r\nIl sale dovrebbe presentarsi alle labbra del bevitore e non mescolarsi mai al cocktail.\r\nShakerare gli altri ingredienti con ghiaccio, quindi versarli delicatamente nel bicchiere.',
   'strInstructionsZH-HANS': None,
   'strInstructionsZH-HANT': None,
   'strDrinkThumb': 'https://www.thecocktaildb.com/images/media/drink/5noda61589575158.jpg',
   'strIngredient1': 'Tequila',
   'strIngredient2': 'Triple sec',
   'strIngredient3': 'Lime juice',
   'strIngredient4': 'Salt',
   'strIngredient5': None,
   'strIngredient6': None,
   'strIngredient7': None,
   'strIngredient8': None,
   'strIngredient9': None,
   'strIngredient10': None,
   'strIngredient11': None,
   'strIngredient12': None,
   'strIngredient13': None,
   'strIngredient14': None,
   'strIngredient15': None,
   'strMeasure1': '1 1/2 oz ',
   'strMeasure2': '1/2 oz ',
   'strMeasure3': '1 oz ',
   'strMeasure4': None,
   'strMeasure5': None,
   'strMeasure6': None,
   'strMeasure7': None,
   'strMeasure8': None,
   'strMeasure9': None,
   'strMeasure10': None,
   'strMeasure11': None,
   'strMeasure12': None,
   'strMeasure13': None,
   'strMeasure14': None,
   'strMeasure15': None,
   'strImageSource': 'https://commons.wikimedia.org/wiki/File:Klassiche_Margarita.jpg',
   'strImageAttribution': 'Cocktailmarler',
   'strCreativeCommonsConfirmed': 'Yes',
   'dateModified': '2015-08-18 14:42:59'},
    ...,
    ]
}

5. Weather Forecast API☁️

イヌとお散歩に出かける時は天気予報が大事です!
雨が降るかどうかをチェックしてからお散歩しましょう!

Weather Forecast APIでは簡単に天気情報を取得できます!

weather.py
weather_url = "https://api.open-meteo.com/v1/"

path_param = "forecast"

query_param_1 = "latitude=35.69"
query_param_2 = "longitude=139.69"
query_param_3 = "hourly=temperature_2m,rain"

# クエリパラメータが複数存在する場合は「&」で連結する
res = requests.get(f"{weather_url}/{path_param}?{query_param_1}&{query_param_2}&{query_param_3}")
res.json()

>>> 
{'latitude': 35.7,
 'longitude': 139.6875,
 'generationtime_ms': 0.3019571304321289,
 'utc_offset_seconds': 0,
 'timezone': 'GMT',
 'timezone_abbreviation': 'GMT',
 'elevation': 43.0,
 'hourly_units': {'time': 'iso8601', 'temperature_2m': '°C', 'rain': 'mm'},
 'hourly': {'time': [...],
  'temperature_2m': [...],
  'rain': [...]
  }
}

まとめ

今回はAPIとトーケンや申請などを要しないAPIをいくつか紹介しました。
作りたいアプリに合わせて、公開されているAPIを活用すれば開発スピード
が一気に上がるでしょう。

また、今回は5つのAPIしか紹介していないが、すぐ使える他の分野や用途の
APIがたくさんあります。気になる方はぜひ下記のGithub Repoを参照してください!

今度はこれらのAPIを用いて、簡単にアプリを作成しデプロイしていきたいと思います!
それでは👋!

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1