public static IServiceCollection AddSwagger(this IServiceCollection services) { return(services.AddSwaggerGen(c => { var provider = services.BuildServiceProvider().GetService <IApiVersionDescriptionProvider>(); if (provider?.ApiVersionDescriptions != null) { // add a swagger document for each discovered API version // note: you might choose to skip or document deprecated API versions differently foreach (var description in provider.ApiVersionDescriptions) { var info = new OpenApiInfo { Title = $"ActivityCalculator API {description.ApiVersion.ToString()}", Version = description.ApiVersion.ToString() }; if (description.IsDeprecated) { info.Description += "DEPRECATED"; } c.SwaggerDoc(description.GroupName, info); } } })); }
public ConfigureSwaggerOptions( IApiVersionDescriptionProvider provider, IOptions <OpenApiInfo> options) { _provider = provider; _openApiInfo = options.Value; }
static OpenApiInfo CreateInfoForApiVersion(ApiVersionDescription description) { var info = new OpenApiInfo() { Title = $"CalculatorApi {description.ApiVersion}", Version = description.ApiVersion.ToString(), Description = "CalculatorApi", Contact = new OpenApiContact() { Name = "Iain Kiloh", Email = "*****@*****.**" }, TermsOfService = new System.Uri("https://kilohsoftware.com"), License = new OpenApiLicense() { Name = "None", Url = new System.Uri("https://kilohsoftware.com") } }; if (description.IsDeprecated) { info.Description += " This API version has been deprecated."; } return(info); }
/// <summary> /// Visits <see cref="OpenApiInfo"/> and child objects /// </summary> /// <param name="info"></param> internal void Walk(OpenApiInfo info) { _visitor.Visit(info); Walk(info.Contact); Walk(info.License); Walk(info as IOpenApiExtensible); }
public void GetSwagger_GeneratesSwagger_ForEachConfiguredDocument() { var v1Info = new OpenApiInfo { Version = "v2", Title = "API V2" }; var v2Info = new OpenApiInfo { Version = "v1", Title = "API V1" }; var subject = Subject( setupApis: apis => { apis.Add("GET", "v1/collection", nameof(FakeController.ReturnsEnumerable)); apis.Add("GET", "v2/collection", nameof(FakeController.ReturnsEnumerable)); }, setupAction: c => { c.SwaggerDocs.Clear(); c.SwaggerDocs.Add("v1", v1Info); c.SwaggerDocs.Add("v2", v2Info); c.DocInclusionPredicate = (docName, api) => api.RelativePath.StartsWith(docName); }); var v1Swagger = subject.GetSwagger("v1"); var v2Swagger = subject.GetSwagger("v2"); Assert.Equal(new[] { "/v1/collection" }, v1Swagger.Paths.Keys.ToArray()); Assert.Equal(v1Info, v1Swagger.Info); Assert.Equal(new[] { "/v2/collection" }, v2Swagger.Paths.Keys.ToArray()); Assert.Equal(v2Info, v2Swagger.Info); }
private static void ConfigureSwagger(IServiceCollection serviceCollection, OpenApiInfo openApiInfo) { serviceCollection.AddSwaggerGen(c => { c.SwaggerDoc(openApiInfo.Version, new OpenApiInfo { Title = openApiInfo.Title, Version = openApiInfo.Version }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new[] { "readAccess", "writeAccess" } } }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); }
/// <summary> /// Use OpenAPI specification /// </summary> /// <param name="services">Collections of services in application</param> /// <param name="prometheusScrapeEndpointPath">Endpoint where the prometheus scraping is exposed</param> /// <param name="apiVersion">Version of the API</param> public static IServiceCollection UseOpenApiSpecifications(this IServiceCollection services, string prometheusScrapeEndpointPath, int apiVersion) { var openApiInformation = new OpenApiInfo { Contact = new OpenApiContact { Name = "Tom Kerkhove", Url = new Uri("https://blog.tomkerkhove.be") }, Title = $"Promitor v{apiVersion}", Description = $"Collection of APIs to manage the Azure Monitor scrape endpoint for Prometheus.\r\nThe scrape endpoint is exposed at '<a href=\"./../..{prometheusScrapeEndpointPath}\" target=\"_blank\">{prometheusScrapeEndpointPath}</a>'", Version = $"v{apiVersion}", License = new OpenApiLicense { Name = "MIT", Url = new Uri("https://github.com/tomkerkhove/promitor/LICENSE") } }; var xmlDocumentationPath = GetXmlDocumentationPath(services); services.AddSwaggerGen(swaggerGenerationOptions => { swaggerGenerationOptions.EnableAnnotations(); swaggerGenerationOptions.SwaggerDoc($"v{apiVersion}", openApiInformation); if (string.IsNullOrEmpty(xmlDocumentationPath) == false) { swaggerGenerationOptions.IncludeXmlComments(xmlDocumentationPath); } }); return(services); }
/// <summary> /// Internal implementation for building the Swagger basic config. /// </summary> /// <param name="description">The description object containing the.</param> /// <param name="apiInfo"></param> /// <returns>The generated Open API info.</returns> private static OpenApiInfo CreateInfoForApiVersion(ApiVersionDescription description, ApiInfoOptions apiInfo) { var info = new OpenApiInfo { Title = apiInfo.Title, Version = description.ApiVersion.ToString(), Description = apiInfo.Description, TermsOfService = new Uri(apiInfo.TermsOfService), Contact = new OpenApiContact { Name = apiInfo.Contact.Name, Email = apiInfo.Contact.Email, Url = new Uri(apiInfo.Contact.Url) }, License = new OpenApiLicense { Name = apiInfo.License.Name } }; if (description.IsDeprecated) { info.Description += @"<p><strong><span style=""color:white;background-color:red"">VERSION IS DEPRECATED</span></strong></p>"; } return(info); }
private static OpenApiInfo CreateInfoForApiVersion(ApiVersionDescription description) { var info = new OpenApiInfo() { Title = "Blockcore Node API", Version = description.ApiVersion.ToString(), Description = "Access to the Blockcore Node features.", Contact = new OpenApiContact { Name = "Blockcore", Url = new Uri("https://www.blockcore.net/") } }; if (info.Version.Contains("dev")) { info.Description += " This version of the API is in development and subject to change. Use an earlier version for production applications."; } if (description.IsDeprecated) { info.Description += " This API version has been deprecated."; } return(info); }
private OpenApiInfo CreateInfoForApiVersion(ApiVersionDescription description) { var openApiInfo = new OpenApiInfo() { Title = "API - ihtech.io", Version = description.ApiVersion.ToString(), Description = "Esta API faz parte do curso REST AspNet Core com WebApi", Contact = new OpenApiContact() { Name = "Icaro Henrique", Email = "*****@*****.**" }, TermsOfService = new System.Uri("https://opensource.org/licenses/MIT"), License = new OpenApiLicense() { Name = "MIT", Url = new System.Uri("https://opensource.org/licenses/MIT") } }; if (description.IsDeprecated) { openApiInfo.Description += "Esta versão está obsoleta!"; } return(openApiInfo); }
public static void ConfigureDocs(IServiceCollection services, OpenApiInfo apiInfo) { services.AddSwaggerGen(c => { c.SwaggerDoc(SwaggerDocumentName, apiInfo); }); }
public void ConfigureServices(IServiceCollection services) { var sqlServerConnectionString = Configuration.GetConnectionString("default"); services.AddDbContext <BilSoftTaskContext>(options => options.UseSqlServer(sqlServerConnectionString).EnableSensitiveDataLogging(true)); services.AddScoped <DbContext, BilSoftTaskContext>(); services.AddScoped <IRepository <Product>, SqlRepository <Product> >(); services.AddScoped <IRepository <Category>, SqlRepository <Category> >(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddScoped <IProductService, ProductService>(); services.AddScoped <ICategoryService, CategoryService>(); services.AddControllers(); services.AddAutoMapper(typeof(Startup)); var apiInfo = new OpenApiInfo() { Title = "BilSoft Task API" }; services.AddSwaggerGen(options => options.SwaggerDoc("v1", apiInfo)); var client = Configuration.GetValue <string>("Client"); services.AddCors(options => options.AddPolicy(corsPolicyName, builder => builder.WithOrigins(client).AllowAnyHeader().AllowAnyMethod())); }
private void ConfigureSwagger(IServiceCollection services) { var contact = new OpenApiContact() { Name = "Daniil Nichitenco", Email = "*****@*****.**", Url = new Uri("http://www.example.com") }; var license = new OpenApiLicense() { Name = "My License", Url = new Uri("http://www.example.com") }; var info = new OpenApiInfo() { Version = "v1", Title = "Swagger Expense Tracker API", Description = "Swagger Expense Tracker API Description", TermsOfService = new Uri("http://www.example.com"), Contact = contact, License = license }; services.AddSwaggerGen(c => { c.SwaggerDoc("v1", info); }); }
public static IServiceCollection AddSwaggerConfiguration(this IServiceCollection services) { var contact = new OpenApiContact() { Name = "Demo API", Email = "*****@*****.**" }; var license = new OpenApiLicense() { Name = "Demo API", Url = new Uri("https://demoapi.com") }; var info = new OpenApiInfo() { Version = "v1", Title = "Demo API", Description = "Demo API", TermsOfService = new Uri("https://demoapi.com"), Contact = contact, License = license }; services.AddSwaggerGen(c => { c.SwaggerDoc("DemoAPI", info); c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); //Adding configuration of jwt for swagger UI ---------------------------------- c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() { Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "Bearer" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new List <string>() } }); //---------------------------------------- }); return(services); }
private void ConfigureSwagger(IServiceCollection services) { var contact = new OpenApiContact() { Name = "FirstName LastName", Email = "*****@*****.**", Url = new Uri("http://www.example.com") }; var license = new OpenApiLicense() { Name = "My License", Url = new Uri("http://www.example.com") }; var info = new OpenApiInfo() { Version = "v1", Title = "Swagger Demo API", Description = "Swagger Demo API Description", TermsOfService = new Uri("http://www.example.com"), Contact = contact, License = license }; services.AddSwaggerGen(c => { c.SwaggerDoc("v1", info); }); }
public Startup(IConfiguration configuration) { this.openApiInfo = new OpenApiInfo { Title = "Generic Demo Api", Description = "", Version = "v1" }; this.configuration = configuration; }
public static IServiceCollection AddSwagger(this IServiceCollection services, IConfiguration configuration) { ApiDetails apiDetails = new ApiDetails(); configuration.GetSection("ApiDetails").Bind(apiDetails); services.AddSwaggerGen(options => { var info = new OpenApiInfo { Title = $"{apiDetails.Title} - {apiDetails.Owners}", Version = "v1", Description = $"### {apiDetails.Description}\n" + $"### [{apiDetails.Title} Git Repository]({apiDetails.GitRepoUrl})" }; options.SwaggerDoc("v1", info); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); options.IncludeXmlComments(xmlPath); }); return(services); }
//apiDescription.GroupName.ToLower().Contains(version.ToLower()); /// <summary> /// Ask Kurt, I abstracted common declarations /// </summary> /// <param name="version"></param> /// <returns></returns> public static OpenApiInfo CreateInfoForApiVersion(string version) { string description = "API Documentation of the Assistant for Scrap Mechanic API"; if (version.Equals(ApiAccess.Public)) { description = "Easy to use endpoints, these are Public endpoints that do not need a JWT token to work. These endpoints should never return 401 or 403 error codes."; } //if (version.Equals(ApiAccess.Auth)) description = "Authenticated endpoints that do require a valid JWT token (passed in the header 'Authorization': 'Bearer xxxxx') to work. \n\rYou can get the JWT token by logging into the /Auth controller using Basic Authentication (passed in the header 'Authorization': 'Basic xxxxx='), the token is returned in the header."; if (version.Equals(ApiAccess.All)) { description = "All endpoints, those that are Public and those that require you to be logged in."; } OpenApiInfo info = new OpenApiInfo { Version = version, Title = "Assistant for Scrap Mechanic API", Description = description, Contact = new OpenApiContact { Name = "AssistantSMS", Email = "*****@*****.**", Url = new Uri("https://scrapassistant.com") } }; return(info); }
public static IServiceCollection AddSwagger( this IServiceCollection services, SwaggerSettings swaggerSettings, List <string> xmls, string tokenKey = null, OpenApiSecurityScheme oass = null, OpenApiSecurityRequirement oasr = null ) { var oai = new OpenApiInfo { Title = swaggerSettings.Title, Version = swaggerSettings.Version, }; return(services.AddSwaggerGen(options => { options.SwaggerDoc(swaggerSettings.Code, oai); options.EnableAnnotations(); options.DocumentFilter <ApiHiddenFilter>(); options.DocumentFilter <PropertyHiddenFilter>(); options.DocumentFilter <EnumDescriptionFilter>(); foreach (string xml in xmls) { options.IncludeXmlComments(xml, true); } if (!tokenKey.IsEmptyString() && oass != null && oasr != null) { options.AddSecurityDefinition(tokenKey, oass); options.AddSecurityRequirement(oasr); } })); }
private void ConfigureSwagger(IServiceCollection services) { var contact = new OpenApiContact() { Name = "Ivan Scoropad", Email = "*****@*****.**", }; var license = new OpenApiLicense() { Name = "My License", }; var info = new OpenApiInfo() { Version = "v1", Title = "Swagger Demo API", Description = "Swagger Api YourChoice", Contact = contact, License = license }; services.AddSwaggerGen(c => { c.SwaggerDoc("v1", info); }); }
/// <summary> /// Adds Swagger services and configures the Swagger services. /// </summary> public static IServiceCollection AddSwaggerOptionService(this IServiceCollection services) { services.AddSwaggerGen(options => { var assembly = typeof(Startup).Assembly; var assemblyProduct = assembly.GetCustomAttribute <AssemblyProductAttribute>().Product; var assemblyDescription = assembly.GetCustomAttribute <AssemblyDescriptionAttribute>()?.Description; options.DescribeAllParametersInCamelCase(); options.OperationFilter <ApiVersionOperationFilter>(); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = System.IO.Path.Combine(System.AppContext.BaseDirectory, xmlFile); options.IncludeXmlComments(xmlPath); var provider = services.BuildServiceProvider().GetRequiredService <IApiVersionDescriptionProvider>(); foreach (var apiVersionDescription in provider.ApiVersionDescriptions) { if (apiVersionDescription.IsDeprecated) { continue; } var info = new OpenApiInfo() { Title = assemblyProduct, Description = apiVersionDescription.IsDeprecated ? $"{assemblyDescription} This API version has been deprecated." : assemblyDescription, Version = apiVersionDescription.ApiVersion.ToString(), }; options.SwaggerDoc(apiVersionDescription.GroupName, info); } //https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1295 //https://stackoverflow.com/questions/58197244/swaggerui-with-netcore-3-0-bearer-token-authorization //options.OperationFilter<TokenOperationFilter>(); var securitySchema = new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "bearer", Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }; options.AddSecurityDefinition("Bearer", securitySchema); var securityRequirement = new OpenApiSecurityRequirement(); securityRequirement.Add(securitySchema, new[] { "Bearer" }); options.AddSecurityRequirement(securityRequirement); }); return(services); }
public static IServiceCollection AddCustomOpenApi(this IServiceCollection services, string title = DefaultOpenApiTitle, string version = DefaultOpenApiVersion, Func <ApiDescription, string> operationIdSelector = null) { if (string.IsNullOrWhiteSpace(title)) { throw new ArgumentException(nameof(title)); } if (string.IsNullOrWhiteSpace(version)) { throw new ArgumentException(nameof(version)); } services.AddSwaggerGen(setupAction => { // Do we wish to override the current operationId with some custom logic? if (operationIdSelector != null) { setupAction.CustomOperationIds(operationIdSelector); } var info = new OpenApiInfo { Title = title, Version = version }; setupAction.SwaggerDoc(version, info); }); return(services); }
private static void AddSwagger(this IServiceCollection services) { services.AddSwaggerGen(config => { // TODO: use config.json file for this values var openApiContact = new OpenApiContact() { Name = "Beso Genebashvili", Email = "*****@*****.**", Url = new Uri("https://github.com/BesoGenebashvili") }; var openApiInfo = new OpenApiInfo() { Version = "v1", Title = "BlogEngine.API", Description = "This is a Web API for BlogEngine project", Contact = openApiContact }; config.SwaggerDoc("v1", openApiInfo); string xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; string xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); config.IncludeXmlComments(xmlPath); }); }
public static IServiceCollection AddSwaggerConfiguration(this IServiceCollection services, IConfiguration config) { services .AddSwaggerGen(c => { var info = new OpenApiInfo { Title = config.GetDocumentTitle(), Version = config.GetDocumentVersion() }; var documentName = config.GetDocumentName(); c.SwaggerDoc(documentName, info); c.AddSecurity(config); var filePath = Path.Combine( AppContext.BaseDirectory, "WebApiCorona.xml"); c.IncludeXmlComments(filePath); }); return(services); }
public static Action <SwaggerGenOptions> Create() { var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var openApiInfo = new OpenApiInfo { Title = "Speech - API", Version = "v1", Description = "Conjunto de APIs para TCC (Desenvolvimento Mobile)", Contact = new OpenApiContact { Name = "Diogo 'Nitro' Fernandes", Url = new Uri("https://www.nitrocodes.com") } }; return(options => { options.SwaggerDoc("v1", openApiInfo); options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFile)); options.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); options.OrderActionsBy(d => d.GroupName); options.EnableAnnotations(); options.CustomSchemaIds(x => x.FullName); options.DescribeAllParametersInCamelCase(); }); }
/// <summary> /// /// </summary> /// <param name="services"></param> /// <param name="name">A URI-friendly name that uniquely identifies the document</param> /// <param name="info">Global meta data to be included in the Swagger output</param> public static void AddSwagger(this IServiceCollection services, string name, OpenApiInfo info, List <string> xmlFiles = null) { #region Swagger services.AddSwaggerGen(c => { c.SwaggerDoc(name, info); if (xmlFiles == null || !xmlFiles.Any()) { return; } var basePath = AppContext.BaseDirectory; xmlFiles.ForEach(p => { var xmlPath = Path.Combine(basePath, p); if (XmlFilePathCache.Contains(xmlPath)) { return; } c.IncludeXmlComments(xmlPath); XmlFilePathCache.Add(xmlPath); }); }); #endregion }
private OpenApiInfo CreateInfoForApiVersion(ApiVersionDescription description) { var info = new OpenApiInfo { Title = string.Format(_openApiInfo.Title ?? "ShaProjectName Api", description.ApiVersion.ToString()), Version = description.ApiVersion.ToString(), Description = _openApiInfo.Description, Contact = new OpenApiContact { Name = _openApiInfo.Contact?.Name, Email = _openApiInfo.Contact?.Email, Url = _openApiInfo.Contact?.Url }, TermsOfService = _openApiInfo.TermsOfService, License = new OpenApiLicense { Name = _openApiInfo.License?.Name, Url = _openApiInfo.License?.Url } }; if (description.IsDeprecated) { info.Description += " This API version has been deprecated."; } return(info); }
public Startup(IConfiguration configuration) { this.openApiInfo = new OpenApiInfo { Title = "Artist Stats Api", Description = "", Version = "v1" }; this.configuration = configuration; }
/// <summary> /// Define one or more documents to be created by the Swagger generator /// </summary> /// <param name="swaggerGenOptions"></param> /// <param name="name">A URI-friendly name that uniquely identifies the document</param> /// <param name="info">Global metadata to be included in the Swagger output</param> public static void SwaggerDoc( this SwaggerGenOptions swaggerGenOptions, string name, OpenApiInfo info) { swaggerGenOptions.SwaggerGeneratorOptions.SwaggerDocs.Add(name, info); }
public OpenApiDocument GenerateDocument(OpenApiInfo openApiInfo, IEnumerable <RestEndpoint> restEndpoints, IEnumerable <ResponseValue> responseValues, IEnumerable <Type> types) { var document = new OpenApiDocument() { Info = openApiInfo, // TODO: auto discover this somehow? Servers = new List <OpenApiServer>() { new OpenApiServer() { Url = "https://localhost:7071/" }, }, }; var responses = BuildResponses(responseValues); var schemas = BuildSchemas(types); document.Components = new OpenApiComponents() { Responses = responses as Dictionary <string, OpenApiResponse>, Schemas = schemas as Dictionary <string, OpenApiSchema>, }; document.Paths = BuildPaths(restEndpoints); return(document); }