Functions in Semantic Kernel — OpenAPI
🌐 OpenAPI functions
OpenAPI functions let you import REST APIs declaratively from a Swagger/OpenAPI spec. They’re ideal when the spec is trustworthy and auth is straightforward.
Pros and cons
- Pros: Fast to connect, discoverable operations, consistent inputs/outputs, governance‑friendly.
- Cons: Spec quality varies, custom auth/flows may be tricky, complex transformations still need code.
Import a spec (C#)
var weather = await kernel.ImportPluginFromOpenApiAsync(
"weather",
new Uri("https://api.weatherapi.com/v1/openapi.json")
);
var result = await kernel.InvokeAsync(weather["getForecast"], new()
{
["location"] = "Vienna"
});
Auth wiring
Options:
- API keys: add a header via request hooks or an HttpClient handler.
- OAuth2 client credentials: attach bearer tokens via a delegating handler.
- On‑behalf‑of (OBO): often easier in native code; consider a hybrid (native wrapper around critical endpoints).
Typed HttpClient + auth handler example
services.AddHttpClient("weather")
.AddHttpMessageHandler(() => new AuthHeaderHandler(getTokenAsync));
public class AuthHeaderHandler(Func<Task<string>> getToken) : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
{
var token = await getToken();
request.Headers.Authorization = new("Bearer", token);
return await base.SendAsync(request, ct);
}
}
Then configure the OpenAPI function to use that client (SDK‑specific; if not available, prefer native code for the call).
Error handling and resiliency
- Validate required parameters before invoking.
- Handle 4xx/5xx explicitly; map to user‑friendly messages.
- Add retries, timeouts, and circuit breakers (Polly) at the HttpClient layer.
When to prefer native over OpenAPI
- Complex auth (OBO, mTLS, custom claims).
- Non‑trivial business rules and transformations.
- Tight observability or advanced resiliency requirements.
Hybrid approach: start with OpenAPI for broad coverage; lift critical paths into native code with typed clients and policies.
Next in the series
- 03_functions_05_mcp — connecting Copilot plugins and services
- 03_functions_06_plugins — packaging, manifests, governance