プロジェクトの目標
APIからSAPの品目データを取得する処理を模擬し、ALVレポートのように表示します。
ワークフローを順に作りながら、APIについて学びます。
ステップ1:最初のAPIスクリプトを実行する
import requests
url = "https://jsonplaceholder.typicode.com/posts"
response = requests.get(url)
data = response.json()
print(data[:2])
表示される内容
[
{ "userId": 1, "id": 1, "title": "...", "body": "..." },
{ "userId": 1, "id": 2, "title": "...", "body": "..." }
]
ステップ2:ABAPの考え方で捉える
| ABAP | Python/API |
|---|---|
| SELECT * | requests.get() |
| 内部テーブル | data(リスト) |
| ワークエリア | row(辞書) |
ステップ3:SAP ODataの模擬レスポンス
{
"d": {
"results": [
{"Material":"1001","MaterialType":"FERT"},
{"Material":"1002","MaterialType":"HALB"}
]
}
}
対応関係を確認する
内部テーブル = results
行 = {"Material":"1001","MaterialType":"FERT"}
行 = {"Material":"1001","MaterialType":"FERT"}
ステップ4:データを取り出す
records = data["d"]["results"]
for row in records:
print(row["Material"])
想定される出力
1001
1002
1002
ステップ5:表に変換する
import pandas as pd
df = pd.json_normalize(records)
print(df.head())
想定される表
Material | MaterialType
1001 | FERT
1002 | HALB
1001 | FERT
1002 | HALB
ステップ6:小さなSAP風レポートを作る
import requests
import pandas as pd
url = "https://jsonplaceholder.typicode.com/posts"
response = requests.get(url)
data = response.json()
df = pd.DataFrame(data)
print(df[["id","title"]].head())
想定される出力
id | title
1 | ...
2 | ...
1 | ...
2 | ...
ステップ7:エンジニアの視点でデバッグする
print(response.status_code)
print(response.text)
何か失敗したら、まず未加工のレスポンスを必ず出力してください。
確認
- 初めてAPIを呼び出した
- JSONをABAPの考え方に対応付けた
- APIのデータから表を作った
- シンプルなレポートを作った