0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flask note. / はてな 記事取得

Posted at

やり方


はてな APIデベロッパーページ APIキー取得
Note APIデベロッパーページ APIキー取得

code



oath認証 やり方


request : ログインデータ取得 フォーム送信処理

from flask import Flask,request

app = Flask(__name__)

@app.route('/login', methods=['POST'])
def login():
    username = request.form.get('username')  # フォームの値を取得
    password = request.form.get('password')
    return f"ログインユーザー: {username}, パスワード: {password}"

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


request APIデータ受け取り

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/api/data', methods=['POST'])
def get_data():
    data = request.json  # JSONデータを取得
    return jsonify({"受け取ったデータ": data})

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


response エラーメッセージを変えれる

from flask import Flask, jsonify, make_response

app = Flask(__name__)

@app.route('/custom_response')
def custom_response():
    response_data = {"message": "成功!", "status": "OK"}
    response = make_response(jsonify(response_data), 200)  # 200: 成功
    response.headers["Content-Type"] = "application/json"  # ヘッダー指定
    return response

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

response エラーになったら、エラーメッセージページにジャンプさせる

@app.route('/error')
def error():
    response = jsonify({"error": "データが見つかりません"})
    return response, 404  # 404エラーを返す

response request

requestオブジェクト : サーバー  クライアント情報 保存

responseオブジェクト : クライアント  サーバー 情報 保存

HTTPリクエスト

# GET /users - ユーザーの一覧を取得
# POST /users - 新しいユーザーを作成
# GET /users/<id> - 特定のユーザーを取得
# PUT /users/<id> - 特定のユーザーを更新
# DELETE /users/<id> - 特定のユーザーを削除

作ったURL 動いてるかテスト

curl -X POST http://localhost:5000/submit \
     -H "Content-Type: application/json" \
     -d '{"name": "Bob", "age": 25}'

天気APIから気温データのみ取り出したい (レスポンス解析)

import requests

# APIのURL(仮のAPIキーを使用)
url = "https://api.openweathermap.org/data/2.5/weather"
params = {
    "q": "Tokyo",  # 都市名
    "appid": "YOUR_API_KEY",  # APIキーをここに入れる
    "units": "metric"  # 摂氏(°C)で取得
}

# APIリクエストを送信
response = requests.get(url, params=params)

# レスポンス解析
if response.status_code == 200:  # 成功した場合
    data = response.json()  # JSONデータを取得
    temp = data["main"]["temp"]  # 気温を取得
    print(f"東京の気温: {temp}°C")
else:  # エラー処理
    print(f"エラー発生: {response.status_code}, {response.text}")

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?