Update generate_godot_openapi.py to pass base_url as parameter to _init
This commit is contained in:
@@ -112,7 +112,7 @@ def generate_api_client(path: str, method: str, endpoint: dict) -> str:
|
|||||||
|
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
def generate_tag_client(tag: str, endpoints: list, base_url: str) -> str:
|
def generate_tag_client(tag: str, endpoints: list) -> str:
|
||||||
"""Generate a GDScript API client for all endpoints with a given tag."""
|
"""Generate a GDScript API client for all endpoints with a given tag."""
|
||||||
class_name = sanitize_class_name(tag) + "API"
|
class_name = sanitize_class_name(tag) + "API"
|
||||||
|
|
||||||
@@ -121,11 +121,13 @@ def generate_tag_client(tag: str, endpoints: list, base_url: str) -> str:
|
|||||||
"extends RefCounted",
|
"extends RefCounted",
|
||||||
"",
|
"",
|
||||||
"var http_request: HTTPRequest",
|
"var http_request: HTTPRequest",
|
||||||
|
"var base_url: String",
|
||||||
"",
|
"",
|
||||||
"func _init(node: Node):",
|
"func _init(node: Node, base_url_param: String):",
|
||||||
" http_request = HTTPRequest.new()",
|
" http_request = HTTPRequest.new()",
|
||||||
" node.add_child(http_request)",
|
" node.add_child(http_request)",
|
||||||
' http_request.connect("request_completed", self, "_on_request_completed")',
|
' http_request.connect("request_completed", self, "_on_request_completed")',
|
||||||
|
" base_url = base_url_param",
|
||||||
"",
|
"",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -138,11 +140,10 @@ def generate_tag_client(tag: str, endpoints: list, base_url: str) -> str:
|
|||||||
|
|
||||||
# Format URL (replace {param} with %s for Godot's string formatting)
|
# Format URL (replace {param} with %s for Godot's string formatting)
|
||||||
url = path.replace("{", "%").replace("}", "s")
|
url = path.replace("{", "%").replace("}", "s")
|
||||||
full_url = f'"{base_url}{url}"'
|
|
||||||
|
|
||||||
lines.extend([
|
lines.extend([
|
||||||
f"func {func_name}(params: Dictionary = {{}}, callback: Callable):",
|
f"func {func_name}(params: Dictionary = {{}}, callback: Callable):",
|
||||||
f" var url := {full_url}",
|
f' var url := base_url + "{url}"',
|
||||||
' var headers = ["User-Agent: MyGodotApp"]',
|
' var headers = ["User-Agent: MyGodotApp"]',
|
||||||
f" var error := http_request.request(url, headers, false, HTTPClient.METHOD_{method.upper()})",
|
f" var error := http_request.request(url, headers, false, HTTPClient.METHOD_{method.upper()})",
|
||||||
" if error != OK:",
|
" if error != OK:",
|
||||||
@@ -168,7 +169,7 @@ def generate_tag_client(tag: str, endpoints: list, base_url: str) -> str:
|
|||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
def generate_code(spec: dict, output_dir: str, base_url: str):
|
def generate_code(spec: dict, output_dir: str):
|
||||||
"""Generate all GDScript files from the OpenAPI spec."""
|
"""Generate all GDScript files from the OpenAPI spec."""
|
||||||
# Create output directory
|
# Create output directory
|
||||||
Path(output_dir).mkdir(parents=True, exist_ok=True)
|
Path(output_dir).mkdir(parents=True, exist_ok=True)
|
||||||
@@ -198,7 +199,7 @@ def generate_code(spec: dict, output_dir: str, base_url: str):
|
|||||||
|
|
||||||
# Generate one file per tag
|
# Generate one file per tag
|
||||||
for tag, endpoints in tag_endpoints.items():
|
for tag, endpoints in tag_endpoints.items():
|
||||||
code = generate_tag_client(tag, endpoints, base_url)
|
code = generate_tag_client(tag, endpoints)
|
||||||
class_name = sanitize_class_name(tag) + "API"
|
class_name = sanitize_class_name(tag) + "API"
|
||||||
output_path = Path(output_dir) / f"{class_name}.gd"
|
output_path = Path(output_dir) / f"{class_name}.gd"
|
||||||
with open(output_path, "w") as f:
|
with open(output_path, "w") as f:
|
||||||
@@ -210,12 +211,14 @@ def main():
|
|||||||
parser = argparse.ArgumentParser(description="Generate Godot API clients from OpenAPI spec")
|
parser = argparse.ArgumentParser(description="Generate Godot API clients from OpenAPI spec")
|
||||||
parser.add_argument("input", help="Path to the OpenAPI JSON/YAML file")
|
parser.add_argument("input", help="Path to the OpenAPI JSON/YAML file")
|
||||||
parser.add_argument("-o", "--output", default="godot_generated", help="Output directory for GDScript files")
|
parser.add_argument("-o", "--output", default="godot_generated", help="Output directory for GDScript files")
|
||||||
parser.add_argument("-b", "--base-url", default="https://api.example.com", help="Base URL for API requests")
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
spec = load_openapi_spec(args.input)
|
spec = load_openapi_spec(args.input)
|
||||||
generate_code(spec, args.output, args.base_url)
|
generate_code(spec, args.output)
|
||||||
print("Done!")
|
print("Done!")
|
||||||
|
print("Note: When initializing the API classes, pass the base URL as a parameter:")
|
||||||
|
print(" var music_api = MusicAPI.new()")
|
||||||
|
print(" music_api._init(get_node('/root'), 'http://localhost:8080')")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
|
|||||||
Reference in New Issue
Block a user