1p
トップ > APIとは > 【プログラム事例】無料APIで何ができる?面白いアイデア

【プログラム事例】無料APIで何ができる?面白いアイデア

はじめに

このウェブサイトでは、天気予報アプリ、ランダム名言表示、画像検索、最新ニュース集約、映画情報の詳細を簡単にアクセスできます。天気予報アプリで地域ごとの気象情報を即座にチェックし、ランダム名言で心に響く言葉を探すことができます。また、画像検索で美しい写真を探し、最新のニュース集約で世界の出来事を把握。映画情報で最新作の詳細を確認できる便利なツールを提供します。

目次

  1. 無料APIを使った面白いプログラムアイデア
  2. 一般的なプログラムに関する用語と実行方法
  3. プログラム例
  4. 姉妹サイト

無料APIを使った面白いプログラムアイデア

天気予報アプリ
ランダムな名言表示アプリ
画像検索アプリ
ニュース集約アプリ
翻訳ツール
映画情報アプリ
書籍推薦アプリ
スポーツライブスコア
画像生成アプリ
ポエム生成ツール

一般的なプログラムに関する用語と実行方法

1. 必要なライブラリのインストール

プログラムの実行に必要な外部のパッケージやライブラリをインストールすることがよくあります。これにより、プログラムが特定の機能を持つことができます。例えば、データベース操作やAPI通信を行うライブラリ、ウェブ開発のフレームワークなどです。

一般的なインストール方法は、使用するプログラミング言語のパッケージマネージャを使用します。

2. バックエンドとフロントエンド

プログラムを開発する際に、主に2つの部分に分けて考えることがあります。それがバックエンド(サーバーサイド)とフロントエンド(クライアントサイド)です。

バックエンド

バックエンドは、データベースとの連携やAPIの呼び出し、ユーザーからのリクエストに応じたデータの処理などを担当します。一般的に、Webアプリケーションの「裏側」の部分を指します。バックエンドには以下の技術を使うことがよくあります:

フロントエンド

フロントエンドは、ユーザーが実際に操作する部分で、ブラウザで表示される画面のことを指します。フロントエンドは、HTML, CSS, JavaScriptなどを使って作られます。フロントエンドに使われる代表的な技術は次の通りです:

3. アプリケーションの実行方法

プログラムを作成した後、実際にそれを実行するための方法を学ぶことが重要です。実行方法はプログラムの種類や使用する環境によって異なりますが、以下は一般的な手順です:

具体的な実行方法は、使用する技術スタックによって異なりますが、例えば以下のコマンドで実行します:

4. まとめ

プログラムの実行には、必要なライブラリをインストールし、バックエンドとフロントエンドをそれぞれ開発した後、実行環境を整えることが重要です。開発環境が整えば、最終的にはウェブアプリケーションとして公開することができます。

プログラム例

天気予報アプリ

プログラム例

以下は、天気予報アプリの簡単なサンプルコードです。PythonのFlaskを使って、OpenWeatherMap APIから天気情報を取得し、HTMLページで表示する例です。

pip install flask requests
# app.py
import os
import requests
from flask import Flask, render_template, request

app = Flask(__name__)

# OpenWeatherMap APIキー(自分のAPIキーを取得して設定)
API_KEY = 'YOUR_API_KEY'  # 自分のAPIキーをここに設定

# 天気情報を取得する関数
def get_weather(city):
    base_url = "http://api.openweathermap.org/data/2.5/weather?"
    complete_url = f"{base_url}q={city}&appid={API_KEY}&units=metric&lang=ja"  # 温度は摂氏、言語は日本語
    response = requests.get(complete_url)
    data = response.json()

    if data["cod"] != "404":
        main = data["main"]
        weather = data["weather"][0]
        return {
            "city": city,
            "temperature": main["temp"],
            "pressure": main["pressure"],
            "humidity": main["humidity"],
            "description": weather["description"],
            "icon": weather["icon"]
        }
    else:
        return None

@app.route("/", methods=["GET", "POST"])
def index():
    weather_data = None
    if request.method == "POST":
        city = request.form.get("city")
        weather_data = get_weather(city)
    
    return render_template("index.html", weather_data=weather_data)

if __name__ == "__main__":
    app.run(debug=True)
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>天気予報アプリ</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin-top: 50px;
        }
        .weather-container {
            margin-top: 30px;
        }
        .weather-icon {
            width: 50px;
            height: 50px;
        }
        .weather-data {
            font-size: 18px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <h1>天気予報アプリ</h1>

    <form method="POST" action="/">
        <label for="city">都市名を入力してください:</label>
        <input type="text" id="city" name="city" required>
        <button type="submit">天気を確認</button>
    </form>

    {% raw %}{% if weather_data %}{% endraw %}
        <div class="weather-container">
            <h3>{{ weather_data.city }} の天気</h3>
            <img src="http://openweathermap.org/img/wn/{{ weather_data.icon }}.png" alt="天気アイコン" class="weather-icon">
            <div class="weather-data">気温: {{ weather_data.temperature }}°C</div>
            <div class="weather-data">湿度: {{ weather_data.humidity }}%</div>
            <div class="weather-data">気圧: {{ weather_data.pressure }} hPa</div>
            <div class="weather-data">天気: {{ weather_data.description }}</div>
        </div>
    {% raw %}{% elif weather_data is not none %}{% endraw %}
        <p>都市が見つかりませんでした。</p>
    {% raw %}{% endif %}{% endraw %}
</body>
</html>

ランダムな名言表示アプリ

プログラム例

以下に、ランダムな名言表示アプリを作成するためのサンプルコードを示します。このサンプルでは、JavaScript (React) を使用し、Quotable API を利用してランダムな名言を取得して表示するアプリを作成します。

npx create-react-app random-quote-app
cd random-quote-app
npm install axios
// src/App.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './App.css';

function App() {
  const [quote, setQuote] = useState(null);
  const [loading, setLoading] = useState(true);

  // ランダムな名言を取得する関数
  const fetchRandomQuote = async () => {
    setLoading(true);
    try {
      const response = await axios.get('https://api.quotable.io/random');
      setQuote(response.data);
    } catch (error) {
      console.error("名言の取得に失敗しました", error);
    } finally {
      setLoading(false);
    }
  };

  // 初回ロード時に名言を取得
  useEffect(() => {
    fetchRandomQuote();
  }, []);

  return (
<div className="App">
  <header className="App-header">
    <h1>ランダム名言アプリ</h1>
    {loading ? (
      <p>読み込み中...</p>
    ) : (
      <div className="quote-container">
        <p className="quote-text">"{quote.content}"</p>
        <p className="quote-author">- {quote.author}</p>
        <button onClick={fetchRandomQuote} className="quote-button">次の名言</button>
      </div>
    )}
  </header>
</div>
  );
}

export default App;
/* src/App.css */
.App {
  text-align: center;
  font-family: Arial, sans-serif;
  background: linear-gradient(to bottom, #ff7e5f, #feb47b);
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
}

.App-header {
  padding: 20px;
}

.quote-container {
  background-color: rgba(0, 0, 0, 0.6);
  padding: 20px;
  border-radius: 10px;
  max-width: 600px;
  margin: 0 auto;
}

.quote-text {
  font-size: 24px;
  font-style: italic;
}

.quote-author {
  font-size: 20px;
  margin-top: 10px;
}

.quote-button {
  background-color: #feb47b;
  color: #fff;
  padding: 10px 20px;
  font-size: 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-top: 20px;
}

.quote-button:hover {
  background-color: #ff7e5f;
}

画像検索アプリ

プログラム例

以下に、画像検索アプリを作成するためのサンプルコードを示します。このサンプルでは、Unsplash APIを使って、ユーザーが入力したキーワードに基づいて画像を検索し表示するReactアプリを作成します。

npx create-react-app image-search-app
cd image-search-app
npm install axios
// src/App.js
import React, { useState } from 'react';
import axios from 'axios';
import './App.css';

function App() {
  const [query, setQuery] = useState('');
  const [images, setImages] = useState([]);
  const [loading, setLoading] = useState(false);

  // Unsplash APIから画像を検索する関数
  const fetchImages = async () => {
    if (!query) return;
    setLoading(true);
    try {
      const response = await axios.get(`https://api.unsplash.com/search/photos`, {
        params: {
          query,
          client_id: 'YOUR_UNSPLASH_ACCESS_KEY', // ここに自分のAPIキーを入れてください
        },
      });
      setImages(response.data.results);
    } catch (error) {
      console.error("画像の取得に失敗しました", error);
    } finally {
      setLoading(false);
    }
  };

  // 入力されたキーワードで画像を検索する
  const handleSearch = (event) => {
    event.preventDefault();
    fetchImages();
  };

  return (
<div className="App">
  <h1>画像検索アプリ</h1>
  <form onSubmit={handleSearch}>
    <input
      type="text"
      placeholder="検索キーワードを入力"
      value={query}
      onChange={(e) => setQuery(e.target.value)}
    />
    <button type="submit">検索</button>
  </form>

  {loading && <p>読み込み中...</p>}

  <div className="image-gallery">
    {images.length > 0 &&
      images.map((image) => (
        <div key={image.id} className="image-card">
          <img
            src={image.urls.small}
            alt={image.alt_description}
            className="image-thumbnail"
          />
          <a
            href={image.urls.full}
            target="_blank"
            rel="noopener noreferrer"
            className="view-full-size"
          >
            フルサイズで表示
          </a>
          <p>撮影者: {image.user.name}</p>
          <a
            href={image.links.download}
            target="_blank"
            rel="noopener noreferrer"
            className="download-link"
          >
            ダウンロード
          </a>
        </div>
      ))}
  </div>
</div>
  );
}

export default App;
/* src/App.css */
.App {
  font-family: Arial, sans-serif;
  text-align: center;
  margin-top: 30px;
}

form {
  margin-bottom: 20px;
}

input {
  padding: 10px;
  font-size: 16px;
  width: 300px;
  border-radius: 5px;
}

button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 20px;
}

.image-card {
  background-color: #f4f4f4;
  padding: 15px;
  border-radius: 10px;
  max-width: 300px;
  text-align: left;
}

.image-thumbnail {
  width: 100%;
  height: auto;
  border-radius: 10px;
}

.view-full-size, .download-link {
  display: block;
  margin-top: 10px;
  color: #1e90ff;
  text-decoration: none;
}

.view-full-size:hover, .download-link:hover {
  text-decoration: underline;
}

.download-link {
  font-weight: bold;
}

このReactアプリでは、Unsplash APIを使って画像を検索し、ユーザーが検索したキーワードに基づいて関連する美しい画像を表示します。画像をクリックするとフルサイズで表示でき、ダウンロードリンクも提供しています。

ニュース集約アプリ

プログラム例

以下は、ニュース集約アプリを作成するためのサンプルコードです。このサンプルでは、NewsAPIを使用して、最新のニュースを取得し、ユーザーが関心のあるカテゴリーでニュースを表示するReactアプリを作成します。

// src/App.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './App.css';

function App() {
  const [news, setNews] = useState([]);
  const [categories, setCategories] = useState([
    'business', 'entertainment', 'health', 'science', 'sports', 'technology'
  ]);
  const [selectedCategory, setSelectedCategory] = useState('general');
  const [loading, setLoading] = useState(false);

  // ニュースを取得する関数
  const fetchNews = async (category) => {
    setLoading(true);
    try {
      const response = await axios.get('https://newsapi.org/v2/top-headlines', {
        params: {
          category: category,
          apiKey: 'YOUR_NEWSAPI_KEY', // ここに自分のNewsAPIキーを入力
        },
      });
      setNews(response.data.articles);
    } catch (error) {
      console.error("ニュースの取得に失敗しました", error);
    } finally {
      setLoading(false);
    }
  };

  // カテゴリ変更時にニュースを更新
  const handleCategoryChange = (event) => {
    setSelectedCategory(event.target.value);
    fetchNews(event.target.value);
  };

  // 初回ロード時にニュースを取得
  useEffect(() => {
    fetchNews(selectedCategory);
  }, [selectedCategory]);

  return (
<div className="App">
  <h1>ニュース集約アプリ</h1>

  <div>
    <label htmlFor="category">カテゴリを選択:</label>
    <select
      id="category"
      value={selectedCategory}
      onChange={handleCategoryChange}
    >
      <option value="general">一般</option>
      {categories.map((category) => (
        <option key={category} value={category}>
          {category.charAt(0).toUpperCase() + category.slice(1)}
        </option>
      ))}
    </select>
  </div>

  {loading ? (
    <p>読み込み中...</p>
  ) : (
    <div className="news-container">
      {news.length > 0 ? (
        news.map((article, index) => (
          <div key={index} className="news-card">
            <h3>{article.title}</h3>
            <p>{article.description}</p>
            <a href={article.url} target="_blank" rel="noopener noreferrer">
              詳細を読む
            </a>
          </div>
        ))
      ) : (
        <p>ニュースが見つかりませんでした。</p>
      )}
    </div>
  )}
</div>
  );
}

export default App;
/* src/App.css */
.App {
  font-family: Arial, sans-serif;
  text-align: center;
  margin-top: 30px;
}

h1 {
  font-size: 2em;
  margin-bottom: 20px;
}

label {
  font-size: 16px;
  margin-right: 10px;
}

select {
  padding: 8px;
  font-size: 16px;
  border-radius: 5px;
}

.news-container {
  margin-top: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.news-card {
  background-color: #f4f4f4;
  padding: 20px;
  margin: 10px;
  border-radius: 10px;
  max-width: 600px;
  width: 100%;
  text-align: left;
}

.news-card h3 {
  font-size: 1.2em;
  color: #333;
}

.news-card p {
  font-size: 1em;
  color: #555;
}

.news-card a {
  display: block;
  margin-top: 10px;
  color: #1e90ff;
  text-decoration: none;
}

.news-card a:hover {
  text-decoration: underline;
}

このReactアプリでは、NewsAPIを使用して、世界中の最新ニュースを集め、ユーザーが興味のあるカテゴリーを選択してニュースを表示することができます。カテゴリごとにニュースをフィルタリングする機能を提供し、詳細リンクを提供しています。

翻訳ツール

プログラム例

以下は、翻訳ツールを作成するためのサンプルコードです。このサンプルでは、LibreTranslate APIを使用して、ユーザーが入力したテキストを指定した言語に翻訳するアプリを作成します。バックエンドにはPythonのFlaskを使用し、フロントエンドにはHTML、CSS、JavaScriptを使用します。

pip install flask requests
# app.py
from flask import Flask, render_template, request, jsonify
import requests

app = Flask(__name__)

# 翻訳を実行する関数
def translate_text(text, target_lang):
    url = "https://libretranslate.com/translate"
    params = {
        "q": text,
        "source": "auto",  # 自動検出
        "target": target_lang,
        "format": "text",
    }
    response = requests.post(url, data=params)
    return response.json()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/translate', methods=['POST'])
def translate():
    text = request.form['text']
    target_lang = request.form['target_lang']
    translation = translate_text(text, target_lang)
    return jsonify(translation)

if __name__ == '__main__':
    app.run(debug=True)
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>翻訳ツール</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <div class="container">
        <h1>翻訳ツール</h1>
        <form id="translate-form">
            <textarea id="text" placeholder="翻訳したいテキストを入力" required></textarea><br><br>
            
            <label for="target_lang">翻訳先の言語を選択:</label>
            <select id="target_lang" required>
                <option value="en">英語</option>
                <option value="es">スペイン語</option>
                <option value="fr">フランス語</option>
                <option value="de">ドイツ語</option>
                <option value="ja">日本語</option>
                <option value="it">イタリア語</option>
                <option value="pt">ポルトガル語</option>
            </select><br><br>
            
            <button type="submit">翻訳</button>
        </form>
        
        <div id="translation-result">
            <h3>翻訳結果:</h3>
            <p id="translated-text"></p>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#translate-form').submit(function(event) {
                event.preventDefault();

                const text = $('#text').val();
                const targetLang = $('#target_lang').val();

                $.ajax({
                    url: '/translate',
                    type: 'POST',
                    data: {
                        text: text,
                        target_lang: targetLang
                    },
                    success: function(response) {
                        $('#translated-text').text(response.translatedText);
                    },
                    error: function() {
                        alert('翻訳に失敗しました。もう一度お試しください。');
                    }
                });
            });
        });
    </script>
</body>
</html>
/* static/style.css */
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f4f4f4;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

.container {
    background-color: white;
    padding: 30px;
    border-radius: 10px;
    box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
    text-align: center;
    width: 400px;
}

h1 {
    font-size: 2em;
    margin-bottom: 20px;
}

textarea {
    width: 100%;
    height: 150px;
    padding: 10px;
    font-size: 1em;
    border-radius: 5px;
    border: 1px solid #ddd;
    resize: none;
}

select {
    padding: 10px;
    font-size: 1em;
    border-radius: 5px;
    border: 1px solid #ddd;
}

button {
    padding: 10px 20px;
    font-size: 1.2em;
    margin-top: 20px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background-color: #45a049;
}

#translation-result {
    margin-top: 30px;
}

#translated-text {
    font-size: 1.2em;
    font-weight: bold;
    color: #333;
}

このアプリでは、LibreTranslate APIを使用して、ユーザーが入力したテキストを指定した言語に翻訳することができます。ユーザーインターフェースは簡単で、直感的に操作できるように設計されています。

映画情報アプリ

プログラム例

以下は、映画情報アプリのサンプルコードです。このサンプルでは、OMDb APIを使用して、映画タイトルや俳優名で検索し、映画の詳細情報(あらすじ、キャスト、公開日など)を表示するReactアプリを作成します。

npx create-react-app movie-info-app
cd movie-info-app
npm install axios
// src/App.js
import React, { useState } from 'react';
import axios from 'axios';
import './App.css';

function App() {
  const [movieTitle, setMovieTitle] = useState('');
  const [movieData, setMovieData] = useState(null);
  const [error, setError] = useState(null);

  // 映画情報を取得する関数
  const fetchMovieData = async () => {
    if (!movieTitle) return;

    const apiKey = 'YOUR_OMDB_API_KEY'; // ここに自分のOMDb APIキーを入力
    const url = `http://www.omdbapi.com/?t=${movieTitle}&apikey=${apiKey}`;

    try {
      const response = await axios.get(url);
      if (response.data.Response === 'True') {
        setMovieData(response.data);
        setError(null);
      } else {
        setError('映画が見つかりませんでした。');
        setMovieData(null);
      }
    } catch (err) {
      setError('エラーが発生しました。再度試してください。');
      setMovieData(null);
    }
  };

  const handleSearchChange = (event) => {
    setMovieTitle(event.target.value);
  };

  const handleSearchClick = () => {
    fetchMovieData();
  };

  return (
<div className="App">
  <h1>映画情報アプリ</h1>

  <div>
    <input
      type="text"
      placeholder="映画タイトルを入力"
      value={movieTitle}
      onChange={handleSearchChange}
    />
    <button onClick={handleSearchClick}>検索</button>
  </div>

  {error && <p className="error">{error}</p>}

  {movieData && (
    <div className="movie-info">
      <h2>{movieData.Title} ({movieData.Year})</h2>
      <p><strong>ジャンル:</strong> {movieData.Genre}</p>
      <p><strong>監督:</strong> {movieData.Director}</p>
      <p><strong>キャスト:</strong> {movieData.Actors}</p>
      <p><strong>あらすじ:</strong> {movieData.Plot}</p>
      <p><strong>評価:</strong> {movieData.imdbRating} / 10</p>
      <p><strong>公開日:</strong> {movieData.Released}</p>
      <img src={movieData.Poster} alt={movieData.Title} />
    </div>
  )}
</div>
  );
}

export default App;
/* src/App.css */
.App {
  font-family: Arial, sans-serif;
  text-align: center;
  margin-top: 30px;
}

h1 {
  font-size: 2em;
  margin-bottom: 20px;
}

input {
  padding: 10px;
  font-size: 1em;
  width: 300px;
  margin-right: 10px;
  border-radius: 5px;
  border: 1px solid #ddd;
}

button {
  padding: 10px 20px;
  font-size: 1em;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

.movie-info {
  margin-top: 30px;
  text-align: left;
  width: 80%;
  margin: 0 auto;
  padding: 20px;
  background-color: #f4f4f4;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.movie-info img {
  max-width: 200px;
  margin-top: 20px;
}

.error {
  color: red;
  font-weight: bold;
}

p {
  font-size: 1.2em;
  margin: 10px 0;
}

strong {
  font-weight: bold;
}

このアプリでは、OMDb APIを使用して映画情報を取得し、ユーザーが映画の詳細情報を簡単に確認できるようにしています。また、Reactを使用してインタラクティブなUIを作成しています。

書籍推薦アプリ

プログラム例

以下は、書籍推薦アプリのサンプルコードです。このサンプルでは、Google Books APIを使用して、ユーザーが入力した本のタイトルに基づいて関連する書籍をリストアップし、書籍の詳細情報(著者、出版社、レビューなど)を表示するアプリを作成します。フロントエンドにはReact、バックエンドにはPythonのFlaskを使用する方法を示します。

npx create-react-app book-recommendation-app
cd book-recommendation-app
npm install axios
# app.py
from flask import Flask, jsonify, request
import requests

app = Flask(__name__)

# Google Books APIを使用して書籍情報を取得する関数
def fetch_books(query):
    url = f'https://www.googleapis.com/books/v1/volumes?q={query}&maxResults=5'
    response = requests.get(url)
    return response.json()

@app.route('/api/search', methods=['GET'])
def search_books():
    query = request.args.get('query', '')
    if query:
        books_data = fetch_books(query)
        return jsonify(books_data)
    return jsonify({"error": "No query parameter provided"}), 400

if __name__ == '__main__':
    app.run(debug=True)
// src/App.js
import React, { useState } from 'react';
import axios from 'axios';
import './App.css';

function App() {
  const [query, setQuery] = useState('');
  const [books, setBooks] = useState([]);
  const [error, setError] = useState(null);

  const handleSearch = async () => {
    if (!query) return;

    try {
      const response = await axios.get(`http://localhost:5000/api/search?query=${query}`);
      setBooks(response.data.items || []);
      setError(null);
    } catch (err) {
      setError('書籍情報の取得に失敗しました。');
      setBooks([]);
    }
  };

  return (
<div className="App">
  <h1>書籍推薦アプリ</h1>
  <div>
    <input
      type="text"
      placeholder="本のタイトルを入力"
      value={query}
      onChange={(e) => setQuery(e.target.value)}
    />
    <button onClick={handleSearch}>検索</button>
  </div>

  {error && <p className="error">{error}</p>}

  {books.length > 0 && (
    <div className="book-list">
      {books.map((book, index) => (
        <div key={index} className="book-item">
          <h3>{book.volumeInfo.title}</h3>
          <p><strong>著者:</strong> {book.volumeInfo.authors ? book.volumeInfo.authors.join(', ') : '不明'}</p>
          <p><strong>出版社:</strong> {book.volumeInfo.publisher || '不明'}</p>
          <p><strong>説明:</strong> {book.volumeInfo.description ? book.volumeInfo.description : '説明はありません。'}</p>
          <a href={book.volumeInfo.infoLink} target="_blank" rel="noopener noreferrer">詳細情報</a>
          <img src={book.volumeInfo.imageLinks ? book.volumeInfo.imageLinks.thumbnail : '"} alt={book.volumeInfo.title} />
        </div>
      ))}
    </div>
  )}
</div>
  );
}

export default App;
/* src/App.css */
.App {
  font-family: Arial, sans-serif;
  text-align: center;
  margin-top: 30px;
}

h1 {
  font-size: 2em;
  margin-bottom: 20px;
}

input {
  padding: 10px;
  font-size: 1em;
  width: 300px;
  margin-right: 10px;
  border-radius: 5px;
  border: 1px solid #ddd;
}

button {
  padding: 10px 20px;
  font-size: 1em;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

.book-list {
  margin-top: 30px;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 20px;
}

.book-item {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  text-align: left;
}

.book-item img {
  width: 100px;
  height: auto;
  margin-top: 10px;
}

.error {
  color: red;
  font-weight: bold;
}

a {
  display: block;
  margin-top: 10px;
  color: #0066cc;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

このアプリでは、Google Books APIを使用して、ユーザーが入力した本のタイトルに関連する書籍情報を取得し、書籍の詳細情報を表示します。Reactを使用してインタラクティブなUIを作成し、Flaskをバックエンドに利用しています。

スポーツライブスコア

プログラム例

以下は、スポーツライブスコアアプリのサンプルコードです。このアプリでは、Football-Data APIを使用してサッカーや他のスポーツのライブスコアをリアルタイムで表示します。ユーザーが特定のチームや大会を選んで、最新の試合結果をチェックできるようにします。バックエンドにはFlaskを、フロントエンドにはJavaScript (React)を使用する例を示します。

pip install flask requests
npx create-react-app sports-live-score
cd sports-live-score
npm install axios
# app.py
from flask import Flask, jsonify, request
import requests

app = Flask(__name__)

# Football-Data APIのエンドポイントとAPIキー
API_KEY = 'YOUR_API_KEY'  # Football-Data APIのAPIキーをここに記入
BASE_URL = 'https://api.football-data.org/v4/'

# ライブスコアを取得する関数
def fetch_live_scores(competition_id=None):
    headers = {'X-Auth-Token': API_KEY}
    url = BASE_URL + 'matches'
    if competition_id:
        url += f'?competitions={competition_id}'  # 特定の大会のスコアを取得
    response = requests.get(url, headers=headers)
    return response.json()

@app.route('/api/live_scores', methods=['GET'])
def live_scores():
    competition_id = request.args.get('competition_id', None)
    scores_data = fetch_live_scores(competition_id)
    return jsonify(scores_data)

if __name__ == '__main__':
    app.run(debug=True)
// src/App.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './App.css';

function App() {
  const [scores, setScores] = useState([]);
  const [competition, setCompetition] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleCompetitionChange = (e) => {
    setCompetition(e.target.value);
  };

  const fetchScores = async () => {
    if (!competition) {
      setError('大会を選んでください');
      return;
    }
    setLoading(true);
    try {
      const response = await axios.get(`http://localhost:5000/api/live_scores?competition_id=${competition}`);
      setScores(response.data.matches || []);
      setError('');
    } catch (err) {
      setError('試合情報の取得に失敗しました');
    }
    setLoading(false);
  };

  useEffect(() => {
    // 最初のページ読み込み時にライブスコアを取得
    fetchScores();
  }, [competition]);

  return (
<div className="App">
  <h1>スポーツライブスコア</h1>
  <div>
    <select value={competition} onChange={handleCompetitionChange}>
      <option value="">大会を選択</option>
      <option value="PL">プレミアリーグ</option>
      <option value="BL1">ブンデスリーガ</option>
      <option value="PD">ラ・リーガ</option>
    </select>
    <button onClick={fetchScores}>スコアを取得</button>
  </div>

  {loading && <p>読み込み中...</p>}
  {error && <p className="error">{error}</p>}

  {scores.length > 0 && (
    <div className="score-list">
      {scores.map((match, index) => (
        <div key={index} className="score-item">
          <h3>{match.homeTeam.name} vs {match.awayTeam.name}</h3>
          <p>スコア: {match.score.fullTime.homeTeam} - {match.score.fullTime.awayTeam}</p>
          <p>{match.competition.name} - {match.season.startDate}</p>
        </div>
      ))}
    </div>
  )}
</div>
  );
}

export default App;
/* src/App.css */
.App {
  font-family: Arial, sans-serif;
  text-align: center;
  margin-top: 30px;
}

h1 {
  font-size: 2em;
  margin-bottom: 20px;
}

select {
  padding: 10px;
  font-size: 1em;
  margin-right: 10px;
  border-radius: 5px;
  border: 1px solid #ddd;
}

button {
  padding: 10px 20px;
  font-size: 1em;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

.score-list {
  margin-top: 30px;
}

.score-item {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  margin: 10px;
}

.error {
  color: red;
  font-weight: bold;
}

このアプリでは、Football-Data APIを使用してリアルタイムのスポーツライブスコアを表示するWebアプリを作成しています。Flaskをバックエンドに、Reactをフロントエンドに使用して、ユーザーが大会を選択し、ライブスコアを取得できるインターフェースを提供しています。

画像生成アプリ

プログラム例

以下は、画像生成アプリのサンプルコードです。このアプリは、DALL·E APIを使ってユーザーが入力したテキストに基づいて画像を生成します。バックエンドにはFlaskを使用し、生成した画像をユーザーがダウンロードできるようにします。また、エフェクトやフィルタを追加するオプションも提供できます。

pip install flask requests
# app.py
from flask import Flask, request, jsonify, send_file
import requests
import io

app = Flask(__name__)

# DALL·E APIのエンドポイントとAPIキー
API_KEY = 'YOUR_OPENAI_API_KEY'  # OpenAIのAPIキーをここに記入
BASE_URL = 'https://api.openai.com/v1/images/generations'

headers = {
    'Authorization': f'Bearer {API_KEY}',
    'Content-Type': 'application/json'
}

@app.route('/generate_image', methods=['POST'])
def generate_image():
    user_input = request.json.get('prompt')
    if not user_input:
        return jsonify({'error': 'プロンプトが必要です'}), 400

    # DALL·E APIへのリクエスト
    data = {
        'prompt': user_input,
        'n': 1,
        'size': '1024x1024'
    }

    response = requests.post(BASE_URL, headers=headers, json=data)

    if response.status_code == 200:
        image_url = response.json()['data'][0]['url']
        image_data = requests.get(image_url).content

        # 生成した画像をメモリ上に保存し、ダウンロードできるようにする
        return send_file(io.BytesIO(image_data), mimetype='image/png', as_attachment=True, download_name='generated_image.png')

    else:
        return jsonify({'error': '画像の生成に失敗しました'}), 500

if __name__ == '__main__':
    app.run(debug=True)
// src/App.js
import React, { useState } from 'react';
import axios from 'axios';
import './App.css';

function App() {
  const [prompt, setPrompt] = useState('');
  const [imageUrl, setImageUrl] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleInputChange = (e) => {
    setPrompt(e.target.value);
  };

  const generateImage = async () => {
    if (!prompt) {
      setError('プロンプトを入力してください');
      return;
    }
    setLoading(true);
    setError('');

    try {
      const response = await axios.post('http://localhost:5000/generate_image', { prompt });
      setImageUrl(URL.createObjectURL(response.data));  // 生成された画像をURLとして取得
      setError('');
    } catch (err) {
      setError('画像の生成に失敗しました');
    }
    setLoading(false);
  };

  return (
<div className="App">
  <h1>画像生成アプリ</h1>
  <textarea
    value={prompt}
    onChange={handleInputChange}
    placeholder="画像を生成したいテキストを入力"
  />
  <button onClick={generateImage}>画像を生成</button>

  {loading && <p>読み込み中...</p>}
  {error && <p className="error">{error}</p>}

  {imageUrl && (
    <div>
      <h2>生成された画像</h2>
      <img src={imageUrl} alt="Generated" className="generated-image" />
      <a href={imageUrl} download="generated_image.png">画像をダウンロード</a>
    </div>
  )}
</div>
  );
}

export default App;
/* src/App.css */
.App {
  font-family: Arial, sans-serif;
  text-align: center;
  margin-top: 30px;
}

h1 {
  font-size: 2em;
  margin-bottom: 20px;
}

textarea {
  width: 80%;
  height: 100px;
  padding: 10px;
  font-size: 1em;
  margin: 10px 0;
  border-radius: 5px;
  border: 1px solid #ddd;
}

button {
  padding: 10px 20px;
  font-size: 1em;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

.generated-image {
  max-width: 100%;
  height: auto;
  margin-top: 20px;
}

.error {
  color: red;
  font-weight: bold;
}

このアプリでは、DALL·E APIを使用して、ユーザーが入力したテキストに基づいて画像を生成するWebアプリを作成しています。Flaskをバックエンドに、Reactをフロントエンドに使用して、ユーザーが入力したプロンプトに対応する画像を生成し、表示・ダウンロードできるインターフェースを提供しています。

ポエム生成ツール

プログラム例

以下は、ポエム生成ツールのサンプルコードです。このツールは、PoetryDB APIを使ってユーザーが入力したテーマに基づいてポエムを生成します。バックエンドにはFlaskを使用し、フロントエンドにはHTMLとJavaScriptを使用して、生成されたポエムを表示します。

pip install flask requests
# app.py
from flask import Flask, request, jsonify
import requests

app = Flask(__name__)

# PoetryDB APIのエンドポイント
BASE_URL = 'https://poetrydb.org/'

@app.route('/generate_poem', methods=['POST'])
def generate_poem():
    theme = request.json.get('theme')
    if not theme:
        return jsonify({'error': 'テーマが必要です'}), 400

    # PoetryDB APIにリクエストを送る
    url = f'{BASE_URL}title/{theme}'
    response = requests.get(url)

    if response.status_code == 200 and response.json():
        poems = response.json()
        poem_text = poems[0]['lines']  # 最初のポエムの行を取得
        return jsonify({'poem': poem_text})

    return jsonify({'error': 'ポエムの生成に失敗しました'}), 500

if __name__ == '__main__':
    app.run(debug=True)
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ポエム生成ツール</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin-top: 50px;
        }

        textarea {
            width: 80%;
            height: 50px;
            padding: 10px;
            font-size: 1em;
            margin: 10px 0;
            border-radius: 5px;
            border: 1px solid #ddd;
        }

        button {
            padding: 10px 20px;
            font-size: 1em;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        button:hover {
            background-color: #45a049;
        }

        .poem {
            margin-top: 30px;
            font-size: 1.2em;
            white-space: pre-line;
            color: #555;
        }

        .error {
            color: red;
            font-weight: bold;
        }
    </style>
</head>
<body>

    <h1>ポエム生成ツール</h1>
    <textarea id="theme" placeholder="ポエムのテーマを入力してください"></textarea><br>
    <button onclick="generatePoem()">ポエムを生成</button>

    <div id="result" class="poem"></div>
    <div id="error" class="error"></div>

    <script>
        function generatePoem() {
            const theme = document.getElementById("theme").value;
            if (!theme) {
                document.getElementById("error").textContent = "テーマを入力してください";
                return;
            }

            document.getElementById("error").textContent = "";
            document.getElementById("result").textContent = "生成中...";

            fetch('http://localhost:5000/generate_poem', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ theme: theme }),
            })
            .then(response => response.json())
            .then(data => {
                if (data.poem) {
                    document.getElementById("result").textContent = data.poem.join('\n');
                } else {
                    document.getElementById("result").textContent = "ポエムを生成できませんでした";
                }
            })
            .catch(error => {
                document.getElementById("error").textContent = "エラーが発生しました";
                document.getElementById("result").textContent = "";
            });
        }
    </script>

</body>
</html>

このアプリでは、PoetryDB APIを使用して、ユーザーが入力したテーマに基づいてポエムを生成します。Flaskをバックエンドに使用し、HTMLとJavaScriptで作成したフロントエンドでユーザーインターフェースを構築しています。

姉妹サイト

【プログラム事例】API連携とは?わかりやすく 【API一覧】無料/有料、キーの必要、特徴を解説 【プログラム事例】無料APIで何ができる?面白いアイデア 無料X(Twitter)APIでのプログラミング事例 ChatGPT APIのプログラミング活用方法(無料と有料の違い、OpenAI)

AI使用

このサイトは、一部のコンテンツに生成AIを使用しています。

免責事項・著作権表示

情報が古かったり、間違っていることなどによる損害の責任は負いかねますので、ご了承ください。

Copyright (C) SUZ45. All Rights Reserved.