api.go
Overview
The api.go source file defines a sublauncher component that integrates the ADK REST API into the web server framework under the /api/ URL path. This sublauncher provides HTTP endpoints for interacting with AI agents and related services via the ADK REST API. It handles command-line parsing for configuration, sets up HTTP routing with CORS support, and exposes the API handler to serve client requests.
This file is part of the broader API and A2A Sublaunchers and REST API and Web Launchers topics, focusing on enabling REST API access to the agent framework within a modular web server launcher architecture.
Types and Their Functionality
apiConfig
type apiConfig struct {
frontendAddress string
}
Purpose: Holds configuration parameters for launching the ADK REST API sublauncher.
Fields:
frontendAddress(string): Specifies the origin address of the frontend application (e.g., the ADK Web UI) allowed to make cross-origin requests (CORS).
apiLauncher
type apiLauncher struct {
flags *flag.FlagSet
config *apiConfig
}
Purpose: Implements the
web.Sublauncherinterface to provide REST API server functionality integrated into the web server launcher.Fields:
flags: Aflag.FlagSetinstance for parsing command-line flags specific to this sublauncher.config: Pointer to anapiConfiginstance holding launch configuration.
Functions and Methods
NewLauncher() weblauncher.Sublauncher
func NewLauncher() weblauncher.Sublauncher
Description: Factory function that creates and initializes a new
apiLauncherinstance.Functionality:
Creates a new
apiConfig.Sets up a
flag.FlagSetwith awebui_addressflag, defaulting to"localhost:8080".Returns an
apiLauncherwith the flag set and config.
Usage example:
launcher := api.NewLauncher()
(a *apiLauncher) Keyword() string
func (a *apiLauncher) Keyword() string
Description: Returns the command-line keyword used to invoke this sublauncher.
Returns:
"api"
(a *apiLauncher) SimpleDescription() string
func (a *apiLauncher) SimpleDescription() string
Description: Provides a brief description of the sublauncher's purpose.
Returns:
"starts ADK REST API server, accepting origins specified by webui_address (CORS)"
(a *apiLauncher) CommandLineSyntax() string
func (a *apiLauncher) CommandLineSyntax() string
Description: Returns a formatted string describing the command-line flags supported by the sublauncher.
Implementation: Uses
util.FormatFlagUsageto generate usage information from the flag set.
(a *apiLauncher) Parse(args []string) ([]string, error)
func (a *apiLauncher) Parse(args []string) ([]string, error)
Description: Parses command-line arguments specific to the API sublauncher.
Parameters:
args: Slice of argument strings.
Returns:
Remaining unparsed arguments after consuming known flags.
An error if parsing fails.
Behavior: Uses the internal flag set to parse arguments, validates successful parsing.
(a *apiLauncher) UserMessage(webURL string, printer func(v ...any))
func (a *apiLauncher) UserMessage(webURL string, printer func(v ...any))
Description: Prints user-facing informational messages after launch.
Parameters:
webURL: The base URL of the web server.printer: Function to output messages, variadic to support multiple args.
Usage: Prints instructions on how to access the API endpoints, e.g.,
http://<webURL>/api/list-apps.
(a *apiLauncher) SetupSubrouters(router *mux.Router, config *launcher.Config) error
func (a *apiLauncher) SetupSubrouters(router *mux.Router, config *launcher.Config) error
Description: Integrates the ADK REST API handler into the parent HTTP router.
Parameters:
router: The mainmux.Routerto which the API subrouter is added.config: Launcher configuration passed down to the API handler.
Implementation details:
Creates an ADK REST API handler by calling
adkrest.NewHandler(config).Wraps the handler with CORS middleware configured for
frontendAddress.Registers the wrapped handler at the
/api/path prefix.Supports HTTP methods: GET, POST, DELETE, OPTIONS.
Returns:
nilon success, or an error if setup fails.
corsWithArgs(frontendAddress string) func(next http.Handler) http.Handler
func corsWithArgs(frontendAddress string) func(next http.Handler) http.Handler
Description: Middleware factory that returns an HTTP middleware function adding CORS headers.
Parameters:
frontendAddress: The allowed origin for cross-origin requests.
Returned function:
Sets headers:
Access-Control-Allow-OrigintofrontendAddressAccess-Control-Allow-Methodsto"GET, POST, PUT, DELETE, OPTIONS"Access-Control-Allow-Headersto"Content-Type, Authorization"
Handles preflight OPTIONS requests by responding with HTTP 200 status.
Passes other requests to the next handler.
Usage: Applied in
SetupSubroutersto wrap the API handler.
Important Implementation Details
CORS Configuration: The sublauncher enables cross-origin requests only from the specified
webui_addressto support browser-based clients such as the ADK WebUI. This is critical for frontend-backend interaction in a secure manner.HTTP Routing: The sublauncher uses the gorilla/mux router to register the API handler at
/api/, stripping the prefix before passing requests to the ADK REST API handler.Flag Parsing: Uses a dedicated
flag.FlagSetto isolate API-specific flags from others, supporting modular command-line argument parsing in the overall web server launcher.Integration with ADK REST API: Relies on
adkrest.NewHandlerfrom the internalserver/adkrestpackage to provide the actual API logic, delegating HTTP handling to that component.
Interaction with Other Parts of the System
Web Server Launcher: Implements the
web.Sublauncherinterface so that it can be plugged into the overall web server launcher framework (Web Server Launcher). This allows multiple sublaunchers (API, WebUI, A2A) to coexist.ADK REST API Handler: The core REST API functionality is provided by the
adkrestpackage, which exposes agent runtime, sessions, artifacts, and other HTTP endpoints. This file wraps it with routing and CORS middleware.Frontend Web UI: The
frontendAddressflag corresponds to the Web UI origin, enabling CORS for browser clients. This forms a connection between the UI launcher (Web UI Launcher) and the REST API sublauncher.Command-line Interface: This sublauncher registers its flags and keyword with the launcher CLI framework, allowing users to start the API server with custom parameters.
HTTP Middleware Stack: The CORS middleware provided here is a reusable pattern for cross-origin request handling, which can be adapted or extended for other sublaunchers or handlers.
Visual Diagram: apiLauncher Structure and Workflow
classDiagram
class apiLauncher {
-flags: FlagSet
-config: apiConfig
+Keyword()
+SimpleDescription()
+CommandLineSyntax()
+Parse(args)
+UserMessage(webURL, printer)
+SetupSubrouters(router, config)
}
class apiConfig {
-frontendAddress: string
}
apiLauncher --> apiConfig : contains
Workflow Flowchart of Request Handling and Setup
flowchart TD
Start[Launch apiLauncher]
ParseFlags[Parse Command-line Flags]
SetupRouter[SetupSubrouters]
CreateAPIHandler[adkrest.NewHandler]
WrapCORS[CORS Middleware]
RegisterRoute[Register /api/ route]
HTTPRequest[Incoming HTTP Request /api/...]
StripPrefix[Strip /api prefix]
CORSHandler[CORS Middleware Handler]
APIHandler[ADK REST API Handler]
Start --> ParseFlags --> SetupRouter
SetupRouter --> CreateAPIHandler --> WrapCORS --> RegisterRoute
RegisterRoute --> HTTPRequest --> StripPrefix --> CORSHandler --> APIHandler
This flowchart illustrates the lifecycle from launching the sublauncher, parsing flags, setting up HTTP routes, applying CORS middleware, and handling incoming API requests.
Usage Example
To use the API sublauncher within the web server launcher:
./adk_launcher api -webui_address=localhost:8080
This will:
Start the REST API server accessible under
/api/path.Allow cross-origin requests from http://localhost:8080.
Print user messages indicating how to access the API endpoints.
References to Related Topics
The API handler created and registered in this file is from REST API and Web Launchers, which covers the implementation of REST API controllers, routing, and server logic.
The sublauncher implements the
web.Sublauncherinterface as described in Web Server Launcher.CORS handling pattern here facilitates integration with the embedded Web UI launcher (Web UI Launcher) by enabling cross-origin requests.
The overall architecture aligns with the modular sublauncher approach in API and A2A Sublaunchers, which explains how REST API and A2A servers coexist in the web server.
The flag parsing and command line structure conform to patterns in launcher utilities (CLI Utilities).
This file plays a crucial role in bridging HTTP REST API requests from clients (such as the ADK Web UI) to the underlying agent framework, providing a configured, routable, and secure API surface within the web server launcher environment.