-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapitest.py
More file actions
214 lines (195 loc) · 8.01 KB
/
apitest.py
File metadata and controls
214 lines (195 loc) · 8.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import click
import requests
import json
from rich.console import Console
from rich.table import Table
from rich.text import Text
import os
import time
from textblob import TextBlob
from datetime import datetime
import re
console = Console()
REQUESTS_FILE = "requests.json"
TEMPLATES_FILE = "templates.json"
RESPONSES_DIR = "responses"
@click.group()
def cli():
pass
@cli.command()
@click.argument("url")
@click.option("--header", multiple=True, help="Header in 'Key: Value' format, e.g., 'Content-Type: application/json'")
@click.option("--search", help="Keyword to search in response (case-insensitive)")
@click.option("--analyze", is_flag=True, help="Show sentiment analysis of response")
def get(url, header, search, analyze):
headers = dict(h.split(": ", 1) for h in header)
try:
response = requests.get(url, headers=headers)
display_response(response, search)
save_response(response)
if analyze:
analyze_response(response)
except requests.RequestException as e:
console.print(f"[red]Error:[/] Connection error: {e}")
@cli.command()
@click.argument("url")
@click.option("--data", help="JSON data, e.g., '{\"key\": \"value\"}'")
@click.option("--header", multiple=True, help="Header in 'Key: Value' format, e.g., 'Content-Type: application/json'")
@click.option("--analyze", is_flag=True, help="Show sentiment analysis of response")
def post(url, data, header, analyze):
headers = dict(h.split(": ", 1) for h in header)
try:
json_data = json.loads(data) if data else {}
response = requests.post(url, json=json_data, headers=headers)
display_response(response)
save_response(response)
if analyze:
analyze_response(response)
except json.JSONDecodeError:
console.print("[red]Error:[/] Invalid JSON format! Use: '{\"key\": \"value\"}'")
except requests.RequestException as e:
console.print(f"[red]Error:[/] Connection error: {e}")
@cli.command()
@click.argument("name")
def save(name):
if not os.path.exists(".last_request.json"):
console.print("[red]Error:[/] Send a request first!")
return
with open(".last_request.json", "r", encoding="utf-8") as f:
last_request = json.load(f)
requests_data = load_requests()
requests_data[name] = last_request
save_requests(requests_data)
console.print(f"[green]Request saved:[/] {name}")
@cli.command()
@click.argument("name")
@click.option("--analyze", is_flag=True, help="Show sentiment analysis of response")
def replay(name, analyze):
requests_data = load_requests()
if name not in requests_data:
console.print(f"[red]Error:[/] Request '{name}' not found!")
return
request = requests_data[name]
try:
response = requests.request(
method=request["method"],
url=request["url"],
headers=request.get("headers", {}),
json=request.get("data", {})
)
display_response(response)
save_response(response)
if analyze:
analyze_response(response)
except requests.RequestException as e:
console.print(f"[red]Error:[/] Connection error: {e}")
@cli.command()
@click.argument("name")
@click.option("--url", required=True, help="Target URL for the template")
@click.option("--method", default="GET", help="HTTP method (GET, POST, etc.)")
@click.option("--header", multiple=True, help="Header in 'Key: Value' format, e.g., 'Content-Type: application/json'")
@click.option("--data", help="JSON data, e.g., '{\"key\": \"value\"}'")
def template(name, url, method, header, data):
headers = dict(h.split(": ", 1) for h in header)
try:
template_data = {
"url": url,
"method": method.upper(),
"headers": headers,
"data": json.loads(data) if data else {}
}
templates = load_templates()
templates[name] = template_data
save_templates(templates)
console.print(f"[green]Template created:[/] {name}")
except json.JSONDecodeError:
console.print("[red]Error:[/] Invalid JSON format! Use: '{\"key\": \"value\"}'")
@cli.command(name="use-template")
@click.argument("name")
@click.option("--analyze", is_flag=True, help="Show sentiment analysis of response")
@click.option("--search", help="Keyword to search in response (case-insensitive)")
def use_template(name, analyze, search):
templates = load_templates()
if name not in templates:
console.print(f"[red]Error:[/] Template '{name}' not found!")
return
template = templates[name]
try:
response = requests.request(
method=template["method"],
url=template["url"],
headers=template.get("headers", {}),
json=template.get("data", {})
)
display_response(response, search)
save_response(response)
if analyze:
analyze_response(response)
except requests.RequestException as e:
console.print(f"[red]Error:[/] Connection error: {e}")
def display_response(response, search=None):
table = Table(title="API Response")
table.add_column("Property", style="cyan")
table.add_column("Value", style="magenta")
table.add_row("Status Code", str(response.status_code))
table.add_row("Response Time", f"{response.elapsed.total_seconds()}s")
response_text = response.text
if search:
pattern = re.compile(re.escape(search), re.IGNORECASE)
highlighted_text = pattern.sub(lambda m: f"[yellow]{m.group()}[/yellow]", response_text[:200] + ("..." if len(response_text) > 200 else ""))
table.add_row("Response", Text(highlighted_text, style="magenta"))
else:
table.add_row("Response", response_text[:200] + ("..." if len(response_text) > 200 else ""))
console.print(table)
last_request = {
"method": response.request.method,
"url": response.request.url,
"headers": dict(response.request.headers),
"data": json.loads(response.request.body.decode()) if response.request.body else {}
}
with open(".last_request.json", "w", encoding="utf-8") as f:
json.dump(last_request, f, indent=2)
def save_response(response):
os.makedirs(RESPONSES_DIR, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
response_data = {
"status_code": response.status_code,
"response_time": response.elapsed.total_seconds(),
"content": response.text
}
response_file = os.path.join(RESPONSES_DIR, f"response_{timestamp}.json")
with open(response_file, "w", encoding="utf-8") as f:
json.dump(response_data, f, indent=2)
console.print(f"[green]Response saved:[/] {response_file}")
def analyze_response(response):
try:
text = response.text
blob = TextBlob(text)
sentiment = blob.sentiment
table = Table(title="Response Analysis")
table.add_column("Metric", style="cyan")
table.add_column("Value", style="magenta")
table.add_row("Sentiment (Polarity)", f"{sentiment.polarity:.2f} (Positive > 0, Negative < 0)")
table.add_row("Subjectivity", f"{sentiment.subjectivity:.2f} (0=Objective, 1=Subjective)")
console.print(table)
console.print("[yellow]Note:[/] Sentiment analysis measures the emotional tone (positive/negative) and subjectivity of the response text.")
except Exception as e:
console.print(f"[yellow]Analysis failed:[/] {e}")
def load_requests():
if os.path.exists(REQUESTS_FILE):
with open(REQUESTS_FILE, "r", encoding="utf-8") as f:
return json.load(f)
return {}
def save_requests(requests_data):
with open(REQUESTS_FILE, "w", encoding="utf-8") as f:
json.dump(requests_data, f, indent=2)
def load_templates():
if os.path.exists(TEMPLATES_FILE):
with open(TEMPLATES_FILE, "r", encoding="utf-8") as f:
return json.load(f)
return {}
def save_templates(templates):
with open(TEMPLATES_FILE, "w", encoding="utf-8") as f:
json.dump(templates, f, indent=2)
if __name__ == "__main__":
cli()