1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

📅【Python×Flask】日本の祝日APIを使ったWebアプリを作ってみた

Posted at

はじめに

こんにちは!今回は、日本の祝日APIを活用して、指定した年の祝日一覧を表示する簡単なWebアプリをPython(Flask)で作成してみました。

初心者でも理解しやすいように、コードの解説も交えて紹介していきます!


🔧 使用技術

  • Python 3.x
  • Flask
  • HTML/CSS(Jinjaテンプレート)
  • 日本の祝日API(holidays-jp

📌 アプリの概要

指定した年の祝日を日本の祝日APIから取得し、ブラウザ上で日付・曜日・祝日名を表として表示するWebアプリです。

実際の画面イメージ:

スクリーンショット 2025-08-09 0.11.06.png


🧑‍💻 Flaskアプリの実装

まずはPythonコードです。Flaskでルーティング・API取得・データ整形を行っています。

from flask import Flask, render_template, request
import requests
from datetime import datetime

app = Flask(__name__)

API_URL = "https://holidays-jp.github.io/api/v1/date.json"

@app.route('/', methods=['GET', 'POST'])
def index():
    holidays = None
    error = None
    selected_year = None
    if request.method == 'POST':
        selected_year = request.form.get('year')
        try:
            res = requests.get(API_URL)
            data = res.json()
            holidays = []
            days = ['','','','','','','']
            for d, name in data.items():
                if d.startswith(selected_year):
                    dt = datetime.strptime(d, '%Y-%m-%d')
                    weekday = days[(dt.weekday() + 1) % 7]
                    holidays.append({'date': d, 'name': name, 'weekday': weekday})
            holidays.sort(key=lambda x: x['date'])
        except Exception as e:
            error = f"API取得エラー: {e}"
    return render_template('holidays.html', holidays=holidays, error=error, selected_year=selected_year)

if __name__ == '__main__':
    app.run(debug=True)

🔍 解説ポイント

  • requests.get() でJSON形式の祝日データを取得
  • 指定年(例: 2025)の祝日のみを抽出
  • datetimeを使って曜日も算出(日〜土)

🖼️ HTMLテンプレート(holidays.html

Jinja2テンプレートで、データを表形式で表示します。

<!doctype html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>日本の祝日カレンダー</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="{{ url_for('static', filename='holidays.css') }}">
  </head>
  <body>
    <div class="container">
      <h1>日本の祝日カレンダー</h1>
      <form method="post" style="text-align:center; margin-bottom:1em;">
        <label for="year">年を選択:</label>
        <select name="year" id="year" required>
          {% for y in range(2016, 2026) %}
            <option value="{{ y }}" {% if selected_year==y|string %}selected{% endif %}>{{ y }}</option>
          {% endfor %}
        </select>
        <button type="submit">表示</button>
      </form>
      {% if error %}
        <div class="result"><p style="color:red;">{{ error }}</p></div>
      {% endif %}
      {% if holidays %}
        <table>
          <tr><th>日付・曜日</th><th>祝日名</th></tr>
          {% for h in holidays %}
          <tr>
            <td>{{ h.date }}({{ h.weekday }})</td>
            <td>{{ h.name }}</td>
          </tr>
          {% endfor %}
        </table>
      {% elif selected_year %}
        <p>祝日データがありません。</p>
      {% endif %}
    </div>
  </body>
</html>

🎨 CSS(holidays.css

見た目もきれいに整えています。背景グラデーション+柔らかいUI。

body {
  font-family: 'Roboto', sans-serif;
  background: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%);
  margin: 0;
  min-height: 100vh;
}
.container {
  max-width: 500px;
  margin: 3em auto;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.12);
  padding: 2em 2.5em 2em 2.5em;
}
h1 {
  text-align: center;
  color: #2196f3;
  margin-bottom: 1.5em;
}
/* 他は省略(記事では必要に応じて) */

✅ 実行方法

ターミナルで以下を実行するだけ!

python app.py

ブラウザで http://localhost:5000/ を開くとアプリが表示されます。


💡 補足:日本の祝日APIとは?

このアプリでは、holidays-jp.github.ioが提供する祝日一覧のJSONデータを利用しています。メンテナンスもしっかりしており、簡単に使えるのでとても便利です。


🚀 まとめ

今回のWebアプリでは以下の内容を学びました:

  • 外部APIの使い方(JSON取得)
  • FlaskによるWebフォームとテンプレート表示
  • 曜日の計算方法
  • HTML/CSSでのUI構築

🙋‍♀️ ご感想・フィードバック募集中!

この記事が役に立った!と思ったら「いいね」やコメントをぜひお願いします😊
わからない点や質問があれば、お気軽にどうぞ!

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?