Отправить JSON через HTTP POST
Отправляет JSON из строки или файла и показывает код, заголовки и ответ сервера.
Что делает скрипт
Скрипт собирает POST-запрос с Content-Type application/json, проверяет корректность JSON до отправки и умеет добавить авторизацию через переменную окружения. Ответ печатается как JSON или текст, тело можно сохранить отдельно. Таймаут и дополнительные заголовки настраиваются.
- Отправляйте данные только на собственный сервер или тестовый эндпоинт.
Быстрый старт
python http_post.py http://127.0.0.1:8000/api/echo --data '{"name": "demo"}'
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python http_post.py http://127.0.0.1:8000/api/echo --file payload.jsonpython http_post.py https://example.com/api --data '{"ok": true}' --header 'X-Demo: 1'
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
http_post.py
#!/usr/bin/env python3
"""HTTP POST с JSON-телом."""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
def header_pair(value: str) -> tuple[str, str]:
if ":" not in value:
raise argparse.ArgumentTypeError("Заголовок должен быть в формате 'Name: value'")
name, text = value.split(":", 1)
return name.strip(), text.strip()
def main() -> int:
parser = argparse.ArgumentParser(description="Отправить JSON через POST")
parser.add_argument("url", help="Адрес эндпоинта")
parser.add_argument("--data", help="JSON-строка")
parser.add_argument("--file", type=Path, help="Файл с JSON")
parser.add_argument("--header", action="append", type=header_pair, default=[], metavar="NAME:VALUE")
parser.add_argument("--timeout", type=float, default=15.0)
parser.add_argument("--output", type=Path, help="Сохранить ответ")
args = parser.parse_args()
if bool(args.data) == bool(args.file):
parser.error("Укажите ровно один источник: --data или --file")
if args.file:
if not args.file.is_file():
parser.error(f"Файл не найден: {args.file}")
text = args.file.read_text(encoding="utf-8")
else:
text = args.data or ""
try:
payload = json.loads(text)
except json.JSONDecodeError as error:
parser.error(f"Некорректный JSON: {error}")
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
headers = {
"Content-Type": "application/json; charset=utf-8",
"Accept": "application/json, */*;q=0.8",
"User-Agent": "popovdev-scriptdock/1.0",
}
for name, value in args.header:
headers[name] = value
token = os.environ.get("API_TOKEN", "")
if token:
headers.setdefault("Authorization", f"Bearer {token}")
request = Request(args.url, data=body, headers=headers, method="POST")
try:
with urlopen(request, timeout=args.timeout) as response:
status = response.status
reason = response.reason
answer = response.read(2_000_000)
content_type = response.headers.get("Content-Type", "")
except HTTPError as error:
status = error.code
reason = error.reason
answer = error.read(2_000_000)
content_type = error.headers.get("Content-Type", "") if error.headers else ""
except URLError as error:
print(f"Не удалось подключиться: {error.reason}")
return 2
print(f"Статус: {status} {reason}")
print(f"Отправлено: {len(body)} байт")
print(f"Content-Type ответа: {content_type or 'не указан'}")
if args.output:
args.output.write_bytes(answer)
print(f"Сохранено: {args.output}")
text_answer = answer.decode("utf-8", errors="replace")
if "json" in content_type.lower():
try:
print(json.dumps(json.loads(text_answer), ensure_ascii=False, indent=2)[:8000])
except json.JSONDecodeError:
print(text_answer[:2000])
else:
print(text_answer[:2000])
return 0 if status < 400 else 1
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.