Spaces:
Running
Running
Commit
·
3448865
1
Parent(s):
98a99fb
After some headache of accidentally pushing a (revoked) API key, restructured code and did a bit of prompt engineering
Browse files- apiCall.py +114 -0
- main.py +7 -112
apiCall.py
CHANGED
@@ -2,6 +2,120 @@ import requests
|
|
2 |
import json
|
3 |
|
4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
class APIClient:
|
6 |
def __init__(self, base_url):
|
7 |
"""
|
|
|
2 |
import json
|
3 |
|
4 |
|
5 |
+
def api_call(
|
6 |
+
method="GET",
|
7 |
+
base_url=None,
|
8 |
+
endpoint=None,
|
9 |
+
param_keys_values=None,
|
10 |
+
header_keys_values=None,
|
11 |
+
additional_params=None,
|
12 |
+
):
|
13 |
+
"""Make an API call to fetch data with dynamic headers and parameters.
|
14 |
+
|
15 |
+
Parameters:
|
16 |
+
- method: HTTP method to use (GET, POST, PUT, DELETE)
|
17 |
+
- base_url: The base URL of the API
|
18 |
+
- endpoint: The specific API endpoint
|
19 |
+
- param_keys_values: Parameter key-value pairs, one per line
|
20 |
+
- header_keys_values: Header key-value pairs, one per line
|
21 |
+
- additional_params: Optional JSON string for complex parameters
|
22 |
+
|
23 |
+
Examples:
|
24 |
+
|
25 |
+
1. Simple GET request to a search API:
|
26 |
+
method: "GET"
|
27 |
+
base_url: "https://v2.xivapi.com/api"
|
28 |
+
endpoint: "search"
|
29 |
+
param_keys_values:
|
30 |
+
query: Name~"popoto"
|
31 |
+
sheets: Item
|
32 |
+
fields: Name,Description
|
33 |
+
language: en
|
34 |
+
limit: 1j
|
35 |
+
|
36 |
+
2. GitHub API request with headers:
|
37 |
+
method: "GET"
|
38 |
+
base_url: "https://api.github.com"
|
39 |
+
endpoint: "repos/microsoft/TypeScript/issues"
|
40 |
+
param_keys_values:
|
41 |
+
state: open
|
42 |
+
per_page: 5
|
43 |
+
header_keys_values:
|
44 |
+
Accept: application/vnd.github.v3+json
|
45 |
+
|
46 |
+
3. POST request with JSON body. the "messages" parameter is complexly structured, so it requires special handling."
|
47 |
+
method: "POST"
|
48 |
+
base_url: "https://api.anthropic.com"
|
49 |
+
endpoint: "v1/messages"
|
50 |
+
param_keys_values:
|
51 |
+
model: claude-opus-4-20250514
|
52 |
+
max_tokens: 1024
|
53 |
+
header_keys_values:
|
54 |
+
x-api-key: your_api_key_here
|
55 |
+
content-type: application/json
|
56 |
+
additional_params: {"messages": [{"role": "user", "content": "Hello"}]}
|
57 |
+
"""
|
58 |
+
# Build params dictionary from key-value pairs
|
59 |
+
params = {}
|
60 |
+
headers = {}
|
61 |
+
|
62 |
+
# Process param_keys_values
|
63 |
+
if param_keys_values:
|
64 |
+
lines = param_keys_values.strip().split("\n")
|
65 |
+
for line in lines:
|
66 |
+
if ":" in line:
|
67 |
+
key, value = line.split(":", 1)
|
68 |
+
key = key.strip()
|
69 |
+
value = value.strip()
|
70 |
+
|
71 |
+
if key: # Only add non-empty keys
|
72 |
+
# Try to parse numeric values
|
73 |
+
if value.isdigit():
|
74 |
+
params[key] = int(value)
|
75 |
+
elif value.lower() == "true":
|
76 |
+
params[key] = True
|
77 |
+
elif value.lower() == "false":
|
78 |
+
params[key] = False
|
79 |
+
else:
|
80 |
+
params[key] = value
|
81 |
+
|
82 |
+
# Process header_keys_values
|
83 |
+
if header_keys_values:
|
84 |
+
lines = header_keys_values.strip().split("\n")
|
85 |
+
for line in lines:
|
86 |
+
if ":" in line:
|
87 |
+
key, value = line.split(":", 1)
|
88 |
+
key = key.strip()
|
89 |
+
value = value.strip()
|
90 |
+
|
91 |
+
if key: # Only add non-empty keys
|
92 |
+
headers[key] = value
|
93 |
+
|
94 |
+
# Handle additional parameters
|
95 |
+
if additional_params and additional_params.strip():
|
96 |
+
try:
|
97 |
+
# Parse additional JSON parameters
|
98 |
+
extra_params = json.loads(additional_params)
|
99 |
+
if isinstance(extra_params, dict):
|
100 |
+
params.update(extra_params)
|
101 |
+
else:
|
102 |
+
return "Error: Additional parameters must be a valid JSON object"
|
103 |
+
except json.JSONDecodeError as e:
|
104 |
+
return f"Error parsing additional parameters: {str(e)}"
|
105 |
+
|
106 |
+
try:
|
107 |
+
client = APIClient(base_url)
|
108 |
+
result = client.make_request(
|
109 |
+
endpoint=endpoint,
|
110 |
+
params=params,
|
111 |
+
headers=headers,
|
112 |
+
method=method,
|
113 |
+
)
|
114 |
+
return result
|
115 |
+
except Exception as e:
|
116 |
+
return f"Error making API call: {str(e)}"
|
117 |
+
|
118 |
+
|
119 |
class APIClient:
|
120 |
def __init__(self, base_url):
|
121 |
"""
|
main.py
CHANGED
@@ -1,99 +1,11 @@
|
|
1 |
import gradio as gr
|
2 |
-
import
|
3 |
-
import json
|
4 |
-
|
5 |
-
|
6 |
-
def api_call(
|
7 |
-
base_url=None,
|
8 |
-
auth_token=None,
|
9 |
-
endpoint=None,
|
10 |
-
param_keys_values=None,
|
11 |
-
header_keys_values=None,
|
12 |
-
additional_params=None,
|
13 |
-
method="GET",
|
14 |
-
):
|
15 |
-
"""
|
16 |
-
Make an API call to fetch data with dynamic parameters.
|
17 |
-
|
18 |
-
Parameters:
|
19 |
-
- base_url: The base URL of the API (e.g., "https://api.example.com")
|
20 |
-
- auth_token: Optional authentication token for APIs requiring authorization
|
21 |
-
- endpoint: The specific API endpoint to call (e.g., "search", "users/profile")
|
22 |
-
- param_keys_values: String containing parameter key-value pairs, one per line in format "key: value"
|
23 |
-
- header_keys_values: String containing header key-value pairs, one per line in format "key: value"
|
24 |
-
- additional_params: Optional JSON string for complex parameters
|
25 |
-
- method: HTTP method to use (GET, POST, PUT, DELETE)
|
26 |
-
|
27 |
-
Instructions:
|
28 |
-
- Format param_keys_values and header_keys_values as a multi-line string with each pair on a new line
|
29 |
-
- For numeric values, simply use numbers without quotes
|
30 |
-
- For boolean values, use "true" or "false" (lowercase)
|
31 |
-
- For string values, just provide the string without additional quotes
|
32 |
-
"""
|
33 |
-
# Build params dictionary from key-value pairs
|
34 |
-
params = {}
|
35 |
-
headers = {}
|
36 |
-
|
37 |
-
# Process param_keys_values
|
38 |
-
if param_keys_values:
|
39 |
-
lines = param_keys_values.strip().split("\n")
|
40 |
-
for line in lines:
|
41 |
-
if ":" in line:
|
42 |
-
key, value = line.split(":", 1)
|
43 |
-
key = key.strip()
|
44 |
-
value = value.strip()
|
45 |
-
|
46 |
-
if key: # Only add non-empty keys
|
47 |
-
# Try to parse numeric values
|
48 |
-
if value.isdigit():
|
49 |
-
params[key] = int(value)
|
50 |
-
elif value.lower() == "true":
|
51 |
-
params[key] = True
|
52 |
-
elif value.lower() == "false":
|
53 |
-
params[key] = False
|
54 |
-
else:
|
55 |
-
params[key] = value
|
56 |
-
|
57 |
-
# Process header_keys_values
|
58 |
-
if header_keys_values:
|
59 |
-
lines = header_keys_values.strip().split("\n")
|
60 |
-
for line in lines:
|
61 |
-
if ":" in line:
|
62 |
-
key, value = line.split(":", 1)
|
63 |
-
key = key.strip()
|
64 |
-
value = value.strip()
|
65 |
-
|
66 |
-
if key: # Only add non-empty keys
|
67 |
-
headers[key] = value
|
68 |
-
|
69 |
-
# Handle additional parameters
|
70 |
-
if additional_params and additional_params.strip():
|
71 |
-
try:
|
72 |
-
# Parse additional JSON parameters
|
73 |
-
extra_params = json.loads(additional_params)
|
74 |
-
if isinstance(extra_params, dict):
|
75 |
-
params.update(extra_params)
|
76 |
-
else:
|
77 |
-
return "Error: Additional parameters must be a valid JSON object"
|
78 |
-
except json.JSONDecodeError as e:
|
79 |
-
return f"Error parsing additional parameters: {str(e)}"
|
80 |
-
|
81 |
-
try:
|
82 |
-
client = apiCall.APIClient(base_url, auth_token)
|
83 |
-
result = client.make_request(
|
84 |
-
endpoint=endpoint,
|
85 |
-
params=params,
|
86 |
-
headers=headers,
|
87 |
-
method=method,
|
88 |
-
)
|
89 |
-
return result
|
90 |
-
except Exception as e:
|
91 |
-
return f"Error making API call: {str(e)}"
|
92 |
|
93 |
|
94 |
demo = gr.Interface(
|
95 |
fn=api_call,
|
96 |
inputs=[
|
|
|
97 |
gr.Textbox(
|
98 |
label="Base URL",
|
99 |
placeholder="Enter base URL",
|
@@ -118,45 +30,30 @@ demo = gr.Interface(
|
|
118 |
value="{}",
|
119 |
lines=3,
|
120 |
),
|
121 |
-
gr.Radio(choices=["GET", "POST", "PUT", "DELETE"], label="Method", value="GET"),
|
122 |
],
|
123 |
outputs=gr.Textbox(label="API Response", lines=10),
|
124 |
title="Universal API Client",
|
125 |
-
description="Make API calls to any endpoint with custom parameters. \n\n"
|
126 |
-
|
127 |
-
|
128 |
-
+ "- **Parameter Key-Value Pairs**: Format as 'key: value' with each pair on a new line \n"
|
129 |
-
+ " Example: \n```\nquery: search term\nlimit: 10\nfilter: active\n``` \n"
|
130 |
-
+ "- **Header Key-Value Pairs**: Format as 'key: value' with each pair on a new line \n"
|
131 |
-
+ " Example: \n```\nx-api-key: your_api_key\ncontent-type: application/json\n``` \n"
|
132 |
-
+ "- **Additional Parameters**: Use valid JSON format for nested or complex parameters \n"
|
133 |
-
+ "- **Method**: Choose the appropriate HTTP method for your request",
|
134 |
examples=[
|
135 |
[
|
|
|
136 |
"https://v2.xivapi.com/api",
|
137 |
-
"",
|
138 |
"search",
|
139 |
'query: Name~"popoto"\nsheets: Item\nfields: Name,Description\nlanguage: en\nlimit: 1',
|
140 |
"",
|
141 |
"{}",
|
142 |
-
"GET",
|
143 |
],
|
144 |
[
|
|
|
145 |
"https://api.github.com",
|
146 |
-
"",
|
147 |
"repos/microsoft/TypeScript/issues",
|
148 |
"state: open\nper_page: 5",
|
149 |
"Accept: application/vnd.github.v3+json",
|
150 |
"{}",
|
151 |
-
"GET",
|
152 |
],
|
153 |
[
|
154 |
-
"https://api.anthropic.com",
|
155 |
-
"",
|
156 |
-
"v1/messages",
|
157 |
-
"model: claude-opus-4-20250514\nmax_tokens: 1024",
|
158 |
-
"x-api-key: API-KEY-HERE\nanthropic-version: 2023-06-01\ncontent-type: application/json",
|
159 |
-
'{"messages": [{"role": "user", "content": "Hello there!"}]}',
|
160 |
"POST",
|
161 |
"https://api.anthropic.com",
|
162 |
"v1/messages",
|
@@ -165,8 +62,6 @@ demo = gr.Interface(
|
|
165 |
'{"messages": [{"role": "user", "content": "what is a chicken"}]}',
|
166 |
],
|
167 |
],
|
168 |
-
flagging_mode="manual",
|
169 |
-
flagging_options=["Invalid Request", "API Error", "Other"],
|
170 |
)
|
171 |
|
172 |
if __name__ == "__main__":
|
|
|
1 |
import gradio as gr
|
2 |
+
from apiCall import api_call
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
|
5 |
demo = gr.Interface(
|
6 |
fn=api_call,
|
7 |
inputs=[
|
8 |
+
gr.Radio(choices=["GET", "POST", "PUT", "DELETE"], label="Method", value="GET"),
|
9 |
gr.Textbox(
|
10 |
label="Base URL",
|
11 |
placeholder="Enter base URL",
|
|
|
30 |
value="{}",
|
31 |
lines=3,
|
32 |
),
|
|
|
33 |
],
|
34 |
outputs=gr.Textbox(label="API Response", lines=10),
|
35 |
title="Universal API Client",
|
36 |
+
description="Make API calls to any endpoint with custom parameters and headers. \n\n- **Method**: Choose the appropriate HTTP method for your request \n- **Base URL**: Enter the full API base URL (e.g., 'https://api.example.com') \n- **Endpoint**: The specific endpoint to call (without leading slash) \n- **Parameter Key-Value Pairs**: Format as 'key: value' with each pair on a new line \n Example: \n```\nquery: search term\nlimit: 10\nfilter: active\n``` \n- **Header Key-Value Pairs**: Format as 'key: value' with each pair on a new line \n Example: \n```\nx-api-key: your_api_key\ncontent-type: application/json\n``` \n- **Additional Parameters**: Use valid JSON format for nested or complex parameters",
|
37 |
+
flagging_mode="manual",
|
38 |
+
flagging_options=["Invalid Request", "API Error", "Other"],
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
examples=[
|
40 |
[
|
41 |
+
"GET",
|
42 |
"https://v2.xivapi.com/api",
|
|
|
43 |
"search",
|
44 |
'query: Name~"popoto"\nsheets: Item\nfields: Name,Description\nlanguage: en\nlimit: 1',
|
45 |
"",
|
46 |
"{}",
|
|
|
47 |
],
|
48 |
[
|
49 |
+
"GET",
|
50 |
"https://api.github.com",
|
|
|
51 |
"repos/microsoft/TypeScript/issues",
|
52 |
"state: open\nper_page: 5",
|
53 |
"Accept: application/vnd.github.v3+json",
|
54 |
"{}",
|
|
|
55 |
],
|
56 |
[
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
"POST",
|
58 |
"https://api.anthropic.com",
|
59 |
"v1/messages",
|
|
|
62 |
'{"messages": [{"role": "user", "content": "what is a chicken"}]}',
|
63 |
],
|
64 |
],
|
|
|
|
|
65 |
)
|
66 |
|
67 |
if __name__ == "__main__":
|