TypeScript v4 SDKs now authenticate the requests they send. Every authentication scheme your specification declares is generated into src/auth-schemes.ts, and the client options expose one optional credential property per scheme, named after it.
Details
Basic authentication, bearer tokens and API keys sent in a header, a query parameter or a cookie are all supported, as are operations that require several schemes together (AND) or accept any one of several (OR). OAuth2 is supported for the client credentials, authorization code with PKCE, and password grants. The SDK requests the token on first use, caches it until shortly before it expires, and refreshes an authorization-code token with its refresh token.
Each credential property is typed for its scheme. A key or token can also be a function, which the SDK calls on every request, so a credential can rotate without rebuilding the client. When the token endpoint refuses the credentials, or the authorization prompt fails, the call rejects with an AuthError and the operation is never sent. A 401 answered by the operation itself is an ApiError.
Usage Example
Pass a credential for each scheme your API declares when you construct the client:
import { PaymentsClient, PaymentsError } from "payments";
const client = new PaymentsClient({
oAuth2ClientCredentials: {
clientId: process.env.PAYMENTS_CLIENT_ID ?? "",
clientSecret: process.env.PAYMENTS_CLIENT_SECRET ?? "",
},
// A function is called on every request, so the key can rotate.
apiKeyHeader: () => process.env.PAYMENTS_API_KEY ?? "",
});
try {
const payment = await client.payments.get({ paymentId: "pay_123" });
console.log(payment.status);
} catch (err) {
if (err instanceof PaymentsError && err.kind === "auth") {
console.error("Could not obtain a token:", err.message);
} else {
throw err;
}
}
The token request runs once and is shared by every call until the token nears expiry.
This feature is available in the TypeScript v4 SDK (beta). Generate it from the APIMatic CLI:
apimatic sdk generate --language=typescript --codegen-version=v4 --stability=beta
For the full set of flags and options, see the APIMatic CLI documentation.