A C# Source Generator that uses Refitter for generating a REST API Client using the Refit library from OpenAPI specifications.
$ dotnet add package Refitter.SourceGeneratorRefitter is available as a C# Source Generator that uses the Refitter.Core library for generating a REST API Client using the Refit library. Refitter can generate the Refit interface from OpenAPI specifications. Refitter could format the generated Refit interface to be managed by Apizr (v6+) and generate some registration helpers too.
The Refitter source generator is a bit untraditional in a sense that it creates a folder called Generated in the same location as the .refitter file and generates files to disk under the Generated folder (can be changed with --outputFolder). The source generator output should be included in the project and committed to source control. This is done because there is no other way to trigger the Refit source generator to pickup the Refitter generated code
(Translation: I couldn't for the life of me figure how to get that to work, sorry)
The source generator is distributed as a NuGet package and should be installed to the project that will contain the generated code
dotnet add package Refitter.SourceGenerator
This source generator generates code based on any .refitter file included to the project as AdditionalFiles.
The generator can automatically detect all .refitter files inside the project that referenced the Refitter.SourceGenerator package and there is no need to include them manually as AdditionalFiles
The following is an example .refitter file
{
"openApiPath": "/path/to/your/openAPI", // Required
"namespace": "Org.System.Service.Api.GeneratedCode", // Optional. Default=GeneratedCode
"naming": {
"useOpenApiTitle": false, // Optional. Default=true
"interfaceName": "MyApiClient" // Optional. Default=ApiClient
},
"generateContracts": true, // Optional. Default=true
"generateXmlDocCodeComments": true, // Optional. Default=true
"generateStatusCodeComments": true, // Optional. Default=true
"addAutoGeneratedHeader": true, // Optional. Default=true
"addAcceptHeaders": true, // Optional. Default=true
"returnIApiResponse": false, // Optional. Default=false
"responseTypeOverride": { // Optional. Default={}
"File_Upload": "IApiResponse",
"File_Download": "System.Net.Http.HttpContent"
},
"generateOperationHeaders": true, // Optional. Default=true
"typeAccessibility": "Public", // Optional. Values=Public|Internal. Default=Public
"useCancellationTokens": false, // Optional. Default=false
"useIsoDateFormat": false, // Optional. Default=false
"multipleInterfaces": "ByEndpoint", // Optional. May be one of "ByEndpoint" or "ByTag"
"generateDeprecatedOperations": false, // Optional. Default=true
"operationNameTemplate": "{operationName}Async", // Optional. Must contain {operationName} when multipleInterfaces != ByEndpoint
"optionalParameters": false, // Optional. Default=false
"outputFolder": "../CustomOutput" // Optional. Default=./Generated
"outputFilename": "RefitInterface.cs", // Optional. Default=Output.cs for CLI tool
"additionalNamespaces": [ // Optional
"Namespace1",
"Namespace2"
],
"includeTags": [ // Optional. OpenAPI Tag to include when generating code
"Pet",
"Store",
"User"
],
"includePathMatches": [ // Optional. Only include Paths that match the provided regular expression
"^/pet/.*",
"^/store/.*"
],
"useDynamicQuerystringParameters": true, // Optional. Default=false
"usePolymorphicSerialization": true, // Optional. Default=false
"generateDisposableClients": true, // Optional. Default=false
"dependencyInjectionSettings": { // Optional
"baseUrl": "https://petstore3.swagger.io/api/v3", // Optional. Leave this blank to set the base address manually
"httpMessageHandlers": [ // Optional
"AuthorizationMessageHandler",
"TelemetryMessageHandler"
],
"transientErrorHandler": "Polly", // Optional. Value=None|Polly|HttpResilience
"maxRetryCount": 3, // Optional. Default=6
"firstBackoffRetryInSeconds": 0.5 // Optional. Default=1.0
},
"apizrSettings": { // Optional
"withRequestOptions": true, // Optional. Default=true
"withRegistrationHelper": true, // Optional. Default=false
"withCacheProvider": "InMemory", // Optional. Values=None|Akavache|MonkeyCache|InMemory|DistributedAsString|DistributedAsByteArray. Default=None
"withPriority": true, // Optional. Default=false
"withMediation": true, // Optional. Default=false
"withMappingProvider": "AutoMapper", // Optional. Values=None|AutoMapper|Mapster. Default=None
"withFileTransfer": true // Optional. Default=false
},
"codeGeneratorSettings": { // Optional. Default settings are the values set in this example
"requiredPropertiesMustBeDefined": true,
"generateDataAnnotations": true,
"anyType": "object",
"dateType": "System.DateTimeOffset",
"dateTimeType": "System.DateTimeOffset",
"timeType": "System.TimeSpan",
"timeSpanType": "System.TimeSpan",
"arrayType": "System.Collections.Generic.ICollection",
"dictionaryType": "System.Collections.Generic.IDictionary",
"arrayInstanceType": "System.Collections.ObjectModel.Collection",
"dictionaryInstanceType": "System.Collections.Generic.Dictionary",
"arrayBaseType": "System.Collections.ObjectModel.Collection",
"dictionaryBaseType": "System.Collections.Generic.Dictionary",
"propertySetterAccessModifier": "",
"generateImmutableArrayProperties": false,
"generateImmutableDictionaryProperties": false,
"handleReferences": false,
"jsonSerializerSettingsTransformationMethod": null,
"generateJsonMethods": false,
"enforceFlagEnums": false,
"inlineNamedDictionaries": false,
"inlineNamedTuples": true,
"inlineNamedArrays": false,
"generateOptionalPropertiesAsNullable": false,
"generateNullableReferenceTypes": false,
"generateNativeRecords": false,
"generateDefaultValues": true,
"inlineNamedAny": false,
"dateFormat": "yyyy-MM-dd",
"dateTimeFormat": "yyyy-MM-dd",
"excludedTypeNames": [
"ExcludedTypeFoo",
"ExcludedTypeBar"
]
}
}
openApiPath - points to the OpenAPI Specifications file. This can be the path to a file stored on disk, relative to the .refitter file. This can also be a URL to a remote file that will be downloaded over HTTP/HTTPSnamespace - the namespace used in the generated code. If not specified, this defaults to GeneratedCodenaming.useOpenApiTitle - a boolean indicating whether the OpenApi title should be used. Default is truenaming.interfaceName - the name of the generated interface. The generated code will automatically prefix this with I so if this set to MyApiClient then the generated interface is called IMyApiClient. Default is ApiClientgenerateContracts - a boolean indicating whether contracts should be generated. A use case for this is several API clients use the same contracts. Default is truegenerateXmlDocCodeComments - a boolean indicating whether XML doc comments should be generated. Default is trueaddAutoGeneratedHeader - a boolean indicating whether XML doc comments should be generated. Default is trueaddAcceptHeaders - a boolean indicating whether to add accept headers [Headers("Accept: application/json")]. Default is truereturnIApiResponse - a boolean indicating whether to return IApiResponse<T> objects. Default is falseresponseTypeOverride - a dictionary with operation ids (as specified in the OpenAPI document) and a particular return type to use. The types are wrapped in a task, but otherwise unmodified (so make sure to specify or import their namespaces). Default is {}generateOperationHeaders - a boolean indicating whether to use operation headers in the generated methods. Default is truetypeAccessibility - the generated type accessibility. Possible values are Public and Internal. Default is PublicuseCancellationTokens - Use cancellation tokens in the generated methods. Default is falseuseIsoDateFormat - Set to true to explicitly format date query string parameters in ISO 8601 standard date format using delimiters (for example: 2023-06-15). Default is falsemultipleInterfaces - Set to ByEndpoint to generate an interface for each endpoint, or ByTag to group Endpoints by their Tag (like SwaggerUI groups them).outputFolder - a string describing a relative path to a desired output folder. Default is ./GeneratedoutputFilename - Output filename. Default is Output.cs when used from the CLI tool, otherwise its the .refitter filename. So Petstore.refitter becomes Petstore.cs.additionalNamespaces - A collection of additional namespaces to include in the generated file. A use case for this is when you want to reuse contracts from a different namespace than the generated code. Default is emptyincludeTags - A collection of tags to use a filter for including endpoints that contain this tag.includePathMatches - A collection of regular expressions used to filter paths.generateDeprecatedOperations - a boolean indicating whether deprecated operations should be generated or skipped. Default is trueoperationNameTemplate - Generate operation names using pattern. This must contain the string {operationName}. An example usage of this could be {operationName}Async to suffix all method names with Async. When using "multipleIinterfaces": "ByEndpoint", This is name of the Execute() method in the interfaceoptionalParameters - Generate non-required parameters as nullable optional parametersuseDynamicQuerystringParameters: Set to true to wrap multiple query parameters into a single complex one. Default is false (no wrapping).dependencyInjectionSettings - Setting this will generated extension methods to IServiceCollection for configuring Refit clients. See https://github.com/reactiveui/refit?tab=readme-ov-file#dynamic-querystring-parameters for more information.
baseUrl - Used as the HttpClient base address. Leave this blank to manually set the base URLhttpMessageHandlers - A collection of HttpMessageHandler that is added to the HttpClient pipelinetransientErrorHandler - This is the transient error handler to use. Possible values are None, Polly, and HttpResilience. Default is NonemaxRetryCount - This is the max retry count used in the Polly retry policy. Default is 6firstBackoffRetryInSeconds - This is the duration of the initial retry backoff. Default is 1 secondapizrSettings - Setting this will format Refit interface to be managed by Apizr. See https://www.apizr.net for more information
withRequestOptions - Tells if the Refit interface methods should have a final IApizrRequestOptions options parameterwithRegistrationHelper - Tells if Refitter should generate Apizr registration helpers (extended with dependencyInjectionSettings set, otherwise static)withCacheProvider - Set the cache provider to be usedwithPriority - Tells if Apizr should handle request prioritywithMediation - Tells if Apizr should handle request mediation (extended only)withMappingProvider - Set the mapping provider to be usedwithFileTransfer - Tells if Apizr should handle file transfercodeGeneratorSettings - Setting this allows customization of the NSwag generated types and contracts
requiredPropertiesMustBeDefined - Default is true,generateDataAnnotations - Default is true,anyType - Default is object,dateType - Default is System.DateTimeOffset,dateTimeType - Default is System.DateTimeOffset,timeType - Default is System.TimeSpan,timeSpanType - Default is System.TimeSpan,arrayType - Default is System.Collections.Generic.ICollection,dictionaryType - Default is System.Collections.Generic.IDictionary,arrayInstanceType - Default is System.Collections.ObjectModel.Collection,dictionaryInstanceType - Default is System.Collections.Generic.Dictionary,arrayBaseType - Default is System.Collections.ObjectModel.Collection,dictionaryBaseType - Default is System.Collections.Generic.Dictionary,propertySetterAccessModifier - Default is ``,generateImmutableArrayProperties - Default is false,generateImmutableDictionaryProperties - Default is false,handleReferences - Default is false,jsonSerializerSettingsTransformationMethod - Default is null,generateJsonMethods - Default is false,enforceFlagEnums - Default is false,inlineNamedDictionaries - Default is false,inlineNamedTuples - Default is true,inlineNamedArrays - Default is false,generateOptionalPropertiesAsNullable - Default is false,generateNullableReferenceTypes - Default is false,generateNativeRecords - Default is falsegenerateDefaultValues - Default is trueinlineNamedAny - Default is falsedateFormat - Default is nulldateTimeFormatexcludedTypeNames - Default is empty