SnIPPETsX

SnIPPETsX › def test_api(url, method="GET", data=None, headers={})

def test_api(url, method="GET", data=None, headers={})

Python · updated Oct 14, 2026 · 44 lines

main.py

import urllib.request
import urllib.parse
import json

def test_api(url, method="GET", data=None, headers={}):
    try:
        if data:
            data = json.dumps(data).encode("utf-8")

        req = urllib.request.Request(
            url=url,
            data=data,
            headers=headers,
            method=method
        )

        with urllib.request.urlopen(req) as response:
            res_data = response.read().decode("utf-8")
            status_code = response.getcode()

            print(f"Status Code: {status_code}")
            print("Response:")
            print(res_data)

    except urllib.error.HTTPError as e:
        print(f"HTTP Error: {e.code}")
        print(e.read().decode())

    except urllib.error.URLError as e:
        print(f"URL Error: {e.reason}")


# 🔥 Example usage

# GET request
test_api("https://jsonplaceholder.typicode.com/posts/1")

# POST request
test_api(
    "https://jsonplaceholder.typicode.com/posts",
    method="POST",
    data={"title": "test", "body": "hello", "userId": 1},
    headers={"Content-Type": "application/json"}
)

Run this Python snippet

Open this snippet on SnIPPETsX to run the Python code in your browser, edit it together with others in real time, or fork it into your own copy. No install or account is needed.