private void ProcessPath(string?apiRootPath, IEnumerable <ContractInfo> contracts, string?key) { _doc.Paths = new OpenApiPaths(); foreach (var contract in contracts) { var roles = _keyRoles.GetRoles(key); var roleMethods = contract.GetMethods(roles); foreach (var contractMethod in roleMethods) { foreach (var route in contractMethod.Route.SwaggerRouts) { var pathItem = new OpenApiPathItem(); foreach (var method in route.HttpMethods) { //AddOperation var operation = _pathProcessor.Process(contractMethod, route, method); pathItem.AddOperation(method.ToOperationType(), operation); } //add a path //_doc.Paths.Add($"{apiRootPath}/{route.Path}", pathItem); AddPath($"{apiRootPath}/{route.Path}", pathItem); } } } }
private OpenApiPathItem HealthPathItem() { var pathItem = new OpenApiPathItem(); pathItem.AddOperation(OperationType.Get, new OpenApiOperation { Tags = new List <OpenApiTag>() { new OpenApiTag() { Name = "Health" } }, OperationId = "Health_Get", Responses = new OpenApiResponses() { ["200"] = new OpenApiResponse { Description = "OK", }, }, }); return(pathItem); }
public void Apply(OpenApiDocument openApiDocument, DocumentFilterContext context) { var pathItem = new OpenApiPathItem(); var operation = new OpenApiOperation(); operation.Tags.Add(new OpenApiTag { Name = "GraphQL" }); operation.RequestBody = new OpenApiRequestBody() { Content = new Dictionary <string, OpenApiMediaType> { { "application/json", new OpenApiMediaType() { Schema = context.SchemaGenerator .GenerateSchema(typeof(Project), context.SchemaRepository), Example = new OpenApiString(query) } } } }; pathItem.AddOperation(OperationType.Post, operation); openApiDocument?.Paths.Add(graphEndpoint, pathItem); }
void AddPostOperation(IDebuggingHandler handler, OpenApiPathItem item, OpenApiOperation operation) { if (handler.GetType().ImplementsOpenGeneric(typeof(ICanHandlePostRequests <>))) { item.AddOperation(OperationType.Post, operation); } }
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { var logoutItem = new OpenApiPathItem(); logoutItem.AddOperation(OperationType.Post, new OpenApiOperation { Tags = new List <OpenApiTag> { new OpenApiTag { Name = "Authentication" } }, Parameters = new List <OpenApiParameter> { new OpenApiParameter { //Type = "string", Name = "Authorization", Required = false, In = ParameterLocation.Header } } }); swaggerDoc.Paths.Add($"/{Config.TokenLogoutRoute}", logoutItem); }
/// <summary> /// Add one operation into path item. /// </summary> /// <param name="item">The path item.</param> /// <param name="operationType">The operation type.</param> protected virtual void AddOperation(OpenApiPathItem item, OperationType operationType) { IOperationHandlerProvider provider = Context.OperationHanderProvider; IOperationHandler operationHander = provider.GetHandler(Path.Kind, operationType); item.AddOperation(operationType, operationHander.CreateOperation(Context, Path)); }
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { var tokenItem = new OpenApiPathItem(); tokenItem.AddOperation(OperationType.Post, new OpenApiOperation { Tags = new List <OpenApiTag> { new() { Name = "Authentication" } },
/// <summary> /// Include heath check. /// </summary> /// <param name="swaggerDoc"><see cref="OpenApiDocument"/></param> /// <param name="context"><see cref="DocumentFilterContext"/></param> public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { var pathItem = new OpenApiPathItem(); var operation = new OpenApiOperation(); operation.Tags.Add(new OpenApiTag { Name = "ApiHealth" }); pathItem.AddOperation(OperationType.Get, operation); swaggerDoc?.Paths.Add(_healthCheckEndpoint, pathItem); }
/// <summary> /// Add one operation into path item. /// </summary> /// <param name="item">The path item.</param> /// <param name="operationType">The operation type.</param> protected virtual void AddOperation(OpenApiPathItem item, OperationType operationType) { string httpMethod = operationType.ToString(); if (!Path.SupportHttpMethod(httpMethod)) { return; } IOperationHandlerProvider provider = Context.OperationHanderProvider; IOperationHandler operationHander = provider.GetHandler(Path.Kind, operationType); item.AddOperation(operationType, operationHander.CreateOperation(Context, Path)); }
private OpenApiPathItem GetOperationsForPath(ReRouteOptions route, OpenApiPathItem path) { IDictionary <OperationType, OpenApiOperation> operationsByTypes = route.UpstreamHttpMethod == null ? path.Operations : route.UpstreamHttpMethod .Select(x => Enum.TryParse <OperationType>(x, out var result) ? result : (OperationType?)null) .OfType <OperationType>() .ToDictionary( x => x, x => path.Operations.TryGetValue(x, out var result) ? result : null); var operations = new OpenApiPathItem(); foreach (var operationItem in operationsByTypes) { var typedVerb = operationItem.Key; var operation = operationItem.Value; if (operation == null) { _logger.LogWarning($"{typedVerb} not found for {route.DownstreamPath}"); return(null); } var predefinedParams = route.ChangeDownstreamPathTemplate.Keys.Select(s => s.ToLower()).ToList(); predefinedParams.Add(Constants.VersionVariableName); var filteredParameters = operation.Parameters .Where(p => !predefinedParams.Contains(p.Name.ToLower())) .Where(p => !route.AddQueriesToRequest.Keys.Select(k => k.ToLower()).Contains(p.Name.ToLower())); operation.Parameters = filteredParameters.ToList(); operations.AddOperation(typedVerb, operation); } return(operations); }
public void Apply(OpenApiDocument openApiDocument, DocumentFilterContext context) { var pathItem = new OpenApiPathItem(); var operation = new OpenApiOperation(); operation.Tags.Add(new OpenApiTag { Name = "ApiStatus" }); var properties = new Dictionary <string, OpenApiSchema> { { "status", new OpenApiSchema() { Type = "string" } }, { "errors", new OpenApiSchema() { Type = "array" } } }; var response = new OpenApiResponse(); response.Content.Add("application/json", new OpenApiMediaType { Schema = new OpenApiSchema { Type = "object", AdditionalPropertiesAllowed = true, Properties = properties, } }); operation.Responses.Add("200", response); pathItem.AddOperation(OperationType.Get, operation); openApiDocument?.Paths.Add(HealthCheckEndpoint, pathItem); }
public static void AddHealthCheckSwaggerOptions(this SwaggerOptions options) { var HealthReportResult = new OpenApiSchema { Properties = new Dictionary <string, OpenApiSchema> { { "name", new OpenApiSchema { Type = "string" } }, { "status", new OpenApiSchema { Type = "string" } }, { "duration", new OpenApiSchema { Type = "string" } }, { "description", new OpenApiSchema { Type = "string" } }, { "type", new OpenApiSchema { Type = "string" } }, { "data", new OpenApiSchema { Type = "object" } }, { "exception", new OpenApiSchema { Type = "string" } } }, Reference = new OpenApiReference { Id = "HealthReportResult", Type = ReferenceType.Schema } }; var HealthReport = new OpenApiSchema { Properties = new Dictionary <string, OpenApiSchema> { { "status", new OpenApiSchema { Type = "string" } }, { "duration", new OpenApiSchema { Type = "string" } }, { "results", new OpenApiSchema { Type = "array", Items = HealthReportResult } } }, Reference = new OpenApiReference { Id = "HealthReport", Type = ReferenceType.Schema } }; // var Security = new List<OpenApiSecurityRequirement>(); // Security.Add(new OpenApiSecurityRequirement{}); // // Security.Add(new Dictionary<string, IEnumerable<string>> // // { // // { "BearerAuth", new List<string>()} // // }); var Security = new List <OpenApiSecurityRequirement> { new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = "BearerAuth", Type = ReferenceType.SecurityScheme }, UnresolvedReference = true }, new List <string>() } } }; var IsAliveAndWellPath = new OpenApiPathItem(); IsAliveAndWellPath.AddOperation(OperationType.Get, new OpenApiOperation { Description = "Application Health Api", // OperationId = "findPets", // Parameters = new List<OpenApiParameter> // { // new OpenApiParameter // { // Name = "Authorization", // In = ParameterLocation.Header, // Description = "access token", // Required = false, // Schema = new OpenApiSchema{Type = "string"} // } // }, Security = Security, Responses = new OpenApiResponses { ["200"] = new OpenApiResponse { Description = "Healthy", Content = new Dictionary <string, OpenApiMediaType> { ["application/json"] = new OpenApiMediaType { Schema = HealthReport }, // ["application/xml"] = new OpenApiMediaType // { // Schema = new OpenApiSchema // { // Type = "object", // Items = HealthReport // } // } } }, ["4XX"] = new OpenApiResponse { Description = "unexpected client error", Content = new Dictionary <string, OpenApiMediaType> { ["text/html"] = new OpenApiMediaType { Schema = new OpenApiSchema { Type = "string", // Items = HealthReport } } } }, ["503"] = new OpenApiResponse { Description = "Unhealthy", Content = new Dictionary <string, OpenApiMediaType> { ["application/json"] = new OpenApiMediaType { Schema = HealthReport } } } } }); var IsAlivePath = new OpenApiPathItem(); IsAlivePath.AddOperation(OperationType.Get, new OpenApiOperation { }); options.PreSerializeFilters.Add((doc, req) => { doc.Components.Schemas.Add("HealthReport", HealthReport); doc.Components.Schemas.Add("HealthReportResult", HealthReportResult); doc.Paths.Add("/Health/IsAliveAndWell", IsAliveAndWellPath); doc.Paths.Add("/Health/IsAlive", IsAlivePath); }); // // Responses = new Dictionary<string, OpenApiResponse>{ // // {"200",new OpenApiResponse{Description="Success", Schema = new OpenApiSchema{Items=HealthReport}}}, // // {"503",new OpenApiResponse{Description="Failed"}} // // }, // // Security = Security, // // Parameters = new List<IParameter>{ // // new NonBodyParameter // // { // // Name = "Authorization", // // In = "header", // // Description = "access token", // // Required = true, // // Type = "string", // // Default = "Bearer " // // } // // } // }) // }); // doc.Paths.Add("/Health/IsAlive", new PathItem // { // Get = new Operation // { // Tags = new List<string> { "HealthCheck" }, // Produces = new string[] { "application/json" }, // Responses = new Dictionary<string, Response>{ // {"200",new Response{Description="Success", // Schema = new Schema{}}}, // {"503",new Response{Description="Failed"}} // }, // Security = Security, // } // }); }
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { var serviceDiscovery = JimuClient.Host.Container.Resolve <IClientServiceDiscovery>(); var routes = serviceDiscovery.GetRoutesAsync().GetAwaiter().GetResult(); var groupRoutes = routes.GroupBy(x => x.ServiceDescriptor.RoutePath); swaggerDoc.Components.SecuritySchemes = new Dictionary <string, OpenApiSecurityScheme> { { "bearerAuth", new OpenApiSecurityScheme { Type = SecuritySchemeType.Http, In = ParameterLocation.Header, Scheme = "bearer", BearerFormat = "JWT", Name = "bearerAuth", Reference = new OpenApiReference() { Id = "bearerAuth", Type = ReferenceType.SecurityScheme }, UnresolvedReference = false } } }; foreach (var gr in groupRoutes) { var route = gr.Key; var pathItem = new OpenApiPathItem(); foreach (var r in gr) { var x = r.ServiceDescriptor; var paras = new List <OpenApiParameter>(); var jimuParas = new List <JimuServiceParameterDesc>(); if (!string.IsNullOrEmpty(x.Parameters)) { jimuParas = JimuHelper.Deserialize(TypeHelper.ReplaceTypeToJsType(x.Parameters), typeof(List <JimuServiceParameterDesc>)) as List <JimuServiceParameterDesc>; paras = GetParameters(route, jimuParas, x.HttpMethod); } var responses = new OpenApiResponses(); responses.Add("200", GetResponse(x.ReturnDesc)); OpenApiOperation operation = new OpenApiOperation { OperationId = x.RoutePath, Parameters = paras, Responses = responses, Description = x.Comment, Summary = x.Comment, Tags = GetTags(x), RequestBody = GetRequestBody(route, jimuParas, x.HttpMethod) }; if (Enum.TryParse(typeof(OperationType), CultureInfo.CurrentCulture.TextInfo.ToTitleCase(x.HttpMethod.ToLower()), out var opType)) { pathItem.AddOperation((OperationType)opType, operation); } if (!x.GetMetadata <bool>("AllowAnonymous")) { operation.Security = new List <OpenApiSecurityRequirement> { new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference() { Id = "bearerAuth", Type = ReferenceType.SecurityScheme }, UnresolvedReference = true }, new List <string>() } } }; } } swaggerDoc.Paths.Add(route, pathItem); } }
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { var tokenItem = new OpenApiPathItem(); tokenItem.AddOperation(OperationType.Post, new OpenApiOperation { Tags = new List <OpenApiTag> { new OpenApiTag { Name = "Authentication" } }, //Consumes = new List<string> { "application/x-www-form-urlencoded" }, Parameters = new List <OpenApiParameter> { new OpenApiParameter { //Type = "string", Name = "username", Required = false, //In = "formData" }, new OpenApiParameter { //Type = "string", Name = "password", Required = false, //In = "formData" } } }); swaggerDoc.Paths.Add($"/{Config.TokenRoute}", tokenItem); var logoutItem = new OpenApiPathItem(); logoutItem.AddOperation(OperationType.Post, new OpenApiOperation { Tags = new List <OpenApiTag> { new OpenApiTag { Name = "Authentication" } }, Parameters = new List <OpenApiParameter> { new OpenApiParameter { //Type = "string", Name = "Authorization", Required = false, In = ParameterLocation.Header } } }); swaggerDoc.Paths.Add($"/{Config.TokenLogoutRoute}", logoutItem); //swaggerDoc.Paths.Add($"/{Config.TokenLogoutRoute}", new PathItem //{ // Post = new Operation // { // Tags = new List<string> { "Authentication" }, // Parameters = new List<IParameter> // { // new NonBodyParameter // { // Type = "string", // Name = "Authorization", // Required = false, // In = "header" // } // } // } //}); }
protected override void AddOperation(OpenApiPathItem item, OperationType operationType) { item.AddOperation(operationType, new OpenApiOperation()); }
private void ProcessPath(string apiRootPath, List <Contract> contracts) { _doc.Paths = new OpenApiPaths(); foreach (var contract in contracts) { foreach (var contractMethod in contract.ContractInfo.Methods) { if (contractMethod.IsHttpIgnore) { continue; } //Operation var operation = new OpenApiOperation { Tags = GenerateTags(contract, contractMethod), RequestBody = GenerateRequestBody(contractMethod.MergeArgType.TypeWithoutStreamName, contractMethod.MergeArgType.StreamPropName), Responses = GenerateResponses(contractMethod, contractMethod.MergeArgType.CancelToken != null) }; //Summary var filterContext = new OperationFilterContext(new ApiDescription(), _schemaGenerator, _schemaRepository, contractMethod.MethodInfo); foreach (var filter in _options.OperationFilters) { filter.Apply(operation, filterContext); } operation.Summary = AppendSummaryByCallbackAndCancel(operation.Summary, contractMethod.MergeArgType.CallbackAction, contractMethod.MergeArgType.CancelToken); //Header operation.Parameters = new List <OpenApiParameter>(); foreach (var header in contractMethod.HttpHeaderAttributes) { operation.Parameters.Add(new OpenApiParameter { In = ParameterLocation.Header, Name = header.Name, Description = header.Description, Schema = new OpenApiSchema { Type = "string" } }); } //ApiSecurity foreach (var apiKey in contractMethod.SecurityApiKeyAttributes) { var r = new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = apiKey.Key, Type = ReferenceType.SecurityScheme }, UnresolvedReference = true }, new List <string>() } }; operation.Security.Add(r); } var openApiPathItem = new OpenApiPathItem(); openApiPathItem.AddOperation(OperationType.Post, operation); var key = $"{apiRootPath}/{contractMethod.HttpRoutInfo}"; _doc.Paths.Add(key, openApiPathItem); } } }
public OpenApiDocument GetDocument() { var collections = _collections; var swaggerDoc = new OpenApiDocument(); swaggerDoc.Info = new OpenApiInfo() { Title = _api.designation, Description = _api.description, Version = _options.Version }; swaggerDoc.Servers.Add(new OpenApiServer() { Description = _api.designation + " server", Url = _options.BasePath }); var paths = new OpenApiPaths(); foreach (var collection in collections) { swaggerDoc.Tags.Add(new OpenApiTag() { Name = collection.collectionname, Description = collection.description, }); //var collection_attributes = new List<Attribute>(); var collection_keyattributes = new SortedList <int, Data.Models.Attribute>(); var openApiParameters = new List <OpenApiParameter>(); foreach (var attribute in collection.attributes) { if (attribute.keyindex.HasValue) { collection_keyattributes.Add(attribute.keyindex.Value, attribute); openApiParameters.Add(new OpenApiParameter() { Name = attribute.attributename, In = ParameterLocation.Path }); } } if (collection.attributes.Count() <= 0) { continue; } List <OpenApiParameter> fiqlParameters = null; if (collection.attributes.Where(x => x.fiqlkeyindex.HasValue).Count() > 0) { fiqlParameters = new List <OpenApiParameter>(); string fiqlDescription = @"query is the place where collection can be requested with criterias. "; fiqlDescription += "If used, the query has to be compliant with FIQL specification (https://tools.ietf.org/html/draft-nottingham-atompub-fiql-00).\n"; fiqlDescription += "Only the following attributes can be requested via the query : "; fiqlDescription += collection.attributes.Where(x => x.fiqlkeyindex.HasValue).OrderBy(x => x.fiqlkeyindex.Value).Aggregate("", (current, next) => current + ", " + next.attributename).Remove(0, 2); fiqlDescription += "."; fiqlParameters.Add(new OpenApiParameter() { Name = "query", In = ParameterLocation.Query, Description = fiqlDescription, Required = false }); } string idDescription = ""; for (int index = 0; index < collection_keyattributes.Count; index++) { if (idDescription.Length > 0) { idDescription += ","; } idDescription += "{" + collection_keyattributes.Values[index].attributename + "}"; } if (collection_keyattributes.Count > 1) { idDescription = "(" + idDescription + ")"; } var collectionPathItem = new OpenApiPathItem(); var memberPathItem = new OpenApiPathItem(); if (collection.publish_getcollection) { collectionPathItem.AddOperation(OperationType.Get, new OpenApiOperation() { Description = "Returns a collection of " + collection.collectionname + ".", Parameters = fiqlParameters, OperationId = "get_" + collection.collectionname, Tags = new List <OpenApiTag> { new OpenApiTag() { Name = collection.collectionname } }, Responses = new OpenApiResponses() .WithCollectionReturnedSuccessResponse(collection) .WithBadRequestResponse(collection) .WithUnauthorizedErrorResponse() .WithForbiddenErrorResponse() .WithUnprocessableEntityErrorResponse() .WithInternalServerErrorResponse() });; } if (collection.publish_getmember) { memberPathItem.AddOperation(OperationType.Get, new OpenApiOperation() { Description = "Returns a member of the collection of " + collection.collectionname + ".", Parameters = openApiParameters, Tags = new List <OpenApiTag> { new OpenApiTag() { Name = collection.collectionname } }, OperationId = "get_" + collection.membername, Responses = new OpenApiResponses() .WithMemberReturnedSuccessResponse(collection) .WithNotFoundErrorResponse(collection) .WithUnauthorizedErrorResponse() .WithForbiddenErrorResponse() .WithUnprocessableEntityErrorResponse() .WithInternalServerErrorResponse() }); } if (collection.publish_postmember) { collectionPathItem.AddOperation(OperationType.Post, new OpenApiOperation() { Description = "Post a new " + collection.membername + ".", OperationId = "post_" + collection.collectionname, Tags = new List <OpenApiTag> { new OpenApiTag() { Name = collection.collectionname } }, RequestBody = new OpenApiRequestBody().WithMemberContent(collection, false), Responses = new OpenApiResponses() .WithCreatedSuccessResponse(_options.Upsert_FillBodyWithMember, collection) .WithConstraintErrorResponse(collection) .WithUnauthorizedErrorResponse() .WithForbiddenErrorResponse() .WithUnprocessableEntityErrorResponse() .WithInternalServerErrorResponse(), }); } if (collection.publish_putmember) { memberPathItem.AddOperation(OperationType.Put, new OpenApiOperation() { Description = "Put (upsert operation) a " + collection.membername + " in the collection " + collection.collectionname + ".", Parameters = openApiParameters, OperationId = "put_" + collection.collectionname, Tags = new List <OpenApiTag> { new OpenApiTag() { Name = collection.collectionname } }, RequestBody = new OpenApiRequestBody().WithMemberContent(collection, true), Responses = new OpenApiResponses() .WithCreatedSuccessResponse(_options.Upsert_FillBodyWithMember, collection) .WithUpdatedSuccessResponse(_options.Upsert_FillBodyWithMember, collection) .WithUnchangedResponse(collection) .WithUnauthorizedErrorResponse() .WithForbiddenErrorResponse() .WithUnprocessableEntityErrorResponse() .WithInternalServerErrorResponse(), }); } if (collection.publish_patchmember) { memberPathItem.AddOperation(OperationType.Patch, new OpenApiOperation() { Description = "Patch (update operation) a " + collection.membername + " in the collection " + collection.collectionname + ".", Parameters = openApiParameters, OperationId = "patch_" + collection.collectionname, Tags = new List <OpenApiTag> { new OpenApiTag() { Name = collection.collectionname } }, RequestBody = new OpenApiRequestBody().WithPatchContent(collection), Responses = new OpenApiResponses() .WithUpdatedSuccessResponse(collection) .WithUnchangedResponse(collection) .WithUnauthorizedErrorResponse() .WithForbiddenErrorResponse() .WithUnprocessableEntityErrorResponse() .WithInternalServerErrorResponse(), }); } if (collection.publish_deletemember) { memberPathItem.AddOperation(OperationType.Delete, new OpenApiOperation() { Description = "Delete a member of the collection " + collection.collectionname + ".", Parameters = openApiParameters, Tags = new List <OpenApiTag> { new OpenApiTag() { Name = collection.collectionname } }, OperationId = "delete_" + collection.membername, Responses = new OpenApiResponses() .WithDeletedSuccessResponse(collection) .WithUnauthorizedErrorResponse() .WithForbiddenErrorResponse() .WithUnprocessableEntityErrorResponse() .WithInternalServerErrorResponse(), }); } paths.Add("/" + collection.collectionname, collectionPathItem); paths.Add("/" + collection.collectionname + "/" + idDescription, memberPathItem); } swaggerDoc.Paths = paths; return(swaggerDoc); }