Fundamentals 9 min read

29 Minimal Python Code Snippets for API Automation Testing

This article presents 29 concise Python code examples covering common API automation tasks such as JSON conversion, file I/O, dictionary manipulation, request handling, data filtering, encryption, URL encoding, time formatting, exception handling, and regular expressions, each accompanied by clear output and commentary.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
29 Minimal Python Code Snippets for API Automation Testing

The article provides a collection of 29 minimal Python snippets useful for API automation testing, each with a brief explanation and sample output.

Example 1: JSON string to dict

import json
data = json.loads('{"key":"value"}')
print(data)

Example 2: Dict to JSON string

import json
json_str = json.dumps({"key": "value"}, ensure_ascii=False)
print(json_str)

Example 3: Read JSON file

import json
with open('file.json', 'w') as f:
    json.dump({"name": "test"}, f)
with open('file.json', 'r') as f:
    data = json.load(f)
print(data)

Example 4: Write dict to JSON file

import json
with open('file.json', 'w') as f:
    json.dump({"key": "value"}, f, ensure_ascii=False)

Example 5: Extract nested field

data = {"user": {"name": "张三"}}
name = data.get("user", {}).get("name")
print(name)

Example 6: Add new field

data = {"username": "admin"}
data["newKey"] = "newValue"
print(data)

Example 7: Delete field

data = {"key1": "val1", "key2": "val2"}
del data["key1"]
print(data)

Example 8: Check key existence

data = {"name": "Alice"}
print("name" in data)

Example 9: Iterate dictionary items

data = {"a": 1, "b": 2}
for key, value in data.items():
    print(key, value)

Example 10: Merge two dictionaries

dict1 = {"a": 1}
dict2 = {"b": 2}
merged = {**dict1, **dict2}
print(merged)

Example 11: Get default value

data = {"age": 25}
print(data.get("missing_key", "default_value"))

Example 12: Filter list

data = [{"name": "Tom", "age": 20}, {"name": "Jerry", "age": 15}]
filtered = [item for item in data if item['age'] > 18]
print(filtered)

Example 13: Compare two JSON objects (ignore order)

import json
d1 = {"a": 1, "b": 2}
d2 = {"b": 2, "a": 1}
print(json.dumps(d1, sort_keys=True) == json.dumps(d2, sort_keys=True))

Example 14: Output JSON sorted by keys

import json
data = {"b": 2, "a": 1, "c": 3}
sorted_json = json.dumps(data, sort_keys=True)
print(sorted_json)

Example 15: Validate status code

response_data = {"code": 200, "msg": "ok"}
if response_data.get("code") == 200:
    print("请求成功")

Example 16: Use token in request headers

import requests
token = "abc123"
headers = {"Authorization": f"Bearer {token}"}
print("请求头:", headers)

Example 17: jsonpath extraction

from jsonpath import jsonpath
data = {"store": {"book": [{"title": "Java 编程"}, {"title": "Python 自动化"}]}}
titles = jsonpath(data, "$.store.book[*].title")
print(titles)

Example 18: Convert Java‑style keys to Python‑style

def rename_keys(d):
    return {k.lower(): v for k, v in d.items()}
data = {"UserName": "Tom", "Age": "20"}
renamed = rename_keys(data)
print(renamed)

Example 19: Print JSON as table

from tabulate import tabulate
data = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 17}]
print(tabulate(data, headers="keys", tablefmt="grid"))

Example 20: Mock API response

import json
def mock_response():
    return json.dumps({"success": True})
print(mock_response())

Example 21: Response assertion

res = {"success": True}
assert res["success"] is True
print("断言通过")

Example 22: Simple SHA256 hashing

import hashlib
hash_obj = hashlib.sha256(b'Hello World')
print(hash_obj.hexdigest())

Example 23: URL encoding

from urllib.parse import quote
encoded = quote('http://example.com?param=你好')
print(encoded)

Example 24: URL decoding

from urllib.parse import unquote
decoded = unquote('http%3A//example.com%3Fparam%3D%E4%BD%A0%E5%A5%BD')
print(decoded)

Example 25: Time formatting

from datetime import datetime
formatted = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(formatted)

Example 26: Exception handling

try:
    result = 1 / 0
except Exception as e:
    print(f"出现错误:{e}")

Example 27: Regex matching

import re
matches = re.findall(r'\d+', '订单ID是123456,电话是13800138000')
print(matches)

Example 28: String concatenation

parts = ["接口", "自动化", "测试"]
result = "-".join(parts)
print(result)

Example 29: List deduplication

items = [1, 2, 2, 3, 4, 4, 5]
unique = list(set(items))
print(unique)

The collection demonstrates essential Python techniques for handling JSON, performing HTTP requests, processing data, encrypting information, and managing errors, making it a handy reference for developers writing automated API tests.

PythonAutomationJSONcode snippetsAPI testing
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.