Googolplexic commited on
Commit
db4bc9c
·
1 Parent(s): a0644e5

Refactor APIClient to improve request handling and add support for custom headers; enhance api_call function to accept header key-value pairs.

Browse files
Files changed (3) hide show
  1. .vscode/mcp.json +7 -0
  2. apiCall.py +45 -31
  3. main.py +36 -1
.vscode/mcp.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "servers": {
3
+ "my-mcp-server-6195b585": {
4
+ "url": " http://127.0.0.1:7860/gradio_api/mcp/sse"
5
+ }
6
+ }
7
+ }
apiCall.py CHANGED
@@ -3,48 +3,62 @@ import json
3
 
4
 
5
  class APIClient:
6
- def __init__(self, base_url="https://v2.xivapi.com/api", auth_token=None):
7
- self.base_url = base_url if base_url else "https://v2.xivapi.com/api"
 
 
 
 
 
 
 
8
  self.auth_token = auth_token
9
 
10
- def make_request(
11
- self, endpoint=None, params=None, method="GET", data=None, json_data=None
12
- ):
13
  """
14
- Make an API request with flexible parameters.
 
 
 
 
 
 
 
 
 
15
  """
16
- url = f"{self.base_url}/{endpoint}" if endpoint else self.base_url
17
 
18
- # Remove trailing slash if endpoint is empty
19
- if endpoint == "":
20
- url = self.base_url.rstrip("/")
21
 
22
- headers = {}
23
  if self.auth_token:
24
  headers["Authorization"] = f"Bearer {self.auth_token}"
25
 
26
- kwargs = {"headers": headers}
27
-
28
- if params:
29
- kwargs["params"] = params
30
- if data:
31
- kwargs["data"] = data
32
- if json_data:
33
- kwargs["json"] = json_data
34
-
35
  try:
36
- print(f"Making {method} request to {url}")
37
- print(f"Parameters: {params}")
 
 
 
 
 
 
 
 
38
 
39
- response = requests.request(method, url, **kwargs)
 
40
 
41
- # Try to parse response as JSON
42
- if response.status_code == 200:
43
- try:
44
- return response.json()
45
- except json.JSONDecodeError:
46
- return response.text
 
47
 
48
- return f"Error {response.status_code}: {response.text}"
49
  except requests.exceptions.RequestException as e:
50
- return f"Request Error: {str(e)}"
 
3
 
4
 
5
  class APIClient:
6
+ def __init__(self, base_url, auth_token=None):
7
+ """
8
+ Initialize the API client with a base URL and optional auth token.
9
+
10
+ Parameters:
11
+ - base_url: The base URL of the API
12
+ - auth_token: Optional authentication token
13
+ """
14
+ self.base_url = base_url.rstrip("/")
15
  self.auth_token = auth_token
16
 
17
+ def make_request(self, endpoint="", params=None, headers=None, method="GET"):
 
 
18
  """
19
+ Make an HTTP request to the API endpoint.
20
+
21
+ Parameters:
22
+ - endpoint: API endpoint (without leading slash)
23
+ - params: Dictionary of parameters to include in the request
24
+ - headers: Dictionary of headers to include in the request
25
+ - method: HTTP method (GET, POST, PUT, DELETE)
26
+
27
+ Returns:
28
+ - String representation of the API response
29
  """
30
+ url = f"{self.base_url}/{endpoint.lstrip('/')}" if endpoint else self.base_url
31
 
32
+ # Initialize headers dictionary if None
33
+ if headers is None:
34
+ headers = {}
35
 
36
+ # Add authorization if token is provided
37
  if self.auth_token:
38
  headers["Authorization"] = f"Bearer {self.auth_token}"
39
 
 
 
 
 
 
 
 
 
 
40
  try:
41
+ if method.upper() == "GET":
42
+ response = requests.get(url, params=params, headers=headers)
43
+ elif method.upper() == "POST":
44
+ response = requests.post(url, json=params, headers=headers)
45
+ elif method.upper() == "PUT":
46
+ response = requests.put(url, json=params, headers=headers)
47
+ elif method.upper() == "DELETE":
48
+ response = requests.delete(url, json=params, headers=headers)
49
+ else:
50
+ return f"Unsupported method: {method}"
51
 
52
+ # Check if the response is successful
53
+ response.raise_for_status()
54
 
55
+ # Try to parse JSON response
56
+ try:
57
+ result = response.json()
58
+ return json.dumps(result, indent=2)
59
+ except ValueError:
60
+ # Return raw text if not JSON
61
+ return response.text
62
 
 
63
  except requests.exceptions.RequestException as e:
64
+ return f"Request error: {str(e)}"
main.py CHANGED
@@ -8,6 +8,7 @@ def api_call(
8
  auth_token=None,
9
  endpoint=None,
10
  param_keys_values=None,
 
11
  additional_params=None,
12
  method="GET",
13
  ):
@@ -19,17 +20,19 @@ def api_call(
19
  - auth_token: Optional authentication token for APIs requiring authorization
20
  - endpoint: The specific API endpoint to call (e.g., "search", "users/profile")
21
  - param_keys_values: String containing parameter key-value pairs, one per line in format "key: value"
 
22
  - additional_params: Optional JSON string for complex parameters
23
  - method: HTTP method to use (GET, POST, PUT, DELETE)
24
 
25
  Instructions:
26
- - Format param_keys_values as a multi-line string with each parameter on a new line
27
  - For numeric values, simply use numbers without quotes
28
  - For boolean values, use "true" or "false" (lowercase)
29
  - For string values, just provide the string without additional quotes
30
  """
31
  # Build params dictionary from key-value pairs
32
  params = {}
 
33
 
34
  # Process param_keys_values
35
  if param_keys_values:
@@ -51,6 +54,18 @@ def api_call(
51
  else:
52
  params[key] = value
53
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  # Handle additional parameters
55
  if additional_params and additional_params.strip():
56
  try:
@@ -68,6 +83,7 @@ def api_call(
68
  result = client.make_request(
69
  endpoint=endpoint,
70
  params=params,
 
71
  method=method,
72
  )
73
  return result
@@ -91,6 +107,12 @@ demo = gr.Interface(
91
  value='query: Name~"popoto"\nsheets: Item\nfields: Name,Description\nlanguage: en\nlimit: 1',
92
  lines=5,
93
  ),
 
 
 
 
 
 
94
  gr.Textbox(
95
  label="Additional Parameters (JSON)",
96
  placeholder="Enter any additional parameters as JSON",
@@ -107,6 +129,8 @@ demo = gr.Interface(
107
  + "- **Endpoint**: The specific endpoint to call (without leading slash) \n"
108
  + "- **Parameter Key-Value Pairs**: Format as 'key: value' with each pair on a new line \n"
109
  + " Example: \n```\nquery: search term\nlimit: 10\nfilter: active\n``` \n"
 
 
110
  + "- **Additional Parameters**: Use valid JSON format for nested or complex parameters \n"
111
  + "- **Method**: Choose the appropriate HTTP method for your request",
112
  examples=[
@@ -115,6 +139,7 @@ demo = gr.Interface(
115
  "",
116
  "search",
117
  'query: Name~"popoto"\nsheets: Item\nfields: Name,Description\nlanguage: en\nlimit: 1',
 
118
  "{}",
119
  "GET",
120
  ],
@@ -123,9 +148,19 @@ demo = gr.Interface(
123
  "",
124
  "repos/microsoft/TypeScript/issues",
125
  "state: open\nper_page: 5",
 
126
  "{}",
127
  "GET",
128
  ],
 
 
 
 
 
 
 
 
 
129
  ],
130
  flagging_mode="manual",
131
  flagging_options=["Invalid Request", "API Error", "Other"],
 
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
  ):
 
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:
 
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:
 
83
  result = client.make_request(
84
  endpoint=endpoint,
85
  params=params,
86
+ headers=headers,
87
  method=method,
88
  )
89
  return result
 
107
  value='query: Name~"popoto"\nsheets: Item\nfields: Name,Description\nlanguage: en\nlimit: 1',
108
  lines=5,
109
  ),
110
+ gr.Textbox(
111
+ label="Header Key-Value Pairs",
112
+ placeholder="Enter one header per line in format 'key: value'",
113
+ value="",
114
+ lines=3,
115
+ ),
116
  gr.Textbox(
117
  label="Additional Parameters (JSON)",
118
  placeholder="Enter any additional parameters as JSON",
 
129
  + "- **Endpoint**: The specific endpoint to call (without leading slash) \n"
130
  + "- **Parameter Key-Value Pairs**: Format as 'key: value' with each pair on a new line \n"
131
  + " Example: \n```\nquery: search term\nlimit: 10\nfilter: active\n``` \n"
132
+ + "- **Header Key-Value Pairs**: Format as 'key: value' with each pair on a new line \n"
133
+ + " Example: \n```\nx-api-key: your_api_key\ncontent-type: application/json\n``` \n"
134
  + "- **Additional Parameters**: Use valid JSON format for nested or complex parameters \n"
135
  + "- **Method**: Choose the appropriate HTTP method for your request",
136
  examples=[
 
139
  "",
140
  "search",
141
  'query: Name~"popoto"\nsheets: Item\nfields: Name,Description\nlanguage: en\nlimit: 1',
142
+ "",
143
  "{}",
144
  "GET",
145
  ],
 
148
  "",
149
  "repos/microsoft/TypeScript/issues",
150
  "state: open\nper_page: 5",
151
+ "Accept: application/vnd.github.v3+json",
152
  "{}",
153
  "GET",
154
  ],
155
+ [
156
+ "https://api.anthropic.com/v1/messages",
157
+ "",
158
+ "",
159
+ "",
160
+ "x-api-key: YOUR_API_KEY\nanthropic-version: 2023-06-01\ncontent-type: application/json",
161
+ '{"model":"claude-opus-4-20250514","max_tokens":1024,"messages":[{"role":"user","content":"Hello, world"}]}',
162
+ "POST",
163
+ ],
164
  ],
165
  flagging_mode="manual",
166
  flagging_options=["Invalid Request", "API Error", "Other"],