2  Webservice Python

2.1 Method Summary with Python (requests)

HTTP Method requests Function Purpose Response Codes (Typical Success)
GET requests.get() Retrieve resource/data 200 OK
POST requests.post() Create a new resource 201 Created
PUT requests.put() Update existing resource 200 OK
DELETE requests.delete() Delete resource 200 OK, 204 No Content

This structure provides a clear, practical way of interacting with RESTful APIs through Python.

2.2 GET Request (Retrieve Data)

import requests

response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
response
<Response [200]>
response.json()
{'userId': 1,
 'id': 1,
 'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
 'body': 'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto'}

2.3 POST Request (Send Data)

import requests

payload = {
    "title": "Hello World",
    "body": "This is my first API request!",
    "userId": 1
}

response = requests.post(
    "https://jsonplaceholder.typicode.com/posts",
    json=payload
)
if response.status_code == 201:  # 201 Created
    data = response.json()
    print("Created:", data)
else:
    print("Error:", response.status_code)
Created: {'title': 'Hello World', 'body': 'This is my first API request!', 'userId': 1, 'id': 101}

2.4 PUT Request (Update Data)

import requests

updated_payload = {
    "title": "Updated Title",
    "body": "Updated body content",
    "userId": 1
}

response = requests.put(
    "https://jsonplaceholder.typicode.com/posts/1",
    json=updated_payload
)
if response.status_code == 200:
    data = response.json()
    print("Updated:", data)
else:
    print("Error:", response.status_code)
Updated: {'title': 'Updated Title', 'body': 'Updated body content', 'userId': 1, 'id': 1}

2.5 DELETE Request (Remove Data)

import requests

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

if response.status_code == 200 or response.status_code == 204:
    print("Deleted successfully.")
else:
    print("Error:", response.status_code)
Deleted successfully.