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?

REST API Operationの基本

Last updated at Posted at 2025-04-20

REST API(Representational State Transfer)は、Webサービスとクライアント間でデータの送受信を行う際に広く使われている設計スタイルです。

REST APIの主要操作と違い

メソッド 説明 主な用途
GET データの取得 リソースの情報取得
POST 新しいデータの作成 新規リソースの追加
PUT データ全体の更新 既存リソースの完全な上書き
PATCH データの一部更新 リソースの部分的な更新
DELETE データの削除 リソースの削除

PythonによるREST API操作サンプル(requests使用)

まずはライブラリのインストール:

pip install requests

1. GET(取得)

import requests

url = 'https://jsonplaceholder.typicode.com/posts/1'
response = requests.get(url)

print(response.status_code)
print(response.json())

2. POST(新規作成)

url = 'https://jsonplaceholder.typicode.com/posts'
data = {
    'title': '新しい投稿',
    'body': 'これはサンプルの投稿本文です。',
    'userId': 1
}
response = requests.post(url, json=data)

print(response.status_code)
print(response.json())

3. PUT(全体更新)

url = 'https://jsonplaceholder.typicode.com/posts/1'
updated_data = {
    'id': 1,
    'title': '更新されたタイトル',
    'body': '更新された本文です。',
    'userId': 1
}
response = requests.put(url, json=updated_data)

print(response.status_code)
print(response.json())

4. PATCH(一部更新)

url = 'https://jsonplaceholder.typicode.com/posts/1'
partial_update = {
    'title': 'タイトルのみ更新'
}
response = requests.patch(url, json=partial_update)

print(response.status_code)
print(response.json())

5. DELETE(削除)

url = 'https://jsonplaceholder.typicode.com/posts/1'
response = requests.delete(url)

print(response.status_code)  # 通常は204(No Content)が返る

補足:PUTとPATCHの違い

項目 PUT PATCH
更新範囲 リソース全体 指定した一部のみ
送信データ 全フィールドを含める必要がある 更新したいフィールドのみでOK
用途の一例 全体的な書き換え(例:投稿全体更新) 一部修正(例:タイトルのみ変更など)

補足:typicode

typicode(正式には JSONPlaceholder) は、APIの学習やテストに使える無料のモックAPIサービスです。

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?