1. Why do you need self-built tools?
When Postman becomes bloated, when we need to quickly verify an API without opening a browser, or when teams need to customize specific features, using Python's self-built HTTP debugging tools becomes an elegant choice. This article will use 300 lines of code to implement core functions, taking into account both practicality and maintainability.
2. Core functional design
Request sending: Support GET/POST/PUT/DELETE and other methods
Parameter management: Query Params, Form-data, JSON Body
Response parsing: Automatic formatting of JSON/XML, display status codes and time-consuming
History: Save the last 100 request records
Environment variables: Support .env file configuration basic URL
3. Technical selection
Server: Flask (lightweight and simple) + requests (request send)
Data storage: JSON file (record request history)
Environment configuration: python-dotenv (.env file support)
Interactive interface: Rich library (terminal beautification)
4. Step-by-step implementation
Step 1: Build the basic framework
from flask import Flask, request, jsonify import requests from import Console from import Panel import json import os from dotenv import load_dotenv app = Flask(__name__) console = Console() load_dotenv() # Loading environment variables
Step 2: Implement request forwarding logic
@('/api/proxy', methods=['POST']) def proxy(): # parse request parameters target_url = ('url') method = ('method', 'GET') headers = ('headers', {}) data = ('data') # Send a request try: if method == 'GET': resp = (target_url, headers=headers, params=data) elif method == 'POST': resp = (target_url, headers=headers, json=data) # Other methods are similar to processing... # Record request save_request_history({ 'url': target_url, 'method': method, 'status': resp.status_code, 'time': .total_seconds() }) return format_response(resp) except Exception as e: return jsonify({'error': str(e)}), 500
Step 3: Response formatting processing
def format_response(resp): content_type = ('Content-Type', '') if 'application/json' in content_type: try: pretty_json = ((), indent=2, ensure_ascii=False) return Panel(pretty_json, title=f"[bold green]Status: {resp.status_code}") except: return Panel(, title=f"[bold yellow]Raw Response") elif 'xml' in content_type: return Panel(, title=f"[bold blue]XML Response") else: return Panel(, title=f"[bold magenta]Text Response")
Step 4: History Record Storage
HISTORY_FILE = 'request_history.json' def save_request_history(record): try: if (HISTORY_FILE): with open(HISTORY_FILE) as f: history = (f) else: history = [] (0, record) if len(history) > 100: () with open(HISTORY_FILE, 'w') as f: (history, f, indent=2) except Exception as e: (f"[bold red]Error saving history: {str(e)}")
5. Advanced optimization skills
1. Environment variable management
Create a .env file:
BASE_URL= TIMEOUT=10
Read in the code:
base_url = ('BASE_URL', 'http://localhost') timeout = int(('TIMEOUT', 5))
2. Request template function
Create:
{ "user_login": { "url": "/auth/login", "method": "POST", "headers": {"Content-Type": "application/json"}, "body": {"username": "admin", "password": "123456"} } }
Add template call interface:
@('/api/templates', methods=['GET']) def list_templates(): with open('') as f: return jsonify((f)) @('/api/execute_template', methods=['POST']) def execute_template(): template_name = ('template') # Load and execute the template...
3. Performance optimization
Using connection pooling:
(pool_connections=10, pool_maxsize=10)
Asynchronous support (use FastAPI instead):
from fastapi import FastAPI, Request @("/async-proxy") async def async_proxy(request: Request): # Use httpx asynchronous client
6. Use examples
Scenario 1: Send a GET request
curl -X POST http://localhost:5000/api/proxy \ -H "Content-Type: application/json" \ -d '{ "url": "/posts/1", "method": "GET" }'
response:
[bold green]Status: 200 { "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" }
Scenario 2: Send a POST request
curl -X POST http://localhost:5000/api/proxy \ -H "Content-Type: application/json" \ -d '{ "url": "/posts", "method": "POST", "headers": {"X-Custom-Header": "test"}, "data": {"title": "foo", "body": "bar", "userId": 1} }'
response:
[bold green]Status: 201 { "title": "foo", "body": "bar", "userId": 1, "id": 101 }
7. Performance comparison
characteristic | Self-built tools | Postman |
---|---|---|
Startup speed | < 0.1s | ~2s |
Memory usage | ~10MB | ~200MB |
Customization capability | Complete control | Plugin extensions |
Teamwork | Need to be done by yourself | Built-in collaboration features |
Automated testing | Need to combine unittest | Built-in test collection |
8. Expansion direction suggestions
Visual interface: Add a simple GUI with PyQt/Tkinter
Automated testing: Integrated pytest to generate test reports
Monitoring alarm: Add response time/status code abnormal alarm
Document generation: Automatically generate API documents based on request history
9. Summary
This lightweight tool is especially suitable for the following scenarios:
- Quick verification API modification
- Debugging the internal test environment
- Need to customize special request logic
- Teaching demonstration (demonstrate HTTP principles)
For scenarios where advanced features such as complex collection testing and Mock servers are required, it is still recommended to use mature tools such as Postman. However, the flexibility and performance advantages brought by self-built tools will become a tool to improve development efficiency in specific scenarios.
This is the end of this article about using Python’s own lightweight HTTP debugging tool. For more related Python HTTP debugging content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!