from http.client import HTTPConnection
import json


def request(method, path, data=None):
    connection = HTTPConnection("127.0.0.1", 8000, timeout=5)
    body = None
    headers = {}
    if data is not None:
        body = json.dumps(data, ensure_ascii=False).encode("utf-8")
        headers["Content-Type"] = "application/json"
    try:
        connection.request(method, path, body=body, headers=headers)
        response = connection.getresponse()
        result = response.read().decode("utf-8")
        print(method, path, "->", response.status, response.reason)
        print("Content-Type:", response.getheader("Content-Type"))
        print(result)
        return response.status, response.getheader("Location")
    finally:
        connection.close()


def main():
    status, location = request("POST", "/api/messages", {"text": "Pythonから送信"})
    if status == 201 and location is not None:
        request("GET", location)
    request("GET", "/api/messages")
    request("GET", "/missing")


if __name__ == "__main__":
    main()
