### Basic OpenApiClientProvider usage Source: https://fsprojects.github.io/SwaggerProvider/OpenApiClientProvider.html Shows the minimal setup: open the SwaggerProvider namespace, define a schema literal, and create a client instance. ```fsharp open SwaggerProvider let [] Schema = "https://petstore.swagger.io/v2/swagger.json" type PetStore = OpenApiClientProvider let client = PetStore.Client() ``` -------------------------------- ### F# Interactive: Create and use OpenApiClientProvider Source: https://fsprojects.github.io/SwaggerProvider/getting-started.html Use in an F# script file (e.g., openapi.fsx) to reference the SwaggerProvider NuGet package, define a schema literal, and generate a typed client. The example calls GetInventory() and runs the async task synchronously. ```fsharp #r "nuget: SwaggerProvider" open SwaggerProvider let [] Schema = "https://petstore.swagger.io/v2/swagger.json" type PetStore = OpenApiClientProvider let client = PetStore.Client() client.GetInventory() |> Async.AwaitTask |> Async.RunSynchronously ``` -------------------------------- ### Complete sample with HttpClient and custom types Source: https://fsprojects.github.io/SwaggerProvider/OpenApiClientProvider.html Shows a full program: creating an HttpClient with UseCookies=false, setting BaseAddress, providing the client to PetStore.Client, creating a Pet, adding it, and retrieving it. ```fsharp open System open System.Net.Http open SwaggerProvider let [] Schema = "https://petstore.swagger.io/v2/swagger.json" // By default provided methods return Task<'a> // and use Option<'a> for optional params type PetStore = OpenApiClientProvider [] let main argv = // `UseCookies = false` is required if you use Cookie Parameters let handler = new HttpClientHandler(UseCookies = false) // `BaseAddress` uri should end with '/' because TP generates relative URIs let baseUri = Uri("https://petstore.swagger.io/v2/") use httpClient = new HttpClient(handler, true, BaseAddress = baseUri) // You can provide your instance of `HttpClient` to the provided API client // or change it any time at runtime using `client.HttpClient` property let client = PetStore.Client(httpClient) task { // Create a new instance of the provided type and add to store let pet = PetStore.Pet(Id = Some(24L), Name = "Shani") do! client.AddPet(pet) // Request data back and deserialize to the provided type let! myPet = client.GetPetById(24L) printfn "Waw, my name is %A" myPet.Name } |> Async.AwaitTask |> Async.RunSynchronously 0 ``` -------------------------------- ### New Project: Create console app, add package, and run Source: https://fsprojects.github.io/SwaggerProvider/getting-started.html Steps to create a new F# console project, add the SwaggerProvider package, replace Program.fs with the provided code, and run the application. The Program.fs code defines an entry point that creates a client, calls GetInventory(), and prints the result. ```bash dotnet new console --name apiclient --language F# cd apiclient dotnet add package SwaggerProvider ``` ```fsharp open SwaggerProvider let [] Schema = "https://petstore.swagger.io/v2/swagger.json" type PetStore = OpenApiClientProvider [] let main argv = let client = PetStore.Client() client.GetInventory() |> Async.AwaitTask |> Async.RunSynchronously |> printfn "%O" 0 ``` ```bash dotnet run ``` -------------------------------- ### Client() Source: https://fsprojects.github.io/SwaggerProvider/OpenApiClientProvider.html Creates an instance of the generated API client. Optionally accepts an HttpClient instance. The client exposes generated methods for each API operation and a HttpClient property for runtime configuration. ```APIDOC ## Client() ### Description Creates an instance of the generated API client. Optionally accepts an HttpClient instance. The client exposes generated methods for each API operation and a HttpClient property for runtime configuration. ### Parameters - **httpClient** (HttpClient) - Optional - An instance of `HttpClient` to use for requests. If not provided, a default client is created. ### Returns - **client** - The generated API client instance. ### Example ```fsharp let client = PetStore.Client() // or with a custom HttpClient let handler = new HttpClientHandler(UseCookies = false) let baseUri = Uri("https://petstore.swagger.io/v2/") use httpClient = new HttpClient(handler, true, BaseAddress = baseUri) let client = PetStore.Client(httpClient) ``` ``` -------------------------------- ### IgnoreParseErrors for non-strictly-compliant schemas Source: https://fsprojects.github.io/SwaggerProvider/OpenApiClientProvider.html Shows how to continue generating the provider despite OpenAPI parser validation errors, with warnings printed to stderr. Only use when you trust the schema source. ```fsharp // NSwag-generated schema with non-standard nullable annotations type MyApi = OpenApiClientProvider<"https://example.com/swagger.json", IgnoreParseErrors=true> ``` -------------------------------- ### SSRF protection configuration Source: https://fsprojects.github.io/SwaggerProvider/OpenApiClientProvider.html Shows how to disable SSRF protection for development and testing with local servers, and the default production configuration. Warning: never set SsrfProtection=false in production. ```fsharp // Development: Allow HTTP and localhost type LocalApi = OpenApiClientProvider<"http://localhost:5000/swagger.json", SsrfProtection=false> // Production: HTTPS with SSRF protection (default) type ProdApi = OpenApiClientProvider<"https://api.example.com/swagger.json"> ``` -------------------------------- ### Intercept HTTP requests with a custom DelegatingHandler Source: https://fsprojects.github.io/SwaggerProvider/Customization.html Demonstrates request interception by implementing a custom DelegatingHandler (LoggingHandler) that logs each outgoing request. The handler is chained to an HttpClientHandler and passed to the generated PetStore client, which is then used to add and fetch a pet asynchronously. Put a breakpoint inside SendAsync to debug HTTP calls. ```fsharp open System open System.Net.Http open SwaggerProvider let [] Schema = "https://petstore.swagger.io/v2/swagger.json" type PetStore = OpenApiClientProvider type LoggingHandler(messageHandler) = inherit DelegatingHandler(messageHandler) override __.SendAsync(request, cancellationToken) = // Put a breakpoint here if you want to debug HTTP calls printfn "[%A]: %A" request.Method request.RequestUri base.SendAsync(request, cancellationToken) [] let main argv = let baseAddress = Uri("https://petstore.swagger.io/v2/") let handler1 = new HttpClientHandler (UseCookies = false) let handler2 = new LoggingHandler(handler1) use httpClient = new HttpClient(handler2, true, BaseAddress=baseAddress) let client = PetStore.Client(httpClient) async { let pet = PetStore.Pet(Id = Some(24L), Name = "Shani") do! client.AddPet(pet) let! myPet = client.GetPetById(24L) printfn "Waw, my name is %A" myPet.Name } |> Async.RunSynchronously 0 ``` -------------------------------- ### Generated Methods (e.g., GetPetById, AddPet) Source: https://fsprojects.github.io/SwaggerProvider/OpenApiClientProvider.html Each operation in the OpenAPI schema becomes a method on the generated client. Methods accept parameters from the schema and an optional cancellationToken. Return types are Task<'T> by default, or Async<'T> if PreferAsync=true. ```APIDOC ## Generated Methods (e.g., GetPetById, AddPet) ### Description Each operation in the OpenAPI schema becomes a method on the generated client. Methods accept parameters from the schema and an optional cancellationToken. Return types are Task<'T> by default, or Async<'T> if PreferAsync=true. ### Parameters - **cancellationToken** (CancellationToken) - Optional - A cancellation token to cancel the HTTP request. Defaults to `CancellationToken.None`. - Additional parameters are generated from the OpenAPI schema for each operation. ### Example ```fsharp task { use cts = new CancellationTokenSource(TimeSpan.FromSeconds(5.0)) let! pet = client.GetPetById(42L, cancellationToken = cts.Token) printfn $"Pet: {pet}" } |> _.Result ``` ``` -------------------------------- ### ProvidedApiClientBase core members Source: https://fsprojects.github.io/SwaggerProvider/Customization.html Shows the core members of ProvidedApiClientBase that every generated API client subclasses. The full source includes default Serialize and Deserialize implementations built on System.Text.Json; you can override them if the default JsonSerializerOptions do not fit your needs. You can also supply your own HttpClient instance during construction to fully control request execution. ```fsharp type ProvidedApiClientBase(httpClient: HttpClient) = member val HttpClient = httpClient with get, set abstract member Serialize: obj -> string abstract member Deserialize: string * Type -> obj ``` -------------------------------- ### Set Authorization header via HttpClient.DefaultRequestHeaders Source: https://fsprojects.github.io/SwaggerProvider/Customization.html Adds the Authorization header to all requests using HttpClient.DefaultRequestHeaders when token invalidation is not required. Sets UseCookies to false and creates a PetStore client with the configured HttpClient. ```fsharp let baseAddress = Uri("https://petstore.swagger.io/v2/") let handler = new HttpClientHandler (UseCookies = false) use httpClient = new HttpClient(handler, true, BaseAddress=baseAddress) httpClient.DefaultRequestHeaders.Authorization <- Headers.AuthenticationHeaderValue("Bearer", "Your OAuth token") let client = PetStore.Client(httpClient) ``` -------------------------------- ### CancellationToken support in generated methods Source: https://fsprojects.github.io/SwaggerProvider/OpenApiClientProvider.html Shows how to cancel a long-running HTTP request using the optional cancellationToken parameter, defaulting to CancellationToken.None. ```fsharp open System open System.Threading open SwaggerProvider let [] Schema = "https://petstore.swagger.io/v2/swagger.json" type PetStore = OpenApiClientProvider let client = PetStore.Client() task { // Cancel after 5 seconds use cts = new CancellationTokenSource(TimeSpan.FromSeconds(5.0)) let! pet = client.GetPetById(42L, cancellationToken = cts.Token) printfn $"Pet: {pet}" } |> _.Result ``` -------------------------------- ### Override Serialize and Deserialize in custom API client Source: https://fsprojects.github.io/SwaggerProvider/Customization.html Custom API client that overrides Serialize and Deserialize using System.Text.Json with FSharp.SystemTextJson options. The serializer is configurable but not replaceable; the type provider emits types with JsonPropertyNameAttribute. Requires nuget packages System.Text.Json and FSharp.SystemTextJson. ```fsharp open System open SwaggerProvider open System.Text.Json open System.Text.Json.Serialization let [] Schema = "https://petstore.swagger.io/v2/swagger.json" type PetStore = OpenApiClientProvider let jsonSerializerSettings = // nuget: System.Text.Json let settings = JsonSerializerOptions( //PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, // ... DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull ) // nuget: FSharp.SystemTextJson JsonFSharpOptions.Default().AddToJsonSerializerOptions settings settings type MyApiClient() = // inherit from provided API client inherit PetStore.Client() // Override default implementation of Serialize & Deserialize override __.Serialize(value:obj): string = JsonSerializer.Serialize(value, jsonSerializerSettings) override __.Deserialize(value, retTy:Type): obj = JsonSerializer.Deserialize(value, retTy, jsonSerializerSettings) [] let main argv = // Instantiate your API client let client = MyApiClient() async { let pet = PetStore.Pet(Id = Some(24L), Name = "Shani") do! client.AddPet(pet) let! myPet = client.GetPetById(24L) printfn "Waw, my name is %A" myPet.Name } |> Async.RunSynchronously 0 ``` -------------------------------- ### Custom DelegatingHandler for authentication Source: https://fsprojects.github.io/SwaggerProvider/Customization.html Custom DelegatingHandler that adds an Authorization header to every request. The handler is fully responsible for authentication data management, including token invalidation. Replace the placeholder token with your actual OAuth token. ```fsharp type AuthHandler(messageHandler) = inherit DelegatingHandler(messageHandler) override __.SendAsync(request, cancellationToken) = // Invalidate your token if it expired request.Headers.Authorization <- Headers.AuthenticationHeaderValue("Bearer", "Your OAuth token"); base.SendAsync(request, cancellationToken) ``` -------------------------------- ### OpenApiClientProvider Source: https://fsprojects.github.io/SwaggerProvider/OpenApiClientProvider.html Creates a type provider from a Swagger/OpenAPI schema URL or file path. The generated type exposes a Client() method that returns an HTTP client for calling the API operations. ```APIDOC ## OpenApiClientProvider ### Description Creates a type provider from a Swagger/OpenAPI schema URL or file path. The generated type exposes a Client() method that returns an HTTP client for calling the API operations. ### Parameters - **Schema** (string) - Required - URL or path to the Swagger schema file. - **IgnoreOperationId** (bool) - Optional - Do not use `operationsId` and generate method names using `path` only. Default value `false`. - **IgnoreControllerPrefix** (bool) - Optional - Do not parse `operationsId` as `_` and generate one client class for all operations. Default value `true`. - **PreferNullable** (bool) - Optional - Provide `Nullable<_>` for not required properties, instead of `Option<_>`. Default value `false`. - **PreferAsync** (bool) - Optional - Generate async actions of type `Async<'T>` instead of `Task<'T>`. Default value `false`. - **SsrfProtection** (bool) - Optional - Enable SSRF protection (blocks HTTP and localhost). Set to `false` for development/testing. Default value `true`. - **IgnoreParseErrors** (bool) - Optional - Continue generating the provider even when the OpenAPI parser reports validation errors. Warnings are printed to stderr. Default value `false`. ### Example ```fsharp open SwaggerProvider let [] Schema = "https://petstore.swagger.io/v2/swagger.json" type PetStore = OpenApiClientProvider let client = PetStore.Client() ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.