Skip to content

One path for multiple input/output

This page documents emitter behavior and customization when you use union operator | or @sharedRoute to express multiple input/output for a given path.

Default behaviors

The simplest way to express a combination of input in TypeSpec is to use the union operator |. At a glance, JS and Python supports natively union, while Java and C# will use overloads.

client.tsp
@service({
title: "Analyze",
version: "v1",
})
namespace Analyze;
@route("/analyze")
@post
op analyze(@query mode: "strict" | "lenient", @body image: bytes): AnalyzeResult;
model CompletionInput {
input: string | string[];
}
@route("/completions")
@post
op completions(@body input: CompletionInput): CompletionResult;
def analyze(image: bytes, *, mode: Literal["strict", "lenient"]) -> AnalyzeResult:
...
class CompletionInput:
input: Union[str, List[str]] = rest_field(readonly=True)
def completions(input: CompletionInput) -> CompletionResult:
...

Using union implies that the entire combination of possible input is valid. If you have a specific set of combination, or connection between input and output, you must use @sharedRoute. By default, codegen will generate one method per operation name.

client.tsp
@sharedRoute
@route("/foo")
op a(x: int32): float;
@sharedRoute
@route("/foo")
op b(x: string): int64;
def a(x: int) -> float:
# code
def b(x: string) -> int:
# code

Customizations

Merge @sharedRoute operations into one.

If your shared routes are actually one unique semantic operation, you may want to configure codegen to use a unique name. This is simply done by renaming both operations to the same name using @clientName

main.tsp
@sharedRoute
@route("/foo")
op a(x: int) : float
@sharedRoute
@route("/foo")
op b(x: string) : int64
// client.tsp
import "./main.tsp";
import "@azure-tools/typespec-client-generator-core";
using Azure.ClientGenerator.Core;
@@clientName(a, "Foo");
@@clientName(b, "Foo");
@overload
def foo(x: int) -> float:
...
@overload
def foo(x: string) -> int:
...
def foo(x: string | int) -> float | int:
# Code here