Repository: abelsilva/swaggerwcf Branch: master Commit: 3b0bc754a2cc Files: 102 Total size: 394.2 KB Directory structure: gitextract_tza6k42w/ ├── .gitignore ├── .gitmodules ├── LICENSE ├── README.md ├── notes/ │ ├── samples/ │ │ ├── petstore-expanded.json │ │ ├── petstore-minimal.json │ │ ├── petstore-simple.json │ │ ├── petstore-with-external-docs.json │ │ └── petstore.json │ ├── schema.json │ └── spec-2.0.md └── src/ ├── SwaggerWcf/ │ ├── Attributes/ │ │ ├── SwaggerWcfAttribute.cs │ │ ├── SwaggerWcfContactInfoAttribute.cs │ │ ├── SwaggerWcfContentTypesAttribute.cs │ │ ├── SwaggerWcfDefinitionAttribute.cs │ │ ├── SwaggerWcfHeaderAttribute.cs │ │ ├── SwaggerWcfHiddenAttribute.cs │ │ ├── SwaggerWcfLicenseInfoAttribute.cs │ │ ├── SwaggerWcfParameterAttribute.cs │ │ ├── SwaggerWcfPathAttribute.cs │ │ ├── SwaggerWcfPropertyAttribute.cs │ │ ├── SwaggerWcfRegexAttribute.cs │ │ ├── SwaggerWcfRequestTypeAttribute.cs │ │ ├── SwaggerWcfResponseAttribute.cs │ │ ├── SwaggerWcfReturnTypeAttribute.cs │ │ ├── SwaggerWcfSecurityAttribute.cs │ │ ├── SwaggerWcfServiceInfoAttribute.cs │ │ └── SwaggerWcfTagAttribute.cs │ ├── Configuration/ │ │ ├── SettingCollection.cs │ │ ├── SettingElement.cs │ │ ├── SwaggerWcfSection.cs │ │ ├── TagCollection.cs │ │ └── TagElement.cs │ ├── ISwaggerWcfEndpoint.cs │ ├── Models/ │ │ ├── CollectionFormat.cs │ │ ├── Definition.cs │ │ ├── DefinitionProperty.cs │ │ ├── DefinitionSchema.cs │ │ ├── Example.cs │ │ ├── ExternalDocumentation.cs │ │ ├── InType.cs │ │ ├── Info.cs │ │ ├── InfoContact.cs │ │ ├── InfoLicense.cs │ │ ├── ParameterBase.cs │ │ ├── ParameterItems.cs │ │ ├── ParameterPrimitive.cs │ │ ├── ParameterSchema.cs │ │ ├── ParameterType.cs │ │ ├── Path.cs │ │ ├── PathAction.cs │ │ ├── Property.cs │ │ ├── Response.cs │ │ ├── Schema.cs │ │ ├── SecurityAuthorization.cs │ │ ├── SecurityDefinitions.cs │ │ ├── Service.cs │ │ └── TypeFormat.cs │ ├── Properties/ │ │ └── AssemblyInfo.cs │ ├── Support/ │ │ ├── DefinitionsBuilder.cs │ │ ├── EnumerableExtensions.cs │ │ ├── Helpers.cs │ │ ├── ListExtensions.cs │ │ ├── Mapper.cs │ │ ├── MethodInfoExtensions.cs │ │ ├── Serializer.cs │ │ ├── ServiceBuilder.cs │ │ ├── StaticContent.cs │ │ ├── TypeBuilder.cs │ │ ├── TypeExtensions.cs │ │ ├── TypeFieldsProcessor.cs │ │ └── TypePropertiesProcessor.cs │ ├── SwaggerWcf.csproj │ ├── SwaggerWcf.csproj.DotSettings │ ├── SwaggerWcf.nuspec │ ├── SwaggerWcfEndpoint.cs │ ├── SwaggerWcfEndpointGeneric.cs │ └── packages.config ├── SwaggerWcf.Test.Service/ │ ├── AuthorService.cs │ ├── BaseService.cs │ ├── Data/ │ │ ├── Author.cs │ │ ├── Book.cs │ │ ├── Language.cs │ │ └── Store.cs │ ├── Global.asax │ ├── Global.asax.cs │ ├── IAuthorService.cs │ ├── IBaseCRUDService.cs │ ├── IBaseService.cs │ ├── IStore.cs │ ├── Properties/ │ │ └── AssemblyInfo.cs │ ├── Store.svc │ ├── Store.svc.cs │ ├── SwaggerWcf.Test.Service.csproj │ ├── SwaggerWcf.Test.Service.csproj.DotSettings │ ├── Web.Debug.config │ ├── Web.Release.config │ └── Web.config ├── SwaggerWcf.sln ├── SwaggerWcf.sln.DotSettings └── packages/ ├── .gitignore └── repositories.config ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. # User-specific files .vs *.suo *.user *.sln.docstates # build packages *.nupkg # Build results [Dd]ebug/ [Rr]elease/ x64/ build/ [Bb]in/ [Oo]bj/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* *_i.c *_p.c *.ilk *.meta *.obj *.pch *.pdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *.log *.vspscc *.vssscc .builds *.pidb *.log *.scc # Visual C++ cache files ipch/ *.aps *.ncb *.opensdf *.sdf *.cachefile # Visual Studio profiler *.psess *.vsp *.vspx # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # NCrunch *.ncrunch* .*crunch*.local.xml # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.Publish.xml *.pubxml # NuGet Packages Directory ## TODO: If you have NuGet Package Restore enabled, uncomment the next line #packages/ # Windows Azure Build Output csx *.build.csdef # Windows Store app package directory AppPackages/ # Others sql/ *.Cache ClientBin/ [Ss]tyle[Cc]op.* ~$* *~ *.dbmdl *.[Pp]ublish.xml *.pfx *.publishsettings # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file to a newer # Visual Studio version. Backup files are not needed, because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm # SQL Server files App_Data/*.mdf App_Data/*.ldf # ========================= # Windows detritus # ========================= # Windows image file caches Thumbs.db ehthumbs.db # Folder config file Desktop.ini # Recycle Bin used on file shares $RECYCLE.BIN/ # Mac crap .DS_Store # custom entries /src/SampleService/obj ================================================ FILE: .gitmodules ================================================ [submodule "src/SampleService/swagger-ui"] path = src/SampleService/swagger-ui url = https://github.com/wordnik/swagger-ui.git ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================

SwaggerWcf  nuget status

Generates [Swagger](http://swagger.io/) (2.0) for WCF services and also provides [swagger-ui](https://github.com/swagger-api/swagger-ui). With an API described in Swagger you can use multiple Swagger tools like client generators, see [swagger-codegen](https://github.com/swagger-api/swagger-codegen) for more details. This project has started as a fork from [superstator/Swaggeratr](https://github.com/superstator/Swaggeratr) to implement version 2.0 of Swagger. ## Getting Started ### Step 1: Install SwaggerWcf package ``` Install-Package SwaggerWcf ``` ### Step 2: Configure WCF #### ASP.NET Add the route in the `Application_Start` method inside `Global.asax` ```csharp protected void Application_Start(object sender, EventArgs e) { // [.......] RouteTable.Routes.Add(new ServiceRoute("api-docs", new WebServiceHostFactory(), typeof(SwaggerWcfEndpoint))); } ``` Note: You might need to add a reference to `System.ServiceModel.Activation` Edit `Web.config` and add the following (if it doesn't exist yet) inside the `system.serviceModel` block ```xml ``` Edit again `Web.config` and add the following (if it doesn't exist yet) inside the `system.webServer` block ```xml ``` #### Self Hosted Add an endpoint to your App.config file. ```xml ``` Create a WebServiceHost ```csharp var swaggerHost = new WebServiceHost(typeof(SwaggerWcfEndpoint)); swaggerHost.Open(); ``` ### Step 3: Optionaly configure WCF response auto types Add the following to your config file. This will allow the WCF service to accept requests and send replies based on the `Content-Type` headers. ```xml ``` ### Step 4: Configure WCF services general information #### Configure via config file Add the following to your config file and change the values accordingly ```xml
``` Notes: * make sure the `configSections` block is the first child of `configuration` * `tags` will be described further down #### Configure via code Configure the base properties via code. New: You can add security settings to your api (see also the new Security-Methodattribute) ```csharp var info = new Info { Description = "Sample Service to test SwaggerWCF", Version = "0.0.1" // etc }; var security = new SecurityDefinitions { { "api-gateway", new SecurityAuthorization { Type = "oauth2", Name = "api-gateway", Description = "Forces authentication with credentials via an api gateway", Flow = "password", Scopes = new Dictionary { { "author", "use author scope"}, { "admin", "use admin scope"}, }, AuthorizationUrl = "http://yourapi.net/oauth/token" } } }; SwaggerWcfEndpoint.Configure(info, security); ``` ### Step 5: Decorate WCF services interfaces For each method, configure the `WebInvoke` or `WebGet` attribute, and add a `SwaggerWcfPath` attribute. ```csharp [ServiceContract] public interface IStore { [SwaggerWcfPath("Create book", "Create a book on the store")] [WebInvoke(UriTemplate = "/books", BodyStyle = WebMessageBodyStyle.Bare, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] [OperationContract] Book CreateBook(Book value); // [.......] } ``` ### Step 6: Decorate WCF services class Add the `SwaggerWcf` and `AspNetCompatibilityRequirements` attributes to the class providing the base path for the service (the same as used in step 2). Optinally, for each method, add the `SwaggerWcfTag` to categorize the method and the `SwaggerWcfResponse` for each possible response from the service. ```csharp [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [SwaggerWcf("/v1/rest")] public class BookStore : IStore { [SwaggerWcfTag("Books")] [SwaggerWcfResponse(HttpStatusCode.Created, "Book created, value in the response body with id updated")] [SwaggerWcfResponse(HttpStatusCode.BadRequest, "Bad request", true)] [SwaggerWcfResponse(HttpStatusCode.InternalServerError, "Internal error (can be forced using ERROR_500 as book title)", true)] public Book CreateBook(Book value) { // [.......] } // [.......] } ``` ### Step 7: Decorate data types used in WCF services ```csharp [DataContract(Name = "book")] [Description("Book with title, first publish date, author and language")] [SwaggerWcfDefinition(ExternalDocsUrl = "http://en.wikipedia.org/wiki/Book", ExternalDocsDescription = "Description of a book")] public class Book { [DataMember(Name = "id")] [Description("Book ID")] public string Id { get; set; } // [.......] } ``` Note: make sure you add at least the `DataContract` and `DataMember` attributes in classes and properties ## Attributes | Attribute | Used in | Description | Options | | ------------------------ |------------------------------------------- | -------------------------------------- | --------------------------------------------------------------------------------------------------- | | `SwaggerWcf` | `Class`, `Interface` | Enable parsing WCF service | `ServicePath` | | `SwaggerWcfHidden` | `Class`, `Method`, `Property`, `Parameter` | Hide element from Swagger | | | `SwaggerWcfTag` | `Class`, `Method`, `Property`, `Parameter` | Add a tag to an element | `TagName`, `HideFromSpec` | | `SwaggerWcfHeader` | `Method` | Configure method HTTP headers | `Name`, `Required`, `Description`, `DefaultValue` | | `SwaggerWcfPath` | `Method` | Configure a method in Swagger | `Summary`, `Description`, `OperationId`, `ExternalDocsDescription`, `ExternalDocsUrl`, `Deprecated` | | `SwaggerWcfParameter` | `Parameter` | Configure method parameters | `Required`, `Description`, `ParameterType` | | `SwaggerWcfProperty` | `Property` | Configure property parameters | `Required`, `Description`, `Minimum`, `Maximum`, `Default`, ... | | `SwaggerWcfResponse` | `Method` | Configure method return value | `Code`, `Description`, `EmptyResponseOverride`, `Headers` | | `SwaggerWcfDefinition` | `Class` | Configure a data type | `ExternalDocsDescription`, `ExternalDocsUrl` | | `SwaggerWcfReturnType` | `Method` | Override method return type | `ReturnType` | | `SwaggerWcfContentTypes` | `Method` | Override consume/produce content-types | `ConsumeTypes`, `ProduceTypes` | | `SwaggerWcfSecurity` | `Method` | Add security background to this method | `SecurityDefinitionName`, `params Scopes` | ## Tags Tags are used to create categories in Swagger UI. In SwaggerWcf they can also be used to hide or show elements from the Swagger output using the configuration file. Using the configuration from step 4, any elements with the tag `LowPerformance` will be hidden from Swagger. When a `SwaggerWcfTag` is added to an element, it may be configured with `HideFromSpec`. This will prevent this tag to be displayed in the Swagger output. When combined with `SwaggerWcfHidden`, if the tag has the value `visible` as `true` in `web.config` file, the element will be visible ## Query Parameter To specify query parameters to a function you may use the following syntax ```csharp [WebGet(UriTemplate = "/books?filter={filter}", BodyStyle = WebMessageBodyStyle.Bare)] Book[] ReadBooks(string filter = null); ``` ## Optional Parameters To specify a paramter as optional for swagger-ui provide a default value for the parameter on the interface. ```csharp public string Foo(string bar = null); ``` ## Optional Properties To mark a property as optional or required, use the `IsRequired` parameter on the `DataMember` attribute. ## TODO * Add some options to configuration in `Web.config` * Tests ## How to Improve It Fork this project [abelsilva/swaggerwcf](https://github.com/abelsilva/swaggerwcf) and submit pull requests. ================================================ FILE: notes/samples/petstore-expanded.json ================================================ { "swagger": "2.0", "info": { "version": "1.0.0", "title": "Swagger Petstore", "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", "termsOfService": "http://swagger.io/terms/", "contact": { "name": "Swagger API Team", "email": "apiteam@swagger.io", "url": "http://swagger.io" }, "license": { "name": "MIT", "url": "http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT" } }, "host": "petstore.swagger.io", "basePath": "/api", "schemes": [ "http" ], "consumes": [ "application/json" ], "produces": [ "application/json" ], "paths": { "/pets": { "get": { "description": "Returns all pets from the system that the user has access to", "operationId": "findPets", "produces": [ "application/json", "application/xml", "text/xml", "text/html" ], "parameters": [ { "name": "tags", "in": "query", "description": "tags to filter by", "required": false, "type": "array", "items": { "type": "string" }, "collectionFormat": "csv" }, { "name": "limit", "in": "query", "description": "maximum number of results to return", "required": false, "type": "integer", "format": "int32" } ], "responses": { "200": { "description": "pet response", "schema": { "type": "array", "items": { "$ref": "#/definitions/Pet" } } }, "default": { "description": "unexpected error", "schema": { "$ref": "#/definitions/ErrorModel" } } } }, "post": { "description": "Creates a new pet in the store. Duplicates are allowed", "operationId": "addPet", "produces": [ "application/json" ], "parameters": [ { "name": "pet", "in": "body", "description": "Pet to add to the store", "required": true, "schema": { "$ref": "#/definitions/NewPet" } } ], "responses": { "200": { "description": "pet response", "schema": { "$ref": "#/definitions/Pet" } }, "default": { "description": "unexpected error", "schema": { "$ref": "#/definitions/ErrorModel" } } } } }, "/pets/{id}": { "get": { "description": "Returns a user based on a single ID, if the user does not have access to the pet", "operationId": "findPetById", "produces": [ "application/json", "application/xml", "text/xml", "text/html" ], "parameters": [ { "name": "id", "in": "path", "description": "ID of pet to fetch", "required": true, "type": "integer", "format": "int64" } ], "responses": { "200": { "description": "pet response", "schema": { "$ref": "#/definitions/Pet" } }, "default": { "description": "unexpected error", "schema": { "$ref": "#/definitions/ErrorModel" } } } }, "delete": { "description": "deletes a single pet based on the ID supplied", "operationId": "deletePet", "parameters": [ { "name": "id", "in": "path", "description": "ID of pet to delete", "required": true, "type": "integer", "format": "int64" } ], "responses": { "204": { "description": "pet deleted" }, "default": { "description": "unexpected error", "schema": { "$ref": "#/definitions/ErrorModel" } } } } } }, "definitions": { "Pet": { "required": [ "id", "name" ], "properties": { "id": { "type": "integer", "format": "int64" }, "name": { "type": "string" }, "tag": { "type": "string" } } }, "NewPet": { "allOf": [ { "$ref": "#/definitions/Pet" }, { "required": [ "name" ], "properties": { "id": { "type": "integer", "format": "int64" } } } ] }, "ErrorModel": { "required": [ "code", "message" ], "properties": { "code": { "type": "integer", "format": "int32" }, "message": { "type": "string" } } } } } ================================================ FILE: notes/samples/petstore-minimal.json ================================================ { "swagger": "2.0", "info": { "version": "1.0.0", "title": "Swagger Petstore", "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", "termsOfService": "http://swagger.io/terms/", "contact": { "name": "Swagger API Team" }, "license": { "name": "MIT" } }, "host": "petstore.swagger.io", "basePath": "/api", "schemes": [ "http" ], "consumes": [ "application/json" ], "produces": [ "application/json" ], "paths": { "/pets": { "get": { "description": "Returns all pets from the system that the user has access to", "produces": [ "application/json" ], "responses": { "200": { "description": "A list of pets.", "schema": { "type": "array", "items": { "$ref": "#/definitions/Pet" } } } } } } }, "definitions": { "Pet": { "required": [ "id", "name" ], "properties": { "id": { "type": "integer", "format": "int64" }, "name": { "type": "string" }, "tag": { "type": "string" } } } } } ================================================ FILE: notes/samples/petstore-simple.json ================================================ { "swagger": "2.0", "info": { "version": "1.0.0", "title": "Swagger Petstore", "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", "termsOfService": "http://swagger.io/terms/", "contact": { "name": "Swagger API Team" }, "license": { "name": "MIT" } }, "host": "petstore.swagger.io", "basePath": "/api", "schemes": [ "http" ], "consumes": [ "application/json" ], "produces": [ "application/json" ], "paths": { "/pets": { "get": { "description": "Returns all pets from the system that the user has access to", "operationId": "findPets", "produces": [ "application/json", "application/xml", "text/xml", "text/html" ], "parameters": [ { "name": "tags", "in": "query", "description": "tags to filter by", "required": false, "type": "array", "items": { "type": "string" }, "collectionFormat": "csv" }, { "name": "limit", "in": "query", "description": "maximum number of results to return", "required": false, "type": "integer", "format": "int32" } ], "responses": { "200": { "description": "pet response", "schema": { "type": "array", "items": { "$ref": "#/definitions/Pet" } } }, "default": { "description": "unexpected error", "schema": { "$ref": "#/definitions/ErrorModel" } } } }, "post": { "description": "Creates a new pet in the store. Duplicates are allowed", "operationId": "addPet", "produces": [ "application/json" ], "parameters": [ { "name": "pet", "in": "body", "description": "Pet to add to the store", "required": true, "schema": { "$ref": "#/definitions/PetInput" } } ], "responses": { "200": { "description": "pet response", "schema": { "$ref": "#/definitions/Pet" } }, "default": { "description": "unexpected error", "schema": { "$ref": "#/definitions/ErrorModel" } } } } }, "/pets/{id}": { "get": { "description": "Returns a user based on a single ID, if the user does not have access to the pet", "operationId": "findPetById", "produces": [ "application/json", "application/xml", "text/xml", "text/html" ], "parameters": [ { "name": "id", "in": "path", "description": "ID of pet to fetch", "required": true, "type": "integer", "format": "int64" } ], "responses": { "200": { "description": "pet response", "schema": { "$ref": "#/definitions/Pet" } }, "default": { "description": "unexpected error", "schema": { "$ref": "#/definitions/ErrorModel" } } } }, "delete": { "description": "deletes a single pet based on the ID supplied", "operationId": "deletePet", "parameters": [ { "name": "id", "in": "path", "description": "ID of pet to delete", "required": true, "type": "integer", "format": "int64" } ], "responses": { "204": { "description": "pet deleted" }, "default": { "description": "unexpected error", "schema": { "$ref": "#/definitions/ErrorModel" } } } } } }, "definitions": { "Pet": { "required": [ "id", "name" ], "properties": { "id": { "type": "integer", "format": "int64" }, "name": { "type": "string" }, "tag": { "type": "string" } } }, "PetInput": { "allOf": [ { "$ref": "#/definitions/Pet" }, { "required": [ "name" ], "properties": { "id": { "type": "integer", "format": "int64" } } } ] }, "ErrorModel": { "required": [ "code", "message" ], "properties": { "code": { "type": "integer", "format": "int32" }, "message": { "type": "string" } } } } } ================================================ FILE: notes/samples/petstore-with-external-docs.json ================================================ { "swagger": "2.0", "info": { "version": "1.0.0", "title": "Swagger Petstore", "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", "termsOfService": "http://swagger.io/terms/", "contact": { "name": "Swagger API Team", "email": "apiteam@swagger.io", "url": "http://swagger.io" }, "license": { "name": "MIT", "url": "http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT" } }, "externalDocs": { "description": "find more info here", "url": "https://swagger.io/about" }, "host": "petstore.swagger.io", "basePath": "/api", "schemes": [ "http" ], "consumes": [ "application/json" ], "produces": [ "application/json" ], "paths": { "/pets": { "get": { "description": "Returns all pets from the system that the user has access to", "operationId": "findPets", "externalDocs": { "description": "find more info here", "url": "https://swagger.io/about" }, "produces": [ "application/json", "application/xml", "text/xml", "text/html" ], "parameters": [ { "name": "tags", "in": "query", "description": "tags to filter by", "required": false, "type": "array", "items": { "type": "string" }, "collectionFormat": "csv" }, { "name": "limit", "in": "query", "description": "maximum number of results to return", "required": false, "type": "integer", "format": "int32" } ], "responses": { "200": { "description": "pet response", "schema": { "type": "array", "items": { "$ref": "#/definitions/Pet" } } }, "default": { "description": "unexpected error", "schema": { "$ref": "#/definitions/ErrorModel" } } } }, "post": { "description": "Creates a new pet in the store. Duplicates are allowed", "operationId": "addPet", "produces": [ "application/json" ], "parameters": [ { "name": "pet", "in": "body", "description": "Pet to add to the store", "required": true, "schema": { "$ref": "#/definitions/NewPet" } } ], "responses": { "200": { "description": "pet response", "schema": { "$ref": "#/definitions/Pet" } }, "default": { "description": "unexpected error", "schema": { "$ref": "#/definitions/ErrorModel" } } } } }, "/pets/{id}": { "get": { "description": "Returns a user based on a single ID, if the user does not have access to the pet", "operationId": "findPetById", "produces": [ "application/json", "application/xml", "text/xml", "text/html" ], "parameters": [ { "name": "id", "in": "path", "description": "ID of pet to fetch", "required": true, "type": "integer", "format": "int64" } ], "responses": { "200": { "description": "pet response", "schema": { "$ref": "#/definitions/Pet" } }, "default": { "description": "unexpected error", "schema": { "$ref": "#/definitions/ErrorModel" } } } }, "delete": { "description": "deletes a single pet based on the ID supplied", "operationId": "deletePet", "parameters": [ { "name": "id", "in": "path", "description": "ID of pet to delete", "required": true, "type": "integer", "format": "int64" } ], "responses": { "204": { "description": "pet deleted" }, "default": { "description": "unexpected error", "schema": { "$ref": "#/definitions/ErrorModel" } } } } } }, "definitions": { "Pet": { "required": [ "id", "name" ], "externalDocs": { "description": "find more info here", "url": "https://swagger.io/about" }, "properties": { "id": { "type": "integer", "format": "int64" }, "name": { "type": "string" }, "tag": { "type": "string" } } }, "NewPet": { "allOf": [ { "$ref": "#/definitions/Pet" }, { "required": [ "name" ], "properties": { "id": { "type": "integer", "format": "int64" } } } ] }, "ErrorModel": { "required": [ "code", "message" ], "properties": { "code": { "type": "integer", "format": "int32" }, "message": { "type": "string" } } } } } ================================================ FILE: notes/samples/petstore.json ================================================ { "swagger": "2.0", "info": { "version": "1.0.0", "title": "Swagger Petstore", "contact": { "name": "Swagger API Team", "url": "http://swagger.io" }, "license": { "name": "Creative Commons 4.0 International", "url": "http://creativecommons.org/licenses/by/4.0/" } }, "host": "petstore.swagger.io", "basePath": "/api", "schemes": [ "http" ], "paths": { "/pets": { "get": { "tags": [ "Pet Operations" ], "summary": "finds pets in the system", "responses": { "200": { "description": "pet response", "schema": { "type": "array", "items": { "$ref": "#/definitions/Pet" } }, "headers": { "x-expires": { "type": "string" } } }, "default": { "description": "unexpected error", "schema": { "$ref": "#/definitions/Error" } } } } } }, "definitions": { "Pet": { "required": [ "id", "name" ], "properties": { "id": { "type": "integer", "format": "int64" }, "name": { "type": "string" }, "tag": { "type": "string" } } }, "Error": { "required": [ "code", "message" ], "properties": { "code": { "type": "integer", "format": "int32" }, "message": { "type": "string" } } } } } ================================================ FILE: notes/schema.json ================================================ { "title": "A JSON Schema for Swagger 2.0 API.", "id": "http://swagger.io/v2/schema.json#", "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "required": [ "swagger", "info", "paths" ], "additionalProperties": false, "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } }, "properties": { "swagger": { "type": "string", "enum": [ "2.0" ], "description": "The Swagger version of this document." }, "info": { "$ref": "#/definitions/info" }, "host": { "type": "string", "format": "uri", "pattern": "^[^{}/ :\\\\]+(?::\\d+)?$", "description": "The fully qualified URI to the host of the API." }, "basePath": { "type": "string", "pattern": "^/", "description": "The base path to the API. Example: '/api'." }, "schemes": { "$ref": "#/definitions/schemesList" }, "consumes": { "description": "A list of MIME types accepted by the API.", "$ref": "#/definitions/mediaTypeList" }, "produces": { "description": "A list of MIME types the API can produce.", "$ref": "#/definitions/mediaTypeList" }, "paths": { "$ref": "#/definitions/paths" }, "definitions": { "$ref": "#/definitions/definitions" }, "parameters": { "$ref": "#/definitions/parameterDefinitions" }, "responses": { "$ref": "#/definitions/responseDefinitions" }, "security": { "$ref": "#/definitions/security" }, "securityDefinitions": { "$ref": "#/definitions/securityDefinitions" }, "tags": { "type": "array", "items": { "$ref": "#/definitions/tag" }, "uniqueItems": true }, "externalDocs": { "$ref": "#/definitions/externalDocs" } }, "definitions": { "info": { "type": "object", "description": "General information about the API.", "required": [ "version", "title" ], "additionalProperties": false, "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } }, "properties": { "title": { "type": "string", "description": "A unique and precise title of the API." }, "version": { "type": "string", "description": "A semantic version number of the API." }, "description": { "type": "string", "description": "A longer description of the API. Should be different from the title. Github-flavored markdown is allowed." }, "termsOfService": { "type": "string", "description": "The terms of service for the API." }, "contact": { "$ref": "#/definitions/contact" }, "license": { "$ref": "#/definitions/license" } } }, "contact": { "type": "object", "description": "Contact information for the owners of the API.", "additionalProperties": false, "properties": { "name": { "type": "string", "description": "The identifying name of the contact person/organization." }, "url": { "type": "string", "description": "The URL pointing to the contact information.", "format": "uri" }, "email": { "type": "string", "description": "The email address of the contact person/organization.", "format": "email" } } }, "license": { "type": "object", "required": [ "name" ], "additionalProperties": false, "properties": { "name": { "type": "string", "description": "The name of the license type. It's encouraged to use an OSI compatible license." }, "url": { "type": "string", "description": "The URL pointing to the license.", "format": "uri" } } }, "paths": { "type": "object", "description": "Relative paths to the individual endpoints. They must be relative to the 'basePath'.", "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" }, "^/": { "$ref": "#/definitions/pathItem" } }, "additionalProperties": false }, "definitions": { "type": "object", "additionalProperties": { "$ref": "#/definitions/schema" }, "description": "One or more JSON objects describing the schemas being consumed and produced by the API." }, "parameterDefinitions": { "type": "object", "additionalProperties": { "$ref": "#/definitions/parameter" }, "description": "One or more JSON representations for parameters" }, "responseDefinitions": { "type": "object", "additionalProperties": { "$ref": "#/definitions/response" }, "description": "One or more JSON representations for parameters" }, "externalDocs": { "type": "object", "additionalProperties": false, "description": "information about external documentation", "required": [ "url" ], "properties": { "description": { "type": "string" }, "url": { "type": "string", "format": "uri" } } }, "examples": { "type": "object", "patternProperties": { "^[a-z0-9-]+/[a-z0-9\\-+]+$": {} }, "additionalProperties": false }, "mimeType": { "type": "string", "description": "The MIME type of the HTTP message." }, "operation": { "type": "object", "required": [ "responses" ], "additionalProperties": false, "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } }, "properties": { "tags": { "type": "array", "items": { "type": "string" }, "uniqueItems": true }, "summary": { "type": "string", "description": "A brief summary of the operation." }, "description": { "type": "string", "description": "A longer description of the operation, github-flavored markdown is allowed." }, "externalDocs": { "$ref": "#/definitions/externalDocs" }, "operationId": { "type": "string", "description": "A friendly name of the operation" }, "produces": { "description": "A list of MIME types the API can produce.", "$ref": "#/definitions/mediaTypeList" }, "consumes": { "description": "A list of MIME types the API can consume.", "$ref": "#/definitions/mediaTypeList" }, "parameters": { "$ref": "#/definitions/parametersList" }, "responses": { "$ref": "#/definitions/responses" }, "schemes": { "$ref": "#/definitions/schemesList" }, "deprecated": { "type": "boolean", "default": false }, "security": { "$ref": "#/definitions/security" } } }, "pathItem": { "type": "object", "additionalProperties": false, "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } }, "properties": { "$ref": { "type": "string" }, "get": { "$ref": "#/definitions/operation" }, "put": { "$ref": "#/definitions/operation" }, "post": { "$ref": "#/definitions/operation" }, "delete": { "$ref": "#/definitions/operation" }, "options": { "$ref": "#/definitions/operation" }, "head": { "$ref": "#/definitions/operation" }, "patch": { "$ref": "#/definitions/operation" }, "parameters": { "$ref": "#/definitions/parametersList" } } }, "responses": { "type": "object", "description": "Response objects names can either be any valid HTTP status code or 'default'.", "minProperties": 1, "additionalProperties": false, "patternProperties": { "^([0-9]{3})$|^(default)$": { "$ref": "#/definitions/responseValue" }, "^x-": { "$ref": "#/definitions/vendorExtension" } }, "not": { "type": "object", "additionalProperties": false, "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } } } }, "responseValue": { "oneOf": [ { "$ref": "#/definitions/response" }, { "$ref": "#/definitions/jsonReference" } ] }, "response": { "type": "object", "required": [ "description" ], "properties": { "description": { "type": "string" }, "schema": { "$ref": "#/definitions/schema" }, "headers": { "$ref": "#/definitions/headers" }, "examples": { "$ref": "#/definitions/examples" } }, "additionalProperties": false }, "headers": { "type": "object", "additionalProperties": { "$ref": "#/definitions/header" } }, "header": { "type": "object", "additionalProperties": false, "required": [ "type" ], "properties": { "type": { "type": "string", "enum": [ "string", "number", "integer", "boolean", "array" ] }, "format": { "type": "string" }, "items": { "$ref": "#/definitions/primitivesItems" }, "collectionFormat": { "$ref": "#/definitions/collectionFormat" }, "default": { "$ref": "#/definitions/default" }, "maximum": { "$ref": "#/definitions/maximum" }, "exclusiveMaximum": { "$ref": "#/definitions/exclusiveMaximum" }, "minimum": { "$ref": "#/definitions/minimum" }, "exclusiveMinimum": { "$ref": "#/definitions/exclusiveMinimum" }, "maxLength": { "$ref": "#/definitions/maxLength" }, "minLength": { "$ref": "#/definitions/minLength" }, "pattern": { "$ref": "#/definitions/pattern" }, "maxItems": { "$ref": "#/definitions/maxItems" }, "minItems": { "$ref": "#/definitions/minItems" }, "uniqueItems": { "$ref": "#/definitions/uniqueItems" }, "enum": { "$ref": "#/definitions/enum" }, "multipleOf": { "$ref": "#/definitions/multipleOf" }, "description": { "type": "string" } } }, "vendorExtension": { "description": "Any property starting with x- is valid.", "additionalProperties": true, "additionalItems": true }, "bodyParameter": { "type": "object", "required": [ "name", "in", "schema" ], "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } }, "properties": { "description": { "type": "string", "description": "A brief description of the parameter. This could contain examples of use. Github-flavored markdown is allowed." }, "name": { "type": "string", "description": "The name of the parameter." }, "in": { "type": "string", "description": "Determines the location of the parameter.", "enum": [ "body" ] }, "required": { "type": "boolean", "description": "Determines whether or not this parameter is required or optional.", "default": false }, "schema": { "$ref": "#/definitions/schema" } }, "additionalProperties": false }, "headerParameterSubSchema": { "additionalProperties": false, "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } }, "properties": { "required": { "type": "boolean", "description": "Determines whether or not this parameter is required or optional.", "default": false }, "in": { "type": "string", "description": "Determines the location of the parameter.", "enum": [ "header" ] }, "description": { "type": "string", "description": "A brief description of the parameter. This could contain examples of use. Github-flavored markdown is allowed." }, "name": { "type": "string", "description": "The name of the parameter." }, "type": { "type": "string", "enum": [ "string", "number", "boolean", "integer", "array" ] }, "format": { "type": "string" }, "items": { "$ref": "#/definitions/primitivesItems" }, "collectionFormat": { "$ref": "#/definitions/collectionFormat" }, "default": { "$ref": "#/definitions/default" }, "maximum": { "$ref": "#/definitions/maximum" }, "exclusiveMaximum": { "$ref": "#/definitions/exclusiveMaximum" }, "minimum": { "$ref": "#/definitions/minimum" }, "exclusiveMinimum": { "$ref": "#/definitions/exclusiveMinimum" }, "maxLength": { "$ref": "#/definitions/maxLength" }, "minLength": { "$ref": "#/definitions/minLength" }, "pattern": { "$ref": "#/definitions/pattern" }, "maxItems": { "$ref": "#/definitions/maxItems" }, "minItems": { "$ref": "#/definitions/minItems" }, "uniqueItems": { "$ref": "#/definitions/uniqueItems" }, "enum": { "$ref": "#/definitions/enum" }, "multipleOf": { "$ref": "#/definitions/multipleOf" } } }, "queryParameterSubSchema": { "additionalProperties": false, "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } }, "properties": { "required": { "type": "boolean", "description": "Determines whether or not this parameter is required or optional.", "default": false }, "in": { "type": "string", "description": "Determines the location of the parameter.", "enum": [ "query" ] }, "description": { "type": "string", "description": "A brief description of the parameter. This could contain examples of use. Github-flavored markdown is allowed." }, "name": { "type": "string", "description": "The name of the parameter." }, "allowEmptyValue": { "type": "boolean", "default": false, "description": "allows sending a parameter by name only or with an empty value." }, "type": { "type": "string", "enum": [ "string", "number", "boolean", "integer", "array" ] }, "format": { "type": "string" }, "items": { "$ref": "#/definitions/primitivesItems" }, "collectionFormat": { "$ref": "#/definitions/collectionFormatWithMulti" }, "default": { "$ref": "#/definitions/default" }, "maximum": { "$ref": "#/definitions/maximum" }, "exclusiveMaximum": { "$ref": "#/definitions/exclusiveMaximum" }, "minimum": { "$ref": "#/definitions/minimum" }, "exclusiveMinimum": { "$ref": "#/definitions/exclusiveMinimum" }, "maxLength": { "$ref": "#/definitions/maxLength" }, "minLength": { "$ref": "#/definitions/minLength" }, "pattern": { "$ref": "#/definitions/pattern" }, "maxItems": { "$ref": "#/definitions/maxItems" }, "minItems": { "$ref": "#/definitions/minItems" }, "uniqueItems": { "$ref": "#/definitions/uniqueItems" }, "enum": { "$ref": "#/definitions/enum" }, "multipleOf": { "$ref": "#/definitions/multipleOf" } } }, "formDataParameterSubSchema": { "additionalProperties": false, "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } }, "properties": { "required": { "type": "boolean", "description": "Determines whether or not this parameter is required or optional.", "default": false }, "in": { "type": "string", "description": "Determines the location of the parameter.", "enum": [ "formData" ] }, "description": { "type": "string", "description": "A brief description of the parameter. This could contain examples of use. Github-flavored markdown is allowed." }, "name": { "type": "string", "description": "The name of the parameter." }, "allowEmptyValue": { "type": "boolean", "default": false, "description": "allows sending a parameter by name only or with an empty value." }, "type": { "type": "string", "enum": [ "string", "number", "boolean", "integer", "array", "file" ] }, "format": { "type": "string" }, "items": { "$ref": "#/definitions/primitivesItems" }, "collectionFormat": { "$ref": "#/definitions/collectionFormatWithMulti" }, "default": { "$ref": "#/definitions/default" }, "maximum": { "$ref": "#/definitions/maximum" }, "exclusiveMaximum": { "$ref": "#/definitions/exclusiveMaximum" }, "minimum": { "$ref": "#/definitions/minimum" }, "exclusiveMinimum": { "$ref": "#/definitions/exclusiveMinimum" }, "maxLength": { "$ref": "#/definitions/maxLength" }, "minLength": { "$ref": "#/definitions/minLength" }, "pattern": { "$ref": "#/definitions/pattern" }, "maxItems": { "$ref": "#/definitions/maxItems" }, "minItems": { "$ref": "#/definitions/minItems" }, "uniqueItems": { "$ref": "#/definitions/uniqueItems" }, "enum": { "$ref": "#/definitions/enum" }, "multipleOf": { "$ref": "#/definitions/multipleOf" } } }, "pathParameterSubSchema": { "additionalProperties": false, "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } }, "properties": { "required": { "type": "boolean", "enum": [ true ], "description": "Determines whether or not this parameter is required or optional." }, "in": { "type": "string", "description": "Determines the location of the parameter.", "enum": [ "path" ] }, "description": { "type": "string", "description": "A brief description of the parameter. This could contain examples of use. Github-flavored markdown is allowed." }, "name": { "type": "string", "description": "The name of the parameter." }, "type": { "type": "string", "enum": [ "string", "number", "boolean", "integer", "array" ] }, "format": { "type": "string" }, "items": { "$ref": "#/definitions/primitivesItems" }, "collectionFormat": { "$ref": "#/definitions/collectionFormat" }, "default": { "$ref": "#/definitions/default" }, "maximum": { "$ref": "#/definitions/maximum" }, "exclusiveMaximum": { "$ref": "#/definitions/exclusiveMaximum" }, "minimum": { "$ref": "#/definitions/minimum" }, "exclusiveMinimum": { "$ref": "#/definitions/exclusiveMinimum" }, "maxLength": { "$ref": "#/definitions/maxLength" }, "minLength": { "$ref": "#/definitions/minLength" }, "pattern": { "$ref": "#/definitions/pattern" }, "maxItems": { "$ref": "#/definitions/maxItems" }, "minItems": { "$ref": "#/definitions/minItems" }, "uniqueItems": { "$ref": "#/definitions/uniqueItems" }, "enum": { "$ref": "#/definitions/enum" }, "multipleOf": { "$ref": "#/definitions/multipleOf" } } }, "nonBodyParameter": { "type": "object", "required": [ "name", "in", "type" ], "oneOf": [ { "$ref": "#/definitions/headerParameterSubSchema" }, { "$ref": "#/definitions/formDataParameterSubSchema" }, { "$ref": "#/definitions/queryParameterSubSchema" }, { "$ref": "#/definitions/pathParameterSubSchema" } ] }, "parameter": { "oneOf": [ { "$ref": "#/definitions/bodyParameter" }, { "$ref": "#/definitions/nonBodyParameter" } ] }, "schema": { "type": "object", "description": "A deterministic version of a JSON Schema object.", "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } }, "properties": { "$ref": { "type": "string" }, "format": { "type": "string" }, "title": { "$ref": "http://json-schema.org/draft-04/schema#/properties/title" }, "description": { "$ref": "http://json-schema.org/draft-04/schema#/properties/description" }, "default": { "$ref": "http://json-schema.org/draft-04/schema#/properties/default" }, "multipleOf": { "$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf" }, "maximum": { "$ref": "http://json-schema.org/draft-04/schema#/properties/maximum" }, "exclusiveMaximum": { "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum" }, "minimum": { "$ref": "http://json-schema.org/draft-04/schema#/properties/minimum" }, "exclusiveMinimum": { "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum" }, "maxLength": { "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" }, "minLength": { "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" }, "pattern": { "$ref": "http://json-schema.org/draft-04/schema#/properties/pattern" }, "maxItems": { "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" }, "minItems": { "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" }, "uniqueItems": { "$ref": "http://json-schema.org/draft-04/schema#/properties/uniqueItems" }, "maxProperties": { "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" }, "minProperties": { "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" }, "required": { "$ref": "http://json-schema.org/draft-04/schema#/definitions/stringArray" }, "enum": { "$ref": "http://json-schema.org/draft-04/schema#/properties/enum" }, "additionalProperties": { "$ref": "http://json-schema.org/draft-04/schema#/properties/additionalProperties" }, "type": { "$ref": "http://json-schema.org/draft-04/schema#/properties/type" }, "items": { "anyOf": [ { "$ref": "#/definitions/schema" }, { "type": "array", "minItems": 1, "items": { "$ref": "#/definitions/schema" } } ], "default": {} }, "allOf": { "type": "array", "minItems": 1, "items": { "$ref": "#/definitions/schema" } }, "properties": { "type": "object", "additionalProperties": { "$ref": "#/definitions/schema" }, "default": {} }, "discriminator": { "type": "string" }, "readOnly": { "type": "boolean", "default": false }, "xml": { "$ref": "#/definitions/xml" }, "externalDocs": { "$ref": "#/definitions/externalDocs" }, "example": {} }, "additionalProperties": false }, "primitivesItems": { "type": "object", "additionalProperties": false, "properties": { "type": { "type": "string", "enum": [ "string", "number", "integer", "boolean", "array" ] }, "format": { "type": "string" }, "items": { "$ref": "#/definitions/primitivesItems" }, "collectionFormat": { "$ref": "#/definitions/collectionFormat" }, "default": { "$ref": "#/definitions/default" }, "maximum": { "$ref": "#/definitions/maximum" }, "exclusiveMaximum": { "$ref": "#/definitions/exclusiveMaximum" }, "minimum": { "$ref": "#/definitions/minimum" }, "exclusiveMinimum": { "$ref": "#/definitions/exclusiveMinimum" }, "maxLength": { "$ref": "#/definitions/maxLength" }, "minLength": { "$ref": "#/definitions/minLength" }, "pattern": { "$ref": "#/definitions/pattern" }, "maxItems": { "$ref": "#/definitions/maxItems" }, "minItems": { "$ref": "#/definitions/minItems" }, "uniqueItems": { "$ref": "#/definitions/uniqueItems" }, "enum": { "$ref": "#/definitions/enum" }, "multipleOf": { "$ref": "#/definitions/multipleOf" } } }, "security": { "type": "array", "items": { "$ref": "#/definitions/securityRequirement" }, "uniqueItems": true }, "securityRequirement": { "type": "object", "additionalProperties": { "type": "array", "items": { "type": "string" }, "uniqueItems": true } }, "xml": { "type": "object", "additionalProperties": false, "properties": { "name": { "type": "string" }, "namespace": { "type": "string" }, "prefix": { "type": "string" }, "attribute": { "type": "boolean", "default": false }, "wrapped": { "type": "boolean", "default": false } } }, "tag": { "type": "object", "additionalProperties": false, "required": [ "name" ], "properties": { "name": { "type": "string" }, "description": { "type": "string" }, "externalDocs": { "$ref": "#/definitions/externalDocs" } }, "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } } }, "securityDefinitions": { "type": "object", "additionalProperties": { "oneOf": [ { "$ref": "#/definitions/basicAuthenticationSecurity" }, { "$ref": "#/definitions/apiKeySecurity" }, { "$ref": "#/definitions/oauth2ImplicitSecurity" }, { "$ref": "#/definitions/oauth2PasswordSecurity" }, { "$ref": "#/definitions/oauth2ApplicationSecurity" }, { "$ref": "#/definitions/oauth2AccessCodeSecurity" } ] } }, "basicAuthenticationSecurity": { "type": "object", "additionalProperties": false, "required": [ "type" ], "properties": { "type": { "type": "string", "enum": [ "basic" ] }, "description": { "type": "string" } }, "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } } }, "apiKeySecurity": { "type": "object", "additionalProperties": false, "required": [ "type", "name", "in" ], "properties": { "type": { "type": "string", "enum": [ "apiKey" ] }, "name": { "type": "string" }, "in": { "type": "string", "enum": [ "header", "query" ] }, "description": { "type": "string" } }, "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } } }, "oauth2ImplicitSecurity": { "type": "object", "additionalProperties": false, "required": [ "type", "flow", "authorizationUrl" ], "properties": { "type": { "type": "string", "enum": [ "oauth2" ] }, "flow": { "type": "string", "enum": [ "implicit" ] }, "scopes": { "$ref": "#/definitions/oauth2Scopes" }, "authorizationUrl": { "type": "string", "format": "uri" }, "description": { "type": "string" } }, "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } } }, "oauth2PasswordSecurity": { "type": "object", "additionalProperties": false, "required": [ "type", "flow", "tokenUrl" ], "properties": { "type": { "type": "string", "enum": [ "oauth2" ] }, "flow": { "type": "string", "enum": [ "password" ] }, "scopes": { "$ref": "#/definitions/oauth2Scopes" }, "tokenUrl": { "type": "string", "format": "uri" }, "description": { "type": "string" } }, "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } } }, "oauth2ApplicationSecurity": { "type": "object", "additionalProperties": false, "required": [ "type", "flow", "tokenUrl" ], "properties": { "type": { "type": "string", "enum": [ "oauth2" ] }, "flow": { "type": "string", "enum": [ "application" ] }, "scopes": { "$ref": "#/definitions/oauth2Scopes" }, "tokenUrl": { "type": "string", "format": "uri" }, "description": { "type": "string" } }, "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } } }, "oauth2AccessCodeSecurity": { "type": "object", "additionalProperties": false, "required": [ "type", "flow", "authorizationUrl", "tokenUrl" ], "properties": { "type": { "type": "string", "enum": [ "oauth2" ] }, "flow": { "type": "string", "enum": [ "accessCode" ] }, "scopes": { "$ref": "#/definitions/oauth2Scopes" }, "authorizationUrl": { "type": "string", "format": "uri" }, "tokenUrl": { "type": "string", "format": "uri" }, "description": { "type": "string" } }, "patternProperties": { "^x-": { "$ref": "#/definitions/vendorExtension" } } }, "oauth2Scopes": { "type": "object", "additionalProperties": { "type": "string" } }, "mediaTypeList": { "type": "array", "items": { "$ref": "#/definitions/mimeType" }, "uniqueItems": true }, "parametersList": { "type": "array", "description": "The parameters needed to send a valid API call.", "additionalItems": false, "items": { "oneOf": [ { "$ref": "#/definitions/parameter" }, { "$ref": "#/definitions/jsonReference" } ] }, "uniqueItems": true }, "schemesList": { "type": "array", "description": "The transfer protocol of the API.", "items": { "type": "string", "enum": [ "http", "https", "ws", "wss" ] }, "uniqueItems": true }, "collectionFormat": { "type": "string", "enum": [ "csv", "ssv", "tsv", "pipes" ], "default": "csv" }, "collectionFormatWithMulti": { "type": "string", "enum": [ "csv", "ssv", "tsv", "pipes", "multi" ], "default": "csv" }, "title": { "$ref": "http://json-schema.org/draft-04/schema#/properties/title" }, "description": { "$ref": "http://json-schema.org/draft-04/schema#/properties/description" }, "default": { "$ref": "http://json-schema.org/draft-04/schema#/properties/default" }, "multipleOf": { "$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf" }, "maximum": { "$ref": "http://json-schema.org/draft-04/schema#/properties/maximum" }, "exclusiveMaximum": { "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum" }, "minimum": { "$ref": "http://json-schema.org/draft-04/schema#/properties/minimum" }, "exclusiveMinimum": { "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum" }, "maxLength": { "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" }, "minLength": { "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" }, "pattern": { "$ref": "http://json-schema.org/draft-04/schema#/properties/pattern" }, "maxItems": { "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" }, "minItems": { "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" }, "uniqueItems": { "$ref": "http://json-schema.org/draft-04/schema#/properties/uniqueItems" }, "enum": { "$ref": "http://json-schema.org/draft-04/schema#/properties/enum" }, "jsonReference": { "type": "object", "additionalProperties": false, "properties": { "$ref": { "type": "string" } } } } } ================================================ FILE: notes/spec-2.0.md ================================================ # Swagger RESTful API Documentation Specification #### Version 2.0 The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC 2119](http://www.ietf.org/rfc/rfc2119.txt). The Swagger specification is licensed under [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html). ## Introduction Swagger™ is a project used to describe and document RESTful APIs. The Swagger specification defines a set of files required to describe such an API. These files can then be used by the Swagger-UI project to display the API and Swagger-Codegen to generate clients in various languages. Additional utilities can also take advantage of the resulting files, such as testing tools. ## Revision History Version | Date | Notes --- | --- | --- 2.0 | 2014-09-08 | Release of Swagger 2.0 1.2 | 2014-03-14 | Initial release of the formal document. 1.1 | 2012-08-22 | Release of Swagger 1.1 1.0 | 2011-08-10 | First release of the Swagger Specification ## Definitions ##### Path Templating Path templating refers to the usage of curly braces ({}) to mark a section of a URL path as replaceable using path parameters. ##### Mime Types Mime type definitions are spread across several resources. The mime type definitions should be in compliance with [RFC 6838](http://tools.ietf.org/html/rfc6838). Some examples of possible mime type definitions: ``` text/plain; charset=utf-8 application/json application/vnd.github+json application/vnd.github.v3+json application/vnd.github.v3.raw+json application/vnd.github.v3.text+json application/vnd.github.v3.html+json application/vnd.github.v3.full+json application/vnd.github.v3.diff application/vnd.github.v3.patch ``` ##### HTTP Status Codes The HTTP Status Codes are used to indicate the status of the executed operation. The available status codes are described by [RFC 7231](http://tools.ietf.org/html/rfc7231#section-6) and in the [IANA Status Code Registry](http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml). ## Specification ### Format The files describing the RESTful API in accordance with the Swagger specification are represented as JSON objects and conform to the JSON standards. YAML, being a superset of JSON, can be used as well to represent a Swagger specification file. For example, if a field is said to have an array value, the JSON array representation will be used: ```js { "field" : [...] } ``` While the API is described using JSON it does not impose a JSON input/output to the API itself. All field names in the specification are **case sensitive**. The schema exposes two types of fields. Fixed fields, which have a declared name, and Patterned fields, which declare a regex pattern for the field name. Patterned fields can have multiple occurrences as long as each has a unique name. ### File Structure The Swagger representation of the API is made of a single file. However, parts of the definitions can be split into separate files, at the discretion of the user. This is applicable for `$ref` fields in the specification as follows from the [JSON Schema](http://json-schema.org) definitions. By convention, the Swagger specification file is named `swagger.json`. ### Data Types Primitive data types in the Swagger Specification are based on the types supported by the [JSON-Schema Draft 4](http://json-schema.org/latest/json-schema-core.html#anchor8). Models are described using the [Schema Object](#schemaObject) which is a subset of JSON Schema Draft 4. An additional primitive data type `"file"` is used by the [Parameter Object](#parameterObject) and the [Response Object](#responseObject) to set the parameter type or the response as being a file. Primitives have an optional modifier property `format`. Swagger uses several known formats to more finely define the data type being used. However, the `format` property is an open `string`-valued property, and can have any value to support documentation needs. Formats such as `"email"`, `"uuid"`, etc., can be used even though they are not defined by this specification. Types that are not accompanied by a `format` property follow their definition from the JSON Schema (except for `file` type which is defined above). The formats defined by the Swagger Specification are: Common Name | [`type`](#dataTypeType) | [`format`](#dataTypeFormat) | Comments ----------- | ------ | -------- | -------- integer | `integer` | `int32` | signed 32 bits long | `integer` | `int64` | signed 64 bits float | `number` | `float` | double | `number` | `double` | string | `string` | | byte | `string` | `byte` | boolean | `boolean` | | date | `string` | `date` | As defined by `full-date` - [RFC3339](http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14) dateTime | `string` | `date-time` | As defined by `date-time` - [RFC3339](http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14) password | `string` | `password` | Used to hint UIs the input needs to be obscured. ### Schema #### Swagger Object This is the root document object for the API specification. It combines what previously was the Resource Listing and API Declaration (version 1.2 and earlier) together into one document. ##### Fixed Fields Field Name | Type | Description ---|:---:|--- swagger | `string` | **Required.** Specifies the Swagger Specification version being used. It can be used by the Swagger UI and other clients to interpret the API listing. The value MUST be `"2.0"`. info | [Info Object](#infoObject) | **Required.** Provides metadata about the API. The metadata can be used by the clients if needed. host | `string` | The host (name or ip) serving the API. This MUST be the host only and does not include the scheme nor sub-paths. It MAY include a port. If the `host` is not included, the host serving the documentation is to be used (including the port). The `host` does not support [path templating](#pathTemplating). basePath | `string` | The base path on which the API is served, which is relative to the [`host`](#swaggerHost). If it is not included, the API is served directly under the `host`. The value MUST start with a leading slash (`/`). The `basePath` does not support [path templating](#pathTemplating). schemes | [`string`] | The transfer protocol of the API. Values MUST be from the list: `"http"`, `"https"`, `"ws"`, `"wss"`. If the `schemes` is not included, the default scheme to be used is the one used to access the specification. consumes | [`string`] | A list of MIME types the APIs can consume. This is global to all APIs but can be overridden on specific API calls. Value MUST be as described under [Mime Types](#mimeTypes). produces | [`string`] | A list of MIME types the APIs can produce. This is global to all APIs but can be overridden on specific API calls. Value MUST be as described under [Mime Types](#mimeTypes). paths | [Paths Object](#pathsObject) | **Required.** The available paths and operations for the API. definitions | [Definitions Object](#definitionsObject) | An object to hold data types produced and consumed by operations. parameters | [Parameters Definitions Object](#parametersDefinitionsObject) | An object to hold parameters that can be used across operations. This property *does not* define global parameters for all operations. responses | [Responses Definitions Object](#responsesDefinitionsObject) | An object to hold responses that can be used across operations. This property *does not* define global responses for all operations. securityDefinitions | [Security Definitions Object](#securityDefinitionsObject) | Security scheme definitions that can be used across the specification. security | [[Security Requirement Object](#securityRequirementObject)] | A declaration of which security schemes are applied for the API as a whole. The list of values describes alternative security schemes that can be used (that is, there is a logical OR between the security requirements). Individual operations can override this definition. tags | [[Tag Object](#tagObject)] | A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the [Operation Object](#operationObject) must be declared. The tags that are not declared may be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation. #### Info Object The object provides metadata about the API. The metadata can be used by the clients if needed, and can be presented in the Swagger-UI for convenience. ##### Fixed Fields Field Name | Type | Description ---|:---:|--- title | `string` | **Required.** The title of the application. description | `string` | A short description of the application. [GFM syntax](https://help.github.com/articles/github-flavored-markdown) can be used for rich text representation. termsOfService | `string` | The Terms of Service for the API. contact | [Contact Object](#contactObject) | The contact information for the exposed API. license | [License Object](#licenseObject) | The license information for the exposed API. version | `string` | **Required** Provides the version of the application API (not to be confused with the specification version). ##### Patterned Objects Field Pattern | Type | Description ---|:---:|--- ^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#vendorExtensions) for further details. ##### Info Object Example: ```js { "title": "Swagger Sample App", "description": "This is a sample server Petstore server.", "termsOfService": "http://swagger.io/terms/", "contact": { "name": "API Support", "url": "http://www.swagger.io/support", "email": "support@swagger.io" }, "license": { "name": "Apache 2.0", "url": "http://www.apache.org/licenses/LICENSE-2.0.html" }, "version": "1.0.1" } ``` ```yaml title: Swagger Sample App description: This is a sample server Petstore server. termsOfService: http://swagger.io/terms/ contact: name: API Support url: http://www.swagger.io/support email: support@swagger.io license: name: Apache 2.0 url: http://www.apache.org/licenses/LICENSE-2.0.html version: 1.0.1 ``` #### Contact Object Contact information for the exposed API. ##### Fixed Fields Field Name | Type | Description ---|:---:|--- name | `string` | The identifying name of the contact person/organization. url | `string` | The URL pointing to the contact information. MUST be in the format of a URL. email | `string` | The email address of the contact person/organization. MUST be in the format of an email address. ##### Contact Object Example: ```js { "name": "API Support", "url": "http://www.swagger.io/support", "email": "support@swagger.io" } ``` ```yaml name: API Support url: http://www.swagger.io/support email: support@swagger.io ``` #### License Object License information for the exposed API. ##### Fixed Fields Field Name | Type | Description ---|:---:|--- name | `string` | **Required.** The license name used for the API. url | `string` | A URL to the license used for the API. MUST be in the format of a URL. ##### License Object Example: ```js { "name": "Apache 2.0", "url": "http://www.apache.org/licenses/LICENSE-2.0.html" } ``` ```yaml name: Apache 2.0 url: http://www.apache.org/licenses/LICENSE-2.0.html ``` #### Paths Object Holds the relative paths to the individual endpoints. The path is appended to the [`basePath`](#swaggerBasePath) in order to construct the full URL. The Paths may be empty, due to [ACL constraints](#securityFiltering). ##### Patterned Fields Field Pattern | Type | Description ---|:---:|--- /{path} | [Path Item Object](#pathItemObject) | A relative path to an individual endpoint. The field name MUST begin with a slash. The path is appended to the [`basePath`](#swaggerBasePath) in order to construct the full URL. [Path templating](#pathTemplating) is allowed. ^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#vendorExtensions) for further details. ##### Paths Object Example ```js { "/pets": { "get": { "description": "Returns all pets from the system that the user has access to", "produces": [ "application/json" ], "responses": { "200": { "description": "A list of pets.", "schema": { "type": "array", "items": { "$ref": "#/definitions/pet" } } } } } } } ``` ```yaml /pets: get: description: Returns all pets from the system that the user has access to produces: - application/json responses: 200: description: A list of pets. schema: type: array items: $ref: '#/definitions/pet' ``` #### Path Item Object Describes the operations available on a single path. A Path Item may be empty, due to [ACL constraints](#securityFiltering). The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available. ##### Fixed Fields Field Name | Type | Description ---|:---:|--- $ref | `string` | Allows for an external definition of this path item. The referenced structure MUST be in the format of a [Path Item Object](#pathItemObject). If there are conflicts between the referenced definition and this Path Item's definition, the behavior is *undefined*. get | [Operation Object](#operationObject) | A definition of a GET operation on this path. put | [Operation Object](#operationObject) | A definition of a PUT operation on this path. post | [Operation Object](#operationObject) | A definition of a POST operation on this path. delete | [Operation Object](#operationObject) | A definition of a DELETE operation on this path. options | [Operation Object](#operationObject) | A definition of a OPTIONS operation on this path. head | [Operation Object](#operationObject) | A definition of a HEAD operation on this path. patch | [Operation Object](#operationObject) | A definition of a PATCH operation on this path. parameters | [[Parameter Object](#parameterObject) | [Reference Object](#referenceObject)] | A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#referenceObject) to link to parameters that are defined at the [Swagger Object's parameters](#swaggerParameters). There can be one "body" parameter at most. ##### Patterned Fields Field Pattern | Type | Description ---|:---:|--- ^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#vendorExtensions) for further details. ##### Path Item Object Example ```js { "get": { "description": "Returns pets based on ID", "summary": "Find pets by ID", "operationId": "getPetsById", "produces": [ "application/json", "text/html" ], "responses": { "200": { "description": "pet response", "schema": { "type": "array", "items": { "$ref": "#/definitions/Pet" } } }, "default": { "description": "error payload", "schema": { "$ref": "#/definitions/ErrorModel" } } } }, "parameters": [ { "name": "id", "in": "path", "description": "ID of pet to use", "required": true, "type": "array", "items": { "type": "string" }, "collectionFormat": "csv" } ] } ``` ```yaml get: description: Returns pets based on ID summary: Find pets by ID operationId: getPetsById produces: - application/json - text/html responses: 200: description: pet response schema: type: array items: $ref: '#/definitions/Pet' default: description: error payload schema: $ref: '#/definitions/ErrorModel' parameters: - name: id in: path description: ID of pet to use required: true type: array items: type: string collectionFormat: csv ``` #### Operation Object Describes a single API operation on a path. ##### Fixed Fields Field Name | Type | Description ---|:---:|--- tags | [`string`] | A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier. summary | `string` | A short summary of what the operation does. For maximum readability in the swagger-ui, this field SHOULD be less than 120 characters. description | `string` | A verbose explanation of the operation behavior. [GFM syntax](https://help.github.com/articles/github-flavored-markdown) can be used for rich text representation. externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this operation. operationId | `string` | A friendly name for the operation. The id MUST be unique among all operations described in the API. Tools and libraries MAY use the operation id to uniquely identify an operation. consumes | [`string`] | A list of MIME types the operation can consume. This overrides the [`consumes`](#swaggerConsumes) definition at the Swagger Object. An empty value MAY be used to clear the global definition. Value MUST be as described under [Mime Types](#mimeTypes). produces | [`string`] | A list of MIME types the operation can produce. This overrides the [`produces`](#swaggerProduces) definition at the Swagger Object. An empty value MAY be used to clear the global definition. Value MUST be as described under [Mime Types](#mimeTypes). parameters | [[Parameter Object](#parameterObject) | [Reference Object](#referenceObject)] | A list of parameters that are applicable for this operation. If a parameter is already defined at the [Path Item](#pathItemParameters), the new definition will override it, but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#referenceObject) to link to parameters that are defined at the [Swagger Object's parameters](#swaggerParameters). There can be one "body" parameter at most. responses | [Responses Object](#responsesObject) | **Required.** The list of possible responses as they are returned from executing this operation. schemes | [`string`] | The transfer protocol for the operation. Values MUST be from the list: `"http"`, `"https"`, `"ws"`, `"wss"`. The value overrides the Swagger Object [`schemes`](#swaggerSchemes) definition. deprecated | `boolean` | Declares this operation to be deprecated. Usage of the declared operation should be refrained. Default value is `false`. security | [[Security Requirement Object](#securityRequirementObject)] | A declaration of which security schemes are applied for this operation. The list of values describes alternative security schemes that can be used (that is, there is a logical OR between the security requirements). This definition overrides any declared top-level [`security`](#swaggerSecurity). To remove a top-level security declaration, an empty array can be used. ##### Patterned Objects Field Pattern | Type | Description ---|:---:|--- ^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#vendorExtensions) for further details. ##### Operation Object Example ```js { "tags": [ "pet" ], "summary": "Updates a pet in the store with form data", "description": "", "operationId": "updatePetWithForm", "consumes": [ "application/x-www-form-urlencoded" ], "produces": [ "application/json", "application/xml" ], "parameters": [ { "name": "petId", "in": "path", "description": "ID of pet that needs to be updated", "required": true, "type": "string" }, { "name": "name", "in": "formData", "description": "Updated name of the pet", "required": false, "type": "string" }, { "name": "status", "in": "formData", "description": "Updated status of the pet", "required": false, "type": "string" } ], "responses": { "200": { "description": "Pet updated." }, "405": { "description": "Invalid input" } }, "security": [ { "petstore_auth": [ "write:pets", "read:pets" ] } ] } ``` ```yaml tags: - pet summary: Updates a pet in the store with form data description: "" operationId: updatePetWithForm consumes: - application/x-www-form-urlencoded produces: - application/json - application/xml parameters: - name: petId in: path description: ID of pet that needs to be updated required: true type: string - name: name in: formData description: Updated name of the pet required: false type: string - name: status in: formData description: Updated status of the pet required: false type: string responses: 200: description: Pet updated. 405: description: Invalid input security: - petstore_auth: - write:pets - read:pets ``` #### External Documentation Object Allows referencing an external resource for extended documentation. ##### Fixed Fields Field Name | Type | Description ---|:---:|--- description | `string` | A short description of the target documentation. [GFM syntax](https://help.github.com/articles/github-flavored-markdown) can be used for rich text representation. url | `string` | **Required.** The URL for the target documentation. Value MUST be in the format of a URL. ##### External Documentation Object Example ```js { "description": "Find more info here", "url": "https://swagger.io" } ``` ```yaml description: Find more info here url: https://swagger.io ``` #### Parameter Object Describes a single operation parameter. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). There are five possible parameter types. * Path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, the path parameter is `itemId`. * Query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. * Header - Custom headers that are expected as part of the request. * Body - The payload that's appended to the HTTP request. Since there can only be one payload, there can only be *one* body parameter. The name of the body parameter has no effect on the parameter itself and is used for documentation purposes only. Since Form parameters are also in the payload, body and form parameters cannot exist together for the same operation. * Form - Used to describe the payload of an HTTP request when either `application/x-www-form-urlencoded` or `multipart/form-data` are used as the content type of the request (in Swagger's definition, the [`consumes`](#operationConsumes) property of an operation). This is the only parameter type that can be used to send files, thus supporting the `file` type. Since form parameters are sent in the payload, they cannot be declared together with a body parameter for the same operation. Form parameters have a different format based on the content-type used (for further details, consult http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4): * `application/x-www-form-urlencoded` - Similar to the format of Query parameters but as a payload. For example, `foo=1&bar=swagger` - both `foo` and `bar` are form parameters. This is normally used for simple parameters that are being transferred. * `multipart/form-data` - each parameter takes a section in the payload with an internal header. For example, for the header `Content-Disposition: form-data; name="submit-name"` the name of the parameter is `submit-name`. This type of form parameters is more commonly used for file transfers. ##### Fixed Fields Field Name | Type | Description ---|:---:|--- name | `string` | **Required.** The name of the parameter. Parameter names are *case sensitive*.
  • If [`in`](#parameterIn) is `"path"`, the `name` field MUST correspond to the associated path segment from the [path](#pathsPath) field in the [Paths Object](#pathsObject). See [Path Templating](#pathTemplating) for further information.
  • For all other cases, the `name` corresponds to the parameter name used based on the [`in`](#parameterIn) property.
in | `string` | **Required.** The location of the parameter. Possible values are "query", "header", "path", "formData" or "body". description | `string` | A brief description of the parameter. This could contain examples of use. [GFM syntax](https://help.github.com/articles/github-flavored-markdown) can be used for rich text representation. required | `boolean` | Determines whether this parameter is mandatory. If the parameter is [`in`](#parameterIn) "path", this property is **required** and its value MUST be `true`. Otherwise, the property MAY be included and its default value is `false`. If [`in`](#parameterIn) is `"body"`: Field Name | Type | Description ---|:---:|--- schema | [Schema Object](#schemaObject) | **Required.** The schema defining the type used for the body parameter. If [`in`](#parameterIn) is any value other than `"body"`: Field Name | Type | Description ---|:---:|--- type | `string` | **Required.** The type of the parameter. Since the parameter is not located at the request body, it is limited to simple types (that is, not an object). The value MUST be one of `"string"`, `"number"`, `"integer"`, `"boolean"`, `"array"` or `"file"`. If `type` is `"file"`, the [`consumes`](#operationConsumes) MUST be either `"multipart/form-data"` or `" application/x-www-form-urlencoded"` and the parameter MUST be [`in`](#parameterIn) `"formData"`. format | `string` | The extending format for the previously mentioned [`type`](#parameterType). See [Data Type Formats](#dataTypeFormat) for further details. allowEmptyValue | `boolean` | Sets the ability to pass empty-valued parameters. This is valid only for either `query` or `formData` parameters and allows you to send a parameter with a name only or an empty value. Default value is `false`. items | [Items Object](#itemsObject) | **Required if [`type`](#parameterType) is "array".** Describes the type of items in the array. collectionFormat | `string` | Determines the format of the array if type array is used. Possible values are:
  • `csv` - comma separated values `foo,bar`.
  • `ssv` - space separated values `foo bar`.
  • `tsv` - tab separated values `foo\tbar`.
  • `pipes` - pipe separated values foo|bar.
  • `multi` - corresponds to multiple parameter instances instead of multiple values for a single instance `foo=bar&foo=baz`. This is valid only for parameters [`in`](#parameterIn) "query" or "formData".
Default value is `csv`. default | * | Sets a default value to the parameter. See http://json-schema.org/latest/json-schema-validation.html#anchor101. Unlike JSON Schema this value MUST conform to the defined [`type`](#parameterType) for this parameter. maximum | `number` | See http://json-schema.org/latest/json-schema-validation.html#anchor17. exclusiveMaximum | `boolean` | See http://json-schema.org/latest/json-schema-validation.html#anchor17. minimum | `number` | See http://json-schema.org/latest/json-schema-validation.html#anchor21. exclusiveMinimum | `boolean` | See http://json-schema.org/latest/json-schema-validation.html#anchor21. maxLength | `integer` | See http://json-schema.org/latest/json-schema-validation.html#anchor26. minLength | `integer` | See http://json-schema.org/latest/json-schema-validation.html#anchor29. pattern | `string` | See http://json-schema.org/latest/json-schema-validation.html#anchor33. maxItems | `integer` | See http://json-schema.org/latest/json-schema-validation.html#anchor42. minItems | `integer` | See http://json-schema.org/latest/json-schema-validation.html#anchor45. uniqueItems | `boolean` | See http://json-schema.org/latest/json-schema-validation.html#anchor49. enum | [*] | See http://json-schema.org/latest/json-schema-validation.html#anchor76. multipleOf | `number` | See http://json-schema.org/latest/json-schema-validation.html#anchor14. ##### Patterned Fields Field Pattern | Type | Description ---|:---:|--- ^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#vendorExtensions) for further details. ##### Parameter Object Examples ###### Body Parameters A body parameter with a referenced schema definition (normally for a model definition): ```js { "name": "user", "in": "body", "description": "user to add to the system", "required": true, "schema": { "$ref": "#/definitions/User" } } ``` ```yaml name: user in: body description: user to add to the system required: true schema: $ref: '#/definitions/User' ``` A body parameter that is an array of string values: ```js { "name": "user", "in": "body", "description": "user to add to the system", "required": true, "schema": { "type": "array", "items": { "type": "string" } } } ``` ```yaml name: user in: body description: user to add to the system required: true schema: type: array items: type: string ``` ###### Other Parameters A header parameter with an array of 64 bit integer numbers: ```js { "name": "token", "in": "header", "description": "token to be passed as a header", "required": true, "type": "array", "items": { "type": "integer", "format": "int64" }, "collectionFormat": "csv" } ``` ```yaml name: token in: header description: token to be passed as a header required: true type: array items: type: integer format: int64 collectionFormat: csv ``` A path parameter of a string value: ```js { "name": "username", "in": "path", "description": "username to fetch", "required": true, "type": "string" } ``` ```yaml name: username in: path description: username to fetch required: true type: string ``` An optional query parameter of a string value, allowing multiple values by repeating the query parameter: ```js { "name": "id", "in": "query", "description": "ID of the object to fetch", "required": false, "type": "array", "items": { "type": "string" }, "collectionFormat": "multi" } ``` ```yaml name: id in: query description: ID of the object to fetch required: false type: array items: type: string collectionFormat: multi ``` A form data with file type for a file upload: ```js { "name": "avatar", "in": "formData", "description": "The avatar of the user", "required": true, "type": "file" } ``` ```yaml name: avatar in: formData description: The avatar of the user required: true type: file ``` #### Items Object An limited subset of JSON-Schema's items object. It is used by parameter definitions that are not located [`in`](#parameterIn) `"body"`. ##### Fixed Fields Field Name | Type | Description ---|:---:|--- type | `string` | **Required.** The internal type of the array. The value MUST be one of `"string"`, `"number"`, `"integer"`, `"boolean"`, or `"array"`. Files and models are not allowed. format | `string` | The extending format for the previously mentioned [`type`](#parameterType). See [Data Type Formats](#dataTypeFormat) for further details. items | [Items Object](#itemsObject) | **Required if [`type`](#itemsType) is "array".** Describes the type of items in the array. collectionFormat | `string` | Determines the format of the array if type array is used. Possible values are:
  • `csv` - comma separated values `foo,bar`.
  • `ssv` - space separated values `foo bar`.
  • `tsv` - tab separated values `foo\tbar`.
  • `pipes` - pipe separated values foo|bar.
Default value is `csv`. default | * | Sets a default value to the data type. See http://json-schema.org/latest/json-schema-validation.html#anchor101. Unlike JSON Schema this value MUST conform to the defined [`type`](#itemsType) for the data type. maximum | `number` | See http://json-schema.org/latest/json-schema-validation.html#anchor17. exclusiveMaximum | `boolean` | See http://json-schema.org/latest/json-schema-validation.html#anchor17. minimum | `number` | See http://json-schema.org/latest/json-schema-validation.html#anchor21. exclusiveMinimum | `boolean` | See http://json-schema.org/latest/json-schema-validation.html#anchor21. maxLength | `integer` | See http://json-schema.org/latest/json-schema-validation.html#anchor26. minLength | `integer` | See http://json-schema.org/latest/json-schema-validation.html#anchor29. pattern | `string` | See http://json-schema.org/latest/json-schema-validation.html#anchor33. maxItems | `integer` | See http://json-schema.org/latest/json-schema-validation.html#anchor42. minItems | `integer` | See http://json-schema.org/latest/json-schema-validation.html#anchor45. uniqueItems | `boolean` | See http://json-schema.org/latest/json-schema-validation.html#anchor49. enum | [*] | See http://json-schema.org/latest/json-schema-validation.html#anchor76. multipleOf | `number` | See http://json-schema.org/latest/json-schema-validation.html#anchor14. ##### Items Object Examples Items must be of type string and have the minimum length of 2 characters: ```js { "type": "string", "minLength": 2 } ``` ```yaml type: string minLength: 2 ``` An array of arrays, the internal array being of type integer, numbers must be between 0 and 63 (inclusive): ```js { "type": "array", "items": { "type": "integer", "minimum": 0, "maximum": 63 } } ``` ```yaml type: array items: type: integer minimum: 0 maximum: 63 ``` #### Responses Object A container for the expected responses of an operation. The container maps a HTTP response code to the expected response. It is not expected from the documentation to necessarily cover all possible HTTP response codes, since they may not be known in advance. However, it is expected from the documentation to cover a successful operation response and any known errors. The `default` can be used a default response object for all HTTP codes that are not covered individually by the specification. The `Responses Object` MUST contain at least one response code, and it SHOULD be the response for a successful operation call. ##### Fixed Fields Field Name | Type | Description ---|:---:|--- default | [Response Object](#responseObject) | [Reference Object](#referenceObject) | The documentation of responses other than the ones declared for specific HTTP response codes. It can be used to cover undeclared responses. [Reference Object](#referenceObject) can be used to link to a response that is defined at the [Swagger Object's responses](#swaggerResponses) section. ##### Patterned Fields Field Pattern | Type | Description ---|:---:|--- {[HTTP Status Code](#httpCodes)} | [Response Object](#responseObject) | [Reference Object](#referenceObject) | Any [HTTP status code](#httpCodes) can be used as the property name (one property per HTTP status code). Describes the expected response for that HTTP status code. [Reference Object](#referenceObject) can be used to link to a response that is defined at the [Swagger Object's responses](#swaggerResponses) section. ^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#vendorExtensions) for further details. ##### Responses Object Example A 200 response for successful operation and a default response for others (implying an error): ```js { "200": { "description": "a pet to be returned", "schema": { "$ref": "#/definitions/Pet" } }, "default": { "description": "Unexpected error", "schema": { "$ref": "#/definitions/ErrorModel" } } } ``` ```yaml 200: description: a pet to be returned schema: $ref: '#/definitions/Pet' default: description: Unexpected error schema: $ref: '#/definitions/ErrorModel' ``` #### Response Object Describes a single response from an API Operation. ##### Fixed Fields Field Name | Type | Description ---|:---:|--- description | `string` | **Required.** A short description of the response. [GFM syntax](https://help.github.com/articles/github-flavored-markdown) can be used for rich text representation. schema | [Schema Object](#schemaObject) | A definition of the response structure. It can be a primitive, an array or an object. If this field does not exist, it means no content is returned as part of the response. As an extension to the [Schema Object](#schemaObject), its root `type` value may also be `"file"`. This SHOULD be accompanied by a relevant `produces` mime-type. headers | [Headers Object](#headersObject) | A list of headers that are sent with the response. examples | [Example Object](#exampleObject) | An example of the response message. ##### Response Object Examples Response of an array of a complex type: ```js { "description": "A complex object array response", "schema": { "type": "array", "items": { "$ref": "#/definitions/VeryComplexType" } } } ``` ```yaml description: A complex object array response schema: type: array items: $ref: '#/definitions/VeryComplexType' ``` Response with a string type: ```js { "description": "A simple string response", "schema": { "type": "string" } } ``` ```yaml description: A simple string response schema: type: string ``` Response with headers: ```js { "description": "A simple string response", "schema": { "type": "string" }, "headers": { "X-Rate-Limit-Limit": { "description": "The number of allowed requests in the current period", "type": "integer" }, "X-Rate-Limit-Remaining": { "description": "The number of remaining requests in the current period", "type": "integer" }, "X-Rate-Limit-Reset": { "description": "The number of seconds left in the current period", "type": "integer" } } } ``` ```yaml description: A simple string response schema: type: string headers: X-Rate-Limit-Limit: description: The number of allowed requests in the current period type: integer X-Rate-Limit-Remaining: description: The number of remaining requests in the current period type: integer X-Rate-Limit-Reset: description: The number of seconds left in the current period type: integer ``` Response with no return value: ```js { "description": "object created" } ``` ```yaml description: object created ``` #### Headers Object Lists the headers that can be sent as part of a response. ##### Patterned Fields Field Pattern | Type | Description ---|:---:|--- {name} | [Header Object](#headerObject) | The name of the property corresponds to the name of the header. The value describes the type of the header. ##### Headers Object Example Rate-limit headers: ```js { "X-Rate-Limit-Limit": { "description": "The number of allowed requests in the current period", "type": "integer" }, "X-Rate-Limit-Remaining": { "description": "The number of remaining requests in the current period", "type": "integer" }, "X-Rate-Limit-Reset": { "description": "The number of seconds left in the current period", "type": "integer" } } ``` ```yaml X-Rate-Limit-Limit: description: The number of allowed requests in the current period type: integer X-Rate-Limit-Remaining: description: The number of remaining requests in the current period type: integer X-Rate-Limit-Reset: description: The number of seconds left in the current period type: integer ``` #### Example Object Allows sharing examples for operation responses. ##### Patterned Fields Field Pattern | Type | Description ---|:---:|--- {[mime type](#mimeTypes)} | Any | The name of the property MUST be one of the Operation `produces` values (either implicit or inherited). The value SHOULD be an example of what such a response would look like. ##### Example Object Example Example response for application/json mimetype of a Pet data type: ```js { "application/json": { "name": "Puma", "type": "Dog", "color": "Black", "gender": "Female", "breed": "Mixed" } } ``` ```yaml application/json: name: Puma type: Dog color: Black gender: Female breed: Mixed ``` #### Header Object Field Name | Type | Description ---|:---:|--- description | `string` | A short description of the header. type | `string` | **Required.** The type of the object. The value MUST be one of `"string"`, `"number"`, `"integer"`, `"boolean"`, or `"array"`. format | `string` | The extending format for the previously mentioned [`type`](#stType). See [Data Type Formats](#dataTypeFormat) for further details. items | [Items Object](#itemsObject) | **Required if [`type`](#stType) is "array".** Describes the type of items in the array. collectionFormat | `string` | Determines the format of the array if type array is used. Possible values are:
  • `csv` - comma separated values `foo,bar`.
  • `ssv` - space separated values `foo bar`.
  • `tsv` - tab separated values `foo\tbar`.
  • `pipes` - pipe separated values foo|bar.
Default value is `csv`. default | * | Sets a default value for the header. See http://json-schema.org/latest/json-schema-validation.html#anchor101. Unlike JSON Schema this value MUST conform to the defined [`type`](#headerDefault) for the header. maximum | `number` | See http://json-schema.org/latest/json-schema-validation.html#anchor17. exclusiveMaximum | `boolean` | See http://json-schema.org/latest/json-schema-validation.html#anchor17. minimum | `number` | See http://json-schema.org/latest/json-schema-validation.html#anchor21. exclusiveMinimum | `boolean` | See http://json-schema.org/latest/json-schema-validation.html#anchor21. maxLength | `integer` | See http://json-schema.org/latest/json-schema-validation.html#anchor26. minLength | `integer` | See http://json-schema.org/latest/json-schema-validation.html#anchor29. pattern | `string` | See http://json-schema.org/latest/json-schema-validation.html#anchor33. maxItems | `integer` | See http://json-schema.org/latest/json-schema-validation.html#anchor42. minItems | `integer` | See http://json-schema.org/latest/json-schema-validation.html#anchor45. uniqueItems | `boolean` | See http://json-schema.org/latest/json-schema-validation.html#anchor49. enum | [*] | See http://json-schema.org/latest/json-schema-validation.html#anchor76. multipleOf | `number` | See http://json-schema.org/latest/json-schema-validation.html#anchor14. ##### Header Object Example A simple header with of an integer type: ```js { "description": "The number of allowed requests in the current period", "type": "integer" } ``` ```yaml description: The number of allowed requests in the current period type: integer ``` #### Tag Object Allows adding meta data to a single tag that is used by the [Operation Object](#operationObject). It is not mandatory to have a Tag Object per tag used there. ##### Fixed Fields Field Name | Type | Description ---|:---:|--- name | `string` | **Required.** The name of the tag. description | `string` | A short description for the tag. [GFM syntax](https://help.github.com/articles/github-flavored-markdown) can be used for rich text representation. externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this tag. ##### Patterned Fields Field Pattern | Type | Description ---|:---:|--- ^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#vendorExtensions) for further details. ##### Tag Object Example ```js { "name": "pet", "description": "Pets operations" } ``` ```yaml name: pet description: Pets operations ``` #### Reference Object A simple object to allow referencing other definitions in the specification. It can be used to reference parameters and responses that are defined at the top level for reuse. The Reference Object is a [JSON Reference](http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-02) that uses a [JSON Pointer](http://tools.ietf.org/html/rfc6901) as its value. For this specification, only [canonical dereferencing](http://json-schema.org/latest/json-schema-core.html#anchor27) is supported. ##### Fixed Fields Field Name | Type | Description ---|:---:|--- $ref | `string` | **Required.** The reference string. ##### Reference Object Example ```js { "$ref": "#/definitions/Pet" } ``` ```yaml $ref: '#/definitions/Pet' ``` #### Schema Object The Schema Object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. This object is based on the [JSON Schema Specification Draft 4](http://json-schema.org/) and uses a predefined subset of it. On top of this subset, there are extensions provided by this specification to allow for more complete documentation. Further information about the properties can be found in [JSON Schema Core](http://json-schema.org/latest/json-schema-core.html) and [JSON Schema Validation](http://json-schema.org/latest/json-schema-validation.html). Unless stated otherwise, the property definitions follow the JSON Schema specification as referenced here. The following properties are taken directly from the JSON Schema definition and follow the same specifications: - $ref - As a [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03) - format (See [Data Type Formats](#dataTypeFormat) for further details) - title - description ([GFM syntax](https://help.github.com/articles/github-flavored-markdown) can be used for rich text representation) - default (Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object) - multipleOf - maximum - exclusiveMaximum - minimum - exclusiveMinimum - maxLength - minLength - pattern - maxItems - minItems - uniqueItems - maxProperties - minProperties - required - enum - type The following properties are taken from the JSON Schema definition but their definitions were adjusted to the Swagger Specification. Their definition is the same as the one from JSON Schema, only where the original definition references the JSON Schema definition, the [Schema Object](#schemaObject) definition is used instead. - items - allOf - properties - additionalProperties Other than the JSON Schema subset fields, the following fields may be used for further schema documentation. ##### Fixed Fields Field Name | Type | Description ---|:---:|--- discriminator | `string` | Adds support for polymorphism. The discriminator is the schema property name that is used to differentiate between other schema that inherit this schema. The property name used MUST be defined at this schema and it MUST be in the `required` property list. When used, the value MUST be the name of this schema or any schema that inherits it. readOnly | `boolean` | Relevant only for Schema `"properties"` definitions. Declares the property as "read only". This means that it MAY be sent as part of a response but MUST NOT be sent as part of the request. Properties marked as `readOnly` being `true` SHOULD NOT be in the `required` list of the defined schema. Default value is `false`. xml | [XML Object](#xmlObject) | This MAY be used only on properties schemas. It has no effect on root schemas. Adds Additional metadata to describe the XML representation format of this property. externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this schema. example | Any | A free-form property to include a an example of an instance for this schema. ###### Composition and Inheritance (Polymorphism) Swagger allows combining and extending model definitions using the `allOf` property of JSON Schema, in effect offering model composition. `allOf` takes in an array of object definitions that are validated *independently* but together compose a single object. While composition offers model extensibility, it does not imply a hierarchy between the models. To support polymorphism, Swagger adds the support of the `discriminator` field. When used, the `discriminator` will be the name of the property used to decide which schema definition is used to validate the structure of the model. As such, the `discriminator` field MUST be a required field. The value of the chosen property has to be the friendly name given to the model under the `definitions` property. As such, inline schema definitions, which do not have a given id, *cannot* be used in polymorphism. ###### XML Modeling The [xml](#schemaXml) property allows extra definitions when translating the JSON definition to XML. The [XML Object](#xmlObject) contains additional information about the available options. ##### Schema Object Examples ###### Primitive Sample Unlike previous versions of Swagger, Schema definitions can be used to describe primitive and arrays as well. ```js { "type": "string", "format": "email" } ``` ```yaml type: string format: email ``` ###### Simple Model ```js { "type": "object", "required": [ "name" ], "properties": { "name": { "type": "string" }, "address": { "$ref": "#/definitions/Address" }, "age": { "type": "integer", "format": "int32", "minimum": 0 } } } ``` ```yaml type: object required: - name properties: name: type: string address: $ref: '#/definitions/Address' age: type: integer format: int32 minimum: 0 ``` ###### Model with Map/Dictionary Properties For a simple string to string mapping: ```js { "type": "object", "additionalProperties": { "type": "string" } } ``` ```yaml type: object additionalProperties: type: string ``` For a string to model mapping: ```js { "type": "object", "additionalProperties": { "$ref": "#/definitions/ComplexModel" } } ``` ```yaml type: object additionalProperties: $ref: '#/definitions/ComplexModel' ``` ###### Model with Example ```js { "properties": { "id": { "type": "integer", "format": "int64" }, "name": { "type": "string" } }, "required": [ "name" ], "example": { "name": "Puma", "id": 1 } } ``` ```yaml properties: id: type: integer format: int64 name: type: string required: - name example: name: Puma id: 1 ``` ###### Models with Composition ```js { "definitions": { "ErrorModel": { "type": "object", "required": [ "message", "code" ], "properties": { "message": { "type": "string" }, "code": { "type": "integer", "minimum": 100, "maximum": 600 } } }, "ExtendedErrorModel": { "allOf": [ { "$ref": "#/definitions/ErrorModel" }, { "type": "object", "required": [ "rootCause" ], "properties": { "rootCause": { "type": "string" } } } ] } } } ``` ```yaml definitions: ErrorModel: type: object required: - message - code properties: message: type: string code: type: integer minimum: 100 maximum: 600 ExtendedErrorModel: allOf: - $ref: '#/definitions/ErrorModel' - type: object required: - rootCause properties: rootCause: type: string ``` ###### Models with Polymorphism Support ```js { "definitions": { "Pet": { "discriminator": "petType", "properties": { "name": { "type": "string" }, "petType": { "type": "string" } }, "required": [ "name", "petType" ] } }, "Cat": { "description": "A representation of a cat", "allOf": [ { "$ref": "#/definitions/Pet" }, { "properties": { "huntingSkill": { "type": "string", "description": "The measured skill for hunting", "default": "lazy", "enum": [ "clueless", "lazy", "adventurous", "aggressive" ] } }, "required": [ "huntingSkill" ] } ] }, "Dog": { "description": "A representation of a dog", "allOf": [ { "$ref": "#/definitions/Pet" }, { "properties": { "packSize": { "type": "integer", "format": "int32", "description": "the size of the pack the dog is from", "default": 0, "minimum": 0 } }, "required": [ "packSize" ] } ] } } ``` ```yaml definitions: Pet: discriminator: petType properties: name: type: string petType: type: string required: - name - petType Cat: description: A representation of a cat allOf: - $ref: '#/definitions/Pet' - properties: huntingSkill: type: string description: The measured skill for hunting default: lazy enum: - clueless - lazy - adventurous - aggressive required: - huntingSkill Dog: description: A representation of a dog allOf: - $ref: '#/definitions/Pet' - properties: packSize: type: integer format: int32 description: the size of the pack the dog is from default: 0 minimum: 0 required: - packSize ``` #### XML Object A metadata object that allows for more fine-tuned XML model definitions. When using arrays, XML element names are *not* inferred (for singular/plural forms) and the `name` property should be used to add that information. See examples for expected behavior. ##### Fixed Fields Field Name | Type | Description ---|:---:|--- name | `string` | Replaces the name of the element/attribute used for the described schema property. When defined within the Items Object (`items`), it will affect the name of the individual XML elements within the list. When defined alongside `type` being `array` (outside the `items`), it will affect the wrapping element and only if `wrapped` is `true`. If `wrapped` is `false`, it will be ignored. namespace | `string` | The URL of the namespace definition. Value SHOULD be in the form of a URL. prefix | `string` | The prefix to be used for the [name](#xmlName). attribute | `boolean` | Declares whether the property definition translates to an attribute instead of an element. Default value is `false`. wrapped | `boolean` | MAY be used only for an array definition. Signifies whether the array is wrapped (for example, ``) or unwrapped (``). Default value is `false`. The definition takes effect only when defined alongside `type` being `array` (outside the `items`). ##### XML Object Examples The examples of the XML object definitions are included inside a property definition of a [Schema Object](#schemaObject) with a sample of the XML representation of it. ###### No XML Element Basic string property: ```js { "animals": { "type": "string" } } ``` ```yaml animals: type: string ``` ```xml ... ``` Basic string array property ([`wrapped`](#xmlWrapped) is `false` by default): ```js { "animals": { "type": "array", "items": { "type": "string" } } } ``` ```yaml animals: type: array items: type: string ``` ```xml ... ... ... ``` ###### XML Name Replacement ```js { "animals": { "type": "string", "xml": { "name": "animal" } } } ``` ```yaml animals: type: string xml: name: animal ``` ```xml ... ``` ###### XML Attribute, Prefix and Namespace In this example, a full model definition is shown. ```js { "Person": { "type": "object", "properties": { "id": { "type": "integer", "format": "int32", "xml": { "attribute": true }, "name": { "type": "string", "xml": { "namespace": "http://swagger.io/schema/sample", "prefix": "sample" } } } } } } ``` ```yaml Person: type: object properties: id: type: integer format: int32 xml: attribute: true name: type: string xml: namespace: http://swagger.io/schema/sample prefix: sample ``` ```xml example ``` ###### XML Arrays Changing the element names: ```js { "animals": { "type": "array", "items": { "type": "string", "xml": { "name": "animal" } } } } ``` ```yaml animals: type: array items: type: string xml: name: animal ``` ```xml value value ``` The external `name` property has no effect on the XML: ```js { "animals": { "type": "array", "items": { "type": "string", "xml": { "name": "animal" } }, "xml": { "name": "aliens" } } } ``` ```yaml animals: type: array items: type: string xml: name: animal xml: name: aliens ``` ```xml value value ``` Even when the array is wrapped, if no name is explicitly defined, the same name will be used both internally and externally: ```js { "animals": { "type": "array", "items": { "type": "string" }, "xml": { "wrapped": true } } } ``` ```yaml animals: type: array items: type: string xml: wrapped: true ``` ```xml value value ``` To overcome the above example, the following definition can be used: ```js { "animals": { "type": "array", "items": { "type": "string", "xml": { "name": "animal" } }, "xml": { "wrapped": true } } } ``` ```yaml animals: type: array items: type: string xml: name: animal xml: wrapped: true ``` ```xml value value ``` Affecting both internal and external names: ```js { "animals": { "type": "array", "items": { "type": "string", "xml": { "name": "animal" } }, "xml": { "name": "aliens", "wrapped": false } } } ``` ```yaml animals: type: array items: type: string xml: name: animal xml: name: aliens wrapped: false ``` ```xml value value ``` If we change the external element but not the internal ones: ```js { "animals": { "type": "array", "items": { "type": "string" }, "xml": { "name": "aliens", "wrapped": true } } } ``` ```yaml animals: type: array items: type: string xml: name: aliens wrapped: true ``` ```xml value value ``` #### Definitions Object An object to hold data types that can be consumed and produced by operations. These data types can be primitives, arrays or models. ##### Patterned Fields Field Pattern | Type | Description ---|:---:|--- {name} | [Schema Object](#schemaObject) | A single definition, mapping a "name" to the schema it defines. ##### Definitions Object Example ```js { "Category": { "properties": { "id": { "type": "integer", "format": "int64" }, "name": { "type": "string" } } }, "Tag": { "properties": { "id": { "type": "integer", "format": "int64" }, "name": { "type": "string" } } } } ``` ```yaml Category: properties: id: type: integer format: int64 name: type: string Tag: properties: id: type: integer format: int64 name: type: string ``` #### Parameters Definitions Object An object to hold parameters to be reused across operations. Parameter definitions can be referenced to the ones defined here. This does *not* define global operation parameters. ##### Patterned Fields Field Pattern | Type | Description ---|:---:|--- {name} | [Parameter Object](#parameterObject) | A single parameter definition, mapping a "name" to the parameter it defines. ##### Parameters Definition Object Example ```js { "skipParam": { "name": "skip", "in": "query", "description": "number of items to skip", "required": true, "type": "integer", "format": "int32" }, "limitParam": { "name": "limit", "in": "query", "description": "max records to return", "required": true, "type": "integer", "format": "int32" } } ``` ```yaml skipParam: name: skip in: query description: number of items to skip required: true type: integer format: int32 limitParam: name: limit in: query description: max records to return required: true type: integer format: int32 ``` #### Responses Definitions Object An object to hold responses to be reused across operations. Response definitions can be referenced to the ones defined here. This does *not* define global operation responses. ##### Patterned Fields Field Pattern | Type | Description ---|:---:|--- {name} | [Response Object](#responseObject) | A single response definition, mapping a "name" to the response it defines. ##### Responses Definitions Object Example ```js { "NotFound": { "description": "Entity not found." }, "IllegalInput": { "description": "Illegal input for operation." }, "GeneralError": { "description": "General Error", "schema": { "$ref": "#/definitions/GeneralError" } } } ``` ```yaml NotFound: description: Entity not found. IllegalInput: description: Illegal input for operation. GeneralError: description: General Error schema: $ref: '#/definitions/GeneralError' ``` #### Security Definitions Object A declaration of the security schemes available to be used in the specification. This does not enforce the security schemes on the operations and only serves to provide the relevant details for each scheme. ##### Patterned Fields Field Pattern | Type | Description ---|:---:|--- {name} | [Security Scheme Object](#securitySchemeObject) | A single security scheme definition, mapping a "name" to the scheme it defines. ##### Security Definitions Object Example ```js { "api_key": { "type": "apiKey", "name": "api_key", "in": "header" }, "petstore_auth": { "type": "oauth2", "authorizationUrl": "http://swagger.io/api/oauth/dialog", "flow": "implicit", "scopes": { "write:pets": "modify pets in your account", "read:pets": "read your pets" } } } ``` ```yaml api_key: type: apiKey name: api_key in: header petstore_auth: type: oauth2 authorizationUrl: http://swagger.io/api/oauth/dialog flow: implicit scopes: write:pets: modify pets in your account read:pets: read your pets ``` #### Security Scheme Object Allows the definition of a security scheme that can be used by the operations. Supported schemes are basic authentication, an API key (either as a header or as a query parameter) and OAuth2's common flows (implicit, password, application and access code). ##### Fixed Fields Field Name | Type | Validity | Description ---|:---:|---|--- type | `string` | Any | **Required.** The type of the security scheme. Valid values are `"basic"`, `"apiKey"` or `"oauth2"`. description | `string` | Any | A short description for security scheme. name | `string` | `apiKey` | **Required.** The name of the header or query parameter to be used. in | `string` | `apiKey` | **Required** The location of the API key. Valid values are `"query"` or `"header"`. flow | `string` | `oauth2` | **Required.** The flow used by the OAuth2 security scheme. Valid values are `"implicit"`, `"password"`, `"application"` or `"accessCode"`. authorizationUrl | `string` | `oauth2` (`"implicit"`, `"accessCode"`) | **Required.** The authorization URL to be used for this flow. This SHOULD be in the form of a URL. tokenUrl | `string` | `oauth2` (`"password"`, `"application"`, `"accessCode"`) | **Required.** The token URL to be used for this flow. This SHOULD be in the form of a URL. scopes | [Scopes Object](#scopesObject) | `oauth2` | **Required.** The available scopes for the OAuth2 security scheme. ##### Patterned Fields Field Name | Type | Description ---|:---:|--- ^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#vendorExtensions) for further details. ##### Security Scheme Object Example ###### Basic Authentication Sample ```js { "type": "basic" } ``` ```yaml type: basic ``` ###### API Key Sample ```js { "type": "apiKey", "name": "api_key", "in": "header" } ``` ```yaml type: apiKey name: api_key in: header ``` ###### Implicit OAuth2 Sample ```js { "type": "oauth2", "authorizationUrl": "http://swagger.io/api/oauth/dialog", "flow": "implicit", "scopes": { "write:pets": "modify pets in your account", "read:pets": "read your pets" } } ``` ```yaml type: oauth2 authorizationUrl: http://swagger.io/api/oauth/dialog flow: implicit scopes: write:pets: modify pets in your account read:pets: read your pets ``` #### Scopes Object Lists the available scopes for an OAuth2 security scheme. ##### Patterned Fields Field Pattern | Type | Description ---|:---:|--- {name} | `string` | Maps between a name of a scope to a short description of it (as the value of the property). ##### Scopes Object Example ```js { "write:pets": "modify pets in your account", "read:pets": "read your pets" } ``` ```yaml write:pets: modify pets in your account read:pets: read your pets ``` #### Security Requirement Object Lists the required security schemes to execute this operation. The object can have multiple security schemes declared in it which are all required (that is, there is a logical AND between the schemes). The name used for each property MUST correspond to a security scheme declared in the [Security Definitions](#securityDefinitionsObject). ##### Patterned Fields Field Pattern | Type | Description ---|:---:|--- {name} | [`string`] | Each name must correspond to a security scheme which is declared in the [Security Definitions](#securityDefinitions). If the security scheme is of type `"oauth2"`, then the value is a list of scope names required for the execution. For other security scheme types, the array MUST be empty. ##### Security Requirement Object Examples ###### Non-OAuth2 Security Requirement ```js { "api_key": [] } ``` ```yaml api_key: [] ``` ###### OAuth2 Security Requirement ```js { "petstore_auth": [ "write:pets", "read:pets" ] } ``` ```yaml petstore_auth: - write:pets - read:pets ``` ### Specification Extensions While the Swagger Specification tries to accommodate most use cases, additional data can be added to extend the specification at certain points. The extensions properties are always prefixed by `"x-"` and can have any valid JSON format value. The extensions may or may not be supported by the available tooling, but those may be extended as well to add requested support (if tools are internal or open-sourced). ### Security Filtering Some objects in the Swagger specification may be declared and remain empty, or completely be removed, even though they are inherently the core of the API documentation. The reasoning behind it is to allow an additional layer of access control over the documentation itself. While not part of the specification itself, certain libraries may choose to allow access to parts of the documentation based on some form of authentication/authorization. Two examples for this: 1. The [Paths Object](#pathsObject) may be empty. It may be counterintuitive, but this may tell the viewer that they got to the right place, but can't access any documentation. They'd still have access to the [Info Object](#infoObject) which may contain additional information regarding authentication. 2. The [Path Item Object](#pathItemObject) may be empty. In this case, the viewer will be aware that the path exists, but will not be able to see any of its operations or parameters. This is different than hiding the path itself from the [Paths Object](#pathsObject) so the user will not be aware of its existence. This allows the documentation provider a finer control over what the viewer can see. ================================================ FILE: src/SwaggerWcf/Attributes/SwaggerWcfAttribute.cs ================================================ using System; namespace SwaggerWcf.Attributes { /// /// Attribute to enable a class or interface to be scanned by SwaggerWcf /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] public class SwaggerWcfAttribute : Attribute { /// /// The base path on which the API is served, which is relative to the host. If it is not included, /// the API is served directly under the host. The value MUST start with a leading slash (/). The /// basePath does not support path templating. /// public string ServicePath { get; set; } /// /// Export this service on Swagger file /// public SwaggerWcfAttribute() { } /// /// Export this service on Swagger file with base path of /// /// Service path public SwaggerWcfAttribute(string servicePath) { ServicePath = servicePath.StartsWith("/") ? servicePath : $"/{servicePath}"; } } } ================================================ FILE: src/SwaggerWcf/Attributes/SwaggerWcfContactInfoAttribute.cs ================================================ using SwaggerWcf.Models; using System; namespace SwaggerWcf.Attributes { /// /// Provides values for Contact information for the exposed API. /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] public class SwaggerWcfContactInfoAttribute : Attribute { /// /// The identifying name of the contact person/organization. /// public string Name { get; set; } /// /// The email address of the contact person/organization. MUST be in the format of an email address. /// public string Email { get; set; } /// /// The URL pointing to the contact information. MUST be in the format of a URL. /// public string Url { get; set; } public static explicit operator InfoContact(SwaggerWcfContactInfoAttribute attr) { return new InfoContact { Name = attr.Name, Url = attr.Url, Email = attr.Email }; } } } ================================================ FILE: src/SwaggerWcf/Attributes/SwaggerWcfContentTypesAttribute.cs ================================================ using System; using System.Net; namespace SwaggerWcf.Attributes { /// /// Overrides the return type /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class SwaggerWcfContentTypesAttribute : Attribute { /// /// Overrides the return type /// /// Method return type public SwaggerWcfContentTypesAttribute(string[] consumeTypes = null, string[] produceTypes = null) { ConsumeTypes = consumeTypes; ProduceTypes = produceTypes; } /// /// Override Response Content-Types /// public string[] ConsumeTypes { get; set; } /// /// Override Response Content-Types /// public string[] ProduceTypes { get; set; } } } ================================================ FILE: src/SwaggerWcf/Attributes/SwaggerWcfDefinitionAttribute.cs ================================================ using System; namespace SwaggerWcf.Attributes { /// /// Attribute to describe a class as a definition on swagger /// [AttributeUsage(AttributeTargets.Class)] public class SwaggerWcfDefinitionAttribute : Attribute { /// /// Description of the external documentation /// public string ExternalDocsDescription { get; set; } /// /// URL of the external documentation /// public string ExternalDocsUrl { get; set; } /// /// Optional custom name for model. Model names default to class's fully qualified name /// public string ModelName { get; set; } /// /// Configures a description with more information /// /// Description external docs description /// Description external docs URL public SwaggerWcfDefinitionAttribute(string externalDocsDescription = null, string externalDocsUrl = null) { ExternalDocsDescription = externalDocsDescription; ExternalDocsUrl = externalDocsUrl; } } } ================================================ FILE: src/SwaggerWcf/Attributes/SwaggerWcfHeaderAttribute.cs ================================================ using System; namespace SwaggerWcf.Attributes { /// /// Describe a parameter /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class SwaggerWcfHeaderAttribute : Attribute { /// /// Describes a parameter /// /// Parameter name /// Set parameter as required. Defaults is false. /// Parameter description. /// Parameter default value. public SwaggerWcfHeaderAttribute(string name, bool required = false, string description = null, string defaultValue = null) { Name = name; Required = required; Description = description; DefaultValue = defaultValue; } /// /// Name of this parameter /// public string Name { get; set; } /// /// Defines if this parameter is required in operations /// public bool Required { get; set; } /// /// Description of this parameter /// public string Description { get; set; } /// /// Default value of this parameter /// public string DefaultValue { get; set; } } } ================================================ FILE: src/SwaggerWcf/Attributes/SwaggerWcfHiddenAttribute.cs ================================================ using System; namespace SwaggerWcf.Attributes { /// /// Attribute to hide a method, class, parameter or property from Swagger. /// This overrides any tag-based settings. /// [AttributeUsage( AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Parameter)] public class SwaggerWcfHiddenAttribute : Attribute { } } ================================================ FILE: src/SwaggerWcf/Attributes/SwaggerWcfLicenseInfoAttribute.cs ================================================ using SwaggerWcf.Models; using System; namespace SwaggerWcf.Attributes { /// /// Provides values for License information for the exposed API. /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] public class SwaggerWcfLicenseInfoAttribute : Attribute { /// /// Required. The license name used for the API. /// public string Name { get; } /// /// A URL to the license used for the API. MUST be in the format of a URL. /// public string Url { get; set; } /// /// Provides values for License information for the exposed API. /// /// The license name used for the API. public SwaggerWcfLicenseInfoAttribute(string name) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException(nameof(name)); } Name = name; } public static explicit operator InfoLicense(SwaggerWcfLicenseInfoAttribute attr) { return new InfoLicense { Name = attr.Name, Url = attr.Url }; } } } ================================================ FILE: src/SwaggerWcf/Attributes/SwaggerWcfParameterAttribute.cs ================================================ using System; namespace SwaggerWcf.Attributes { /// /// Describe a parameter /// [AttributeUsage(AttributeTargets.Parameter)] public class SwaggerWcfParameterAttribute : Attribute { /// /// Describes a parameter /// /// Set parameter as required. Defaults is false. /// Parameter description. public SwaggerWcfParameterAttribute(bool required = false, string description = null, Type parameterType = null) { Required = required; Description = description; ParameterType = parameterType; } /// /// Defines if this parameter is required in operations /// public bool Required { get; set; } /// /// Description of this parameter /// public string Description { get; set; } /// /// Override parameter type /// public Type ParameterType { get; set; } } } ================================================ FILE: src/SwaggerWcf/Attributes/SwaggerWcfPathAttribute.cs ================================================ using System; namespace SwaggerWcf.Attributes { /// /// Attribute to describe a method exported as a path in swagger /// [AttributeUsage(AttributeTargets.Method)] public class SwaggerWcfPathAttribute : Attribute { /// /// Configures a path with more information /// /// Path summary /// Path description /// Path Operation ID /// Path external docs description /// Path external docs URL /// Path deprecated (defaults to false) public SwaggerWcfPathAttribute(string summary = null, string description = null, string operationId = null, string externalDocsDescription = null, string externalDocsUrl = null, bool deprecated = false, string operationPath = null) { Summary = summary; Description = description; OperationId = operationId; ExternalDocsDescription = externalDocsDescription; ExternalDocsUrl = externalDocsUrl; Deprecated = deprecated; OperationPath = operationPath; } /// /// Path summary /// public string Summary { get; set; } /// /// Path description /// public string Description { get; set; } /// /// Path Operation ID /// public string OperationId { get; set; } /// /// Path external docs description /// public string ExternalDocsDescription { get; set; } /// /// Path external docs URL /// public string ExternalDocsUrl { get; set; } /// /// Path deprecated /// public bool Deprecated { get; set; } /// /// Operation path, extends service path /// public string OperationPath { get; set; } } } ================================================ FILE: src/SwaggerWcf/Attributes/SwaggerWcfPropertyAttribute.cs ================================================ using System; using SwaggerWcf.Models; namespace SwaggerWcf.Attributes { /// /// Describe a property /// [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] public class SwaggerWcfPropertyAttribute : Attribute { /// /// Describes a property /// public SwaggerWcfPropertyAttribute() { } public string Title { get; set; } /// /// Description of this parameter /// public string Description { get; set; } /// /// Determines whether this parameter is mandatory. /// public bool Required { get { return _Required.GetValueOrDefault(); } set { _Required = value; } } /// /// Sets the ability to pass empty-valued parameters. This is valid /// only for either query or formData parameters and allows you to /// send a parameter with a name only or an empty value. /// //public bool AllowEmptyValue { get { return _AllowEmptyValue ?? false; } set { _AllowEmptyValue = value; } } /// /// Determines the format of the array if type array is used. /// //public CollectionFormat? CollectionFormat { get; set; } /// /// Declares the value of the parameter that the server will use if none is provided /// public string Default { get; set; } /// /// Illustrate what the value is supposed to be like. /// public object Example { get; set; } /// /// Maximum allowed value, as modified by ExclusiveMaximum. /// Must be a valid JSON number, and storable as a decimal. /// public string Maximum { get { return _Maximum.HasValue ? _Maximum.ToString() : null; } set { _Maximum = decimal.Parse(value); } } /// /// If true, the instance is valid if it is strictly less than the value of Maximum. /// public bool ExclusiveMaximum { get { return _ExclusiveMaximum.GetValueOrDefault(); } set { _ExclusiveMaximum = value; } } /// /// Minimum allowed value, as modified by ExclusiveMinimum /// Must be a valid JSON number, and storable as a decimal. /// public string Minimum { get { return _Minimum.HasValue ? _Minimum.ToString() : null; } set { _Minimum = decimal.Parse(value); } } /// /// If true, the instance is valid if it is strictly greatern than the value of Maximum. /// public bool ExclusiveMinimum { get { return _ExclusiveMinimum.GetValueOrDefault(); } set { _ExclusiveMinimum = value; } } /// /// Maximum length. /// public int MaxLength { get { return _MaxLength.GetValueOrDefault(); } set { _MaxLength = value; } } /// /// Minimum length /// public int MinLength { get { return _MinLength.GetValueOrDefault(); } set { _MinLength = value; } } /// /// Should be a valid regular expression, according to the ECMA 262 regular expression dialect. /// A string instance is considered valid if the regular expression matches the instance successfully. /// Regular expressions are not implicitly anchored. /// public string Pattern { get; set; } /// /// An array instance is valid against MaxItems if its size /// is less than, or equal to, the value of this keyword. /// public int MaxItems { get { return _MaxItems.GetValueOrDefault(); } set { _MaxItems = value; } } /// /// An array instance is valid against MaxItems if its size /// is greater than, or equal to, the value of this keyword. /// public int MinItems { get { return _MinItems.GetValueOrDefault(); } set { _MinItems = value; } } /// /// If true, the instance validates successfully if all of its elements are unique. /// public bool UniqueItems { get { return _UniqueItems.GetValueOrDefault(); } set { _UniqueItems = value; } } /// /// A numeric instance is valid against "multipleOf" if the result of /// the division of the instance by this keyword's value is an integer. /// public decimal MultipleOf { get { return _MultipleOf.GetValueOrDefault(); } set { _MultipleOf = value; } } // To be usable as attribute named parameters, parameter types must not be // nullable but we need to be able to see whether each value was set or not, // so hide a nullable value for each available option. internal bool? _Required { get; set; } internal bool? _ExclusiveMaximum { get; set; } internal decimal? _Minimum { get; set; } internal decimal? _Maximum { get; set; } internal bool? _ExclusiveMinimum { get; set; } internal int? _MaxLength { get; set; } internal int? _MinLength { get; set; } internal int? _MaxItems { get; set; } internal int? _MinItems { get; set; } internal bool? _UniqueItems { get; set; } internal decimal? _MultipleOf { get; set; } } } ================================================ FILE: src/SwaggerWcf/Attributes/SwaggerWcfRegexAttribute.cs ================================================ using System; namespace SwaggerWcf.Attributes { /// /// Apply a Regular Expression /// [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class SwaggerWcfRegexAttribute : Attribute { /// /// Applies a Regular Expression to a field or property /// /// Regular Expression public SwaggerWcfRegexAttribute(string regex) { Regex = regex; } /// /// Regular Expression /// public string Regex { get; set; } } } ================================================ FILE: src/SwaggerWcf/Attributes/SwaggerWcfRequestTypeAttribute.cs ================================================ using System; using System.Net; namespace SwaggerWcf.Attributes { /// /// Overrides the return type /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class SwaggerWcfRequestTypeAttribute : Attribute { /// /// Overrides the return type /// /// Method parameter type name public SwaggerWcfRequestTypeAttribute(string name = null) { Name = name; } /// /// Override parameter Type in Wrapped Request /// public string Name { get; set; } } } ================================================ FILE: src/SwaggerWcf/Attributes/SwaggerWcfResponseAttribute.cs ================================================ using System; using System.Net; namespace SwaggerWcf.Attributes { /// /// Attribute to describe path responses. If none is specified, a 'default' one is created /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class SwaggerWcfResponseAttribute : Attribute { /// /// Configures a response for a path /// /// Result code /// Result description /// Result has empty response body (override default response type) /// Optional HTTP headers returned /// Optional response Type override /// Optional Response Example MIME Type /// Optional Response Example Content public SwaggerWcfResponseAttribute(string code, string description = null, bool emptyResponseOverride = false, string[] headers = null, Type responseTypeOverride = null, string exampleMimeType = null, string exampleContent = null) { Code = code; Description = description; EmptyResponseOverride = emptyResponseOverride; Headers = headers; ResponseTypeOverride = responseTypeOverride; ExampleMimeType = exampleMimeType; ExampleContent = exampleContent; } /// /// Configures a response for a path /// /// Result code /// Result description /// Result has empty response body (override default response type) /// Optional HTTP headers returned /// Optional response Type override /// Optional Response Example MIME Type /// Optional Response Example Content public SwaggerWcfResponseAttribute(HttpStatusCode code, string description = null, bool emptyResponseOverride = false, string[] headers = null, Type responseTypeOverride = null, string exampleMimeType = null, string exampleContent = null) { Code = ((int) code).ToString(); Description = description; EmptyResponseOverride = emptyResponseOverride; Headers = headers; ResponseTypeOverride = responseTypeOverride; ExampleMimeType = exampleMimeType; ExampleContent = exampleContent; } /// /// Configures a response for a path /// /// Result code /// Result description /// Result has empty response body (override default response type) /// Optional HTTP headers returned /// Optional response Type override /// Optional Response Example MIME Type /// Optional Response Example Content public SwaggerWcfResponseAttribute(int code, string description = null, bool emptyResponseOverride = false, string[] headers = null, Type responseTypeOverride = null, string exampleMimeType = null, string exampleContent = null) { Code = code.ToString(); Description = description; EmptyResponseOverride = emptyResponseOverride; Headers = headers; ResponseTypeOverride = responseTypeOverride; ExampleMimeType = exampleMimeType; ExampleContent = exampleContent; } /// /// Result code /// public string Code { get; set; } /// /// Result description /// public string Description { get; set; } /// /// Result has empty response body (override default response type) /// public bool EmptyResponseOverride { get; set; } /// /// Optional HTTP headers returned /// public string[] Headers { get; set; } /// /// Example MIME Type /// public string ExampleMimeType { get; set; } /// /// Example Content /// public string ExampleContent { get; set; } /// /// Override response type /// public Type ResponseTypeOverride { get; set; } public override bool Equals(object obj) { SwaggerWcfResponseAttribute other = obj as SwaggerWcfResponseAttribute; if (other != null) { return string.Equals(Code, other.Code) && string.Equals(Description, other.Description) && EmptyResponseOverride == other.EmptyResponseOverride && Equals(Headers, other.Headers) && ResponseTypeOverride == other.ResponseTypeOverride && ExampleMimeType == other.ExampleMimeType && ExampleContent == other.ExampleContent; } return base.Equals(obj); } public override int GetHashCode() { unchecked { int hashCode = base.GetHashCode(); hashCode = (hashCode * 397) ^ (Code != null ? Code.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Description != null ? Description.GetHashCode() : 0); hashCode = (hashCode * 397) ^ EmptyResponseOverride.GetHashCode(); hashCode = (hashCode * 397) ^ (Headers != null ? Headers.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (ResponseTypeOverride != null ? ResponseTypeOverride.GetHashCode() : 0); hashCode = (hashCode * 397) ^ ExampleMimeType?.GetHashCode() ?? 0; hashCode = (hashCode * 397) ^ ExampleContent?.GetHashCode() ?? 0; return hashCode; } } } } ================================================ FILE: src/SwaggerWcf/Attributes/SwaggerWcfReturnTypeAttribute.cs ================================================ using System; using System.Net; namespace SwaggerWcf.Attributes { /// /// Overrides the return type /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class SwaggerWcfReturnTypeAttribute : Attribute { /// /// Overrides the return type /// /// Method return type /// Method return type name public SwaggerWcfReturnTypeAttribute(Type returnType = null, string name = null) { ReturnType = returnType; Name = name; } /// /// Override Return Type /// public Type ReturnType { get; set; } /// /// Override Return Type in Wrapped Responses /// public string Name { get; set; } } } ================================================ FILE: src/SwaggerWcf/Attributes/SwaggerWcfSecurityAttribute.cs ================================================ using System; namespace SwaggerWcf.Attributes { /// /// Attribute to link operation to a security definition /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class SwaggerWcfSecurityAttribute : Attribute { /// /// Specify security definition for this operation /// /// Name of the Security Definition /// Scopes of the security definition public SwaggerWcfSecurityAttribute(string securityDefinitionName, params string[] scopes) { SecurityDefinitionName = securityDefinitionName; SecurityDefinitionScopes = scopes; } /// /// Name of the Security Definition /// public string SecurityDefinitionName { get; set; } /// /// Scopes of the Security Definition /// public string[] SecurityDefinitionScopes { get; set; } } } ================================================ FILE: src/SwaggerWcf/Attributes/SwaggerWcfServiceInfoAttribute.cs ================================================ using SwaggerWcf.Models; using System; namespace SwaggerWcf.Attributes { /// /// Provides metadata about the API. The metadata can be used by the clients if needed. /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] public class SwaggerWcfServiceInfoAttribute : Attribute { /// /// Required. The title of the application. /// public string Title { get; } /// /// Required Provides the version of the application API (not to be confused with the specification version). /// public string Version { get; } /// /// A short description of the application. GFM syntax can be used for rich text representation. /// public string Description { get; set; } /// /// The Terms of Service for the API. /// public string TermsOfService { get; set; } /// /// Assigns service info values /// /// The title of the application /// Provides the version of the application API (not to be confused with the specification version) public SwaggerWcfServiceInfoAttribute(string title, string version) { if (string.IsNullOrWhiteSpace(title)) throw new ArgumentNullException(nameof(title)); if (string.IsNullOrWhiteSpace(version)) throw new ArgumentNullException(nameof(version)); Title = title; Version = version; } public static explicit operator Info(SwaggerWcfServiceInfoAttribute attribute) => new Info { Title = attribute.Title, Version = attribute.Version, Description = attribute.Description, TermsOfService = attribute.TermsOfService }; } } ================================================ FILE: src/SwaggerWcf/Attributes/SwaggerWcfTagAttribute.cs ================================================ using System; namespace SwaggerWcf.Attributes { /// /// Attribute to inject a tag into a class, method, parameter or property. /// Tags can be used to categorize in Swagger UI and to hide elements using configuration /// [AttributeUsage( AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = true)] public class SwaggerWcfTagAttribute : Attribute { /// /// Injects a tag into an element /// /// Tag name /// Hide tag from spec public SwaggerWcfTagAttribute(string name, bool hideFromSpec = false) { TagName = name; HideFromSpec = hideFromSpec; } /// /// Tag name /// public string TagName { get; set; } /// /// Hide tag from spec /// public bool HideFromSpec { get; set; } } } ================================================ FILE: src/SwaggerWcf/Configuration/SettingCollection.cs ================================================ using System; using System.Configuration; namespace SwaggerWcf.Configuration { [ConfigurationCollection(typeof(TagElement), AddItemName = "setting")] public class SettingCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new SettingElement(); } protected override object GetElementKey(ConfigurationElement element) { if (element == null) { throw new ArgumentException("element"); } return ((SettingElement) element).Name; } } } ================================================ FILE: src/SwaggerWcf/Configuration/SettingElement.cs ================================================ using System.Configuration; namespace SwaggerWcf.Configuration { public class SettingElement : ConfigurationElement { [ConfigurationProperty("name", IsRequired = true, IsKey = true)] public string Name { get { return (string) this["name"]; } set { this["name"] = value; } } [ConfigurationProperty("value", IsRequired = true)] public string Value { get { return (string) this["value"]; } set { this["value"] = value; } } } } ================================================ FILE: src/SwaggerWcf/Configuration/SwaggerWcfSection.cs ================================================ using System.Configuration; namespace SwaggerWcf.Configuration { public class SwaggerWcfSection : ConfigurationSection { [ConfigurationProperty("tags", IsRequired = true)] public TagCollection Tags { get { return (TagCollection) this["tags"]; } set { this["tags"] = value; } } [ConfigurationProperty("settings", IsRequired = false)] public SettingCollection Settings { get { return (SettingCollection) this["settings"]; } set { this["settings"] = value; } } } } ================================================ FILE: src/SwaggerWcf/Configuration/TagCollection.cs ================================================ using System; using System.Configuration; namespace SwaggerWcf.Configuration { [ConfigurationCollection(typeof(TagElement), AddItemName = "tag")] public class TagCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new TagElement(); } protected override object GetElementKey(ConfigurationElement element) { if (element == null) { throw new ArgumentNullException("element"); } return ((TagElement) element).Name; } } } ================================================ FILE: src/SwaggerWcf/Configuration/TagElement.cs ================================================ using System.Configuration; namespace SwaggerWcf.Configuration { public class TagElement : ConfigurationElement { [ConfigurationProperty("name", IsRequired = true, IsKey = true)] public string Name { get { return (string) this["name"]; } set { this["name"] = value; } } [ConfigurationProperty("visible", DefaultValue = true, IsRequired = true)] public bool Visibile { get { return (bool) this["visible"]; } set { this["visible"] = value; } } } } ================================================ FILE: src/SwaggerWcf/ISwaggerWcfEndpoint.cs ================================================ using System.IO; using System.ServiceModel; using System.ServiceModel.Web; namespace SwaggerWcf { [ServiceContract] public interface ISwaggerWcfEndpoint { [OperationContract] [WebGet(UriTemplate = "/swagger.json", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] Stream GetSwaggerFile(); [OperationContract] [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/{*content}")] //[WebGet(UriTemplate = "/", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] Stream StaticContent(string content); } } ================================================ FILE: src/SwaggerWcf/Models/CollectionFormat.cs ================================================ namespace SwaggerWcf.Models { public enum CollectionFormat { Csv = 0, Ssv = 1, Tsv = 2, Pipes = 3, Multi = 4 } } ================================================ FILE: src/SwaggerWcf/Models/Definition.cs ================================================ using Newtonsoft.Json; namespace SwaggerWcf.Models { internal class Definition { public DefinitionSchema Schema { get; set; } public void Serialize(JsonWriter writer) { if (Schema == null) return; writer.WritePropertyName(Schema.Name); writer.WriteStartObject(); Schema.Serialize(writer); writer.WriteEndObject(); } } } ================================================ FILE: src/SwaggerWcf/Models/DefinitionProperty.cs ================================================ using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace SwaggerWcf.Models { internal class DefinitionProperty { public DefinitionProperty() { Maximum = decimal.MaxValue; Minimum = decimal.MinValue; MaxLength = int.MaxValue; MinLength = int.MinValue; MaxItems = int.MaxValue; MinItems = int.MinValue; MultipleOf = decimal.MinValue; } public string Title { get; set; } public string Description { get; set; } public bool Required { get; set; } public TypeFormat TypeFormat { get; set; } public string Ref { get; set; } public ParameterItems Items { get; set; } public string Default { get; set; } public object Example { get; set; } public decimal Maximum { get; set; } public bool ExclusiveMaximum { get; set; } public decimal Minimum { get; set; } public bool ExclusiveMinimum { get; set; } public int MaxLength { get; set; } public int MinLength { get; set; } public string Pattern { get; set; } public int MaxItems { get; set; } public int MinItems { get; set; } public bool UniqueItems { get; set; } public List Enum { get; set; } public decimal MultipleOf { get; set; } public void Serialize(JsonWriter writer) { writer.WritePropertyName(Title); writer.WriteStartObject(); if (TypeFormat.Type == ParameterType.Object) { writer.WritePropertyName("$ref"); writer.WriteValue(string.Format("#/definitions/{0}", Ref)); } else { if (!string.IsNullOrWhiteSpace(Description)) { writer.WritePropertyName("description"); writer.WriteValue(Description); } if (TypeFormat.Type != ParameterType.Unknown) { writer.WritePropertyName("type"); writer.WriteValue(TypeFormat.Type.ToString().ToLower()); if (!string.IsNullOrWhiteSpace(TypeFormat.Format)) { writer.WritePropertyName("format"); writer.WriteValue(TypeFormat.Format); } } if (TypeFormat.Type == ParameterType.Array && Items != null) { writer.WritePropertyName("items"); Items.Serialize(writer); } if (!string.IsNullOrWhiteSpace(Default)) { writer.WritePropertyName("default"); writer.WriteValue(Default); } if (Example!=null) { writer.WritePropertyName("example"); if (Example.GetType().IsArray) { writer.WriteStartArray(); foreach (var value in (object[])Example) { writer.WriteValue(value); } writer.WriteEndArray(); } else writer.WriteValue(Example); } if (Maximum != decimal.MaxValue) { writer.WritePropertyName("maximum"); writer.WriteValue(Maximum); writer.WritePropertyName("exclusiveMaximum"); writer.WriteValue(ExclusiveMaximum); } if (Minimum != decimal.MinValue) { writer.WritePropertyName("minimum"); writer.WriteValue(Minimum); writer.WritePropertyName("exclusiveMinimum"); writer.WriteValue(ExclusiveMinimum); } if (MaxLength != int.MaxValue) { writer.WritePropertyName("maxLength"); writer.WriteValue(MaxLength); } if (MinLength != int.MinValue) { writer.WritePropertyName("minLength"); writer.WriteValue(MinLength); } if (!string.IsNullOrWhiteSpace(Pattern)) { writer.WritePropertyName("pattern"); writer.WriteValue(Pattern); } if (MaxItems != int.MaxValue) { writer.WritePropertyName("maxItems"); writer.WriteValue(MaxItems); } if (MinItems != int.MinValue) { writer.WritePropertyName("minItems"); writer.WriteValue(MinItems); } writer.WritePropertyName("uniqueItems"); writer.WriteValue(UniqueItems); if (Enum != null && Enum.Any()) { writer.WritePropertyName("enum"); writer.WriteStartArray(); foreach (int e in Enum) { writer.WriteValue(e); } writer.WriteEndArray(); } if (MultipleOf != decimal.MinValue) { writer.WritePropertyName("multipleOf"); writer.WriteValue(MultipleOf); } } writer.WriteEndObject(); } } } ================================================ FILE: src/SwaggerWcf/Models/DefinitionSchema.cs ================================================ using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace SwaggerWcf.Models { internal class DefinitionSchema { public TypeFormat TypeFormat { get; set; } // for primitives public string Ref { get; set; } // for references public string Name { get; set; } public string Description { get; set; } public Schema ParentSchema { get; set; } //TODO: Composition and Polymorphism Support public ExternalDocumentation ExternalDocumentation { get; set; } public List Required { get; set; } public List Properties { get; set; } public List Enum { get; set; } public void Serialize(JsonWriter writer) { if (TypeFormat.Type == ParameterType.Object) { // complex object if (!string.IsNullOrWhiteSpace(Description)) { writer.WritePropertyName("description"); writer.WriteValue(Description); } if (ParentSchema != null) { writer.WritePropertyName("allOf"); writer.WriteStartArray(); writer.WritePropertyName("$ref"); writer.WriteValue(string.Format("#/definitions/{0}", ParentSchema.Name)); writer.WriteStartObject(); } SerializeRequired(writer); SerializeExternalDocs(writer); SerializeProperties(writer); if (ParentSchema != null) { writer.WriteEndObject(); writer.WriteEndArray(); } } if (TypeFormat.Type != ParameterType.Unknown) { writer.WritePropertyName("type"); writer.WriteValue(TypeFormat.Type.ToString().ToLower()); if (!string.IsNullOrWhiteSpace(TypeFormat.Format)) { writer.WritePropertyName("format"); writer.WriteValue(TypeFormat.Format); } if (TypeFormat.Type == ParameterType.Array) { writer.WritePropertyName("items"); writer.WriteStartObject(); writer.WritePropertyName("$ref"); writer.WriteValue(string.Format("#/definitions/{0}", Ref)); writer.WriteEndObject(); } if (Enum != null && Enum.Any()) { writer.WritePropertyName("enum"); writer.WriteStartArray(); foreach (int e in Enum) { writer.WriteValue(e); } writer.WriteEndArray(); } } else if (!string.IsNullOrWhiteSpace(Ref)) { writer.WritePropertyName("$ref"); writer.WriteValue(string.Format("#/definitions/{0}", Ref)); } } private void SerializeRequired(JsonWriter writer) { if (Required != null && Required.Any()) { writer.WritePropertyName("required"); writer.WriteStartArray(); foreach (string req in Required) { writer.WriteValue(req); } writer.WriteEndArray(); } } private void SerializeExternalDocs(JsonWriter writer) { if (ExternalDocumentation?.Url != null) { writer.WritePropertyName("externalDocs"); ExternalDocumentation.Serialize(writer); } } private void SerializeProperties(JsonWriter writer) { if (Properties != null && Properties.Any()) { writer.WritePropertyName("properties"); writer.WriteStartObject(); foreach (DefinitionProperty p in Properties) { p.Serialize(writer); } writer.WriteEndObject(); } } } } ================================================ FILE: src/SwaggerWcf/Models/Example.cs ================================================ namespace SwaggerWcf.Models { internal class Example { public string MimeType { get; set; } public string Content { get; set; } } } ================================================ FILE: src/SwaggerWcf/Models/ExternalDocumentation.cs ================================================ using System.Collections.Generic; using Newtonsoft.Json; namespace SwaggerWcf.Models { internal class ExternalDocumentation { public string Description { get; set; } public string Url { get; set; } public void Serialize(JsonWriter writer) { writer.WriteStartObject(); if (!string.IsNullOrWhiteSpace(Description)) { writer.WritePropertyName("description"); writer.WriteValue(Description); } if (!string.IsNullOrWhiteSpace(Url)) { writer.WritePropertyName("url"); writer.WriteValue(Url); } writer.WriteEndObject(); } } } ================================================ FILE: src/SwaggerWcf/Models/InType.cs ================================================ namespace SwaggerWcf.Models { internal enum InType { Unknown = 0, Body = 1, Path = 2, Query = 3, FormData = 4, Header = 5 } } ================================================ FILE: src/SwaggerWcf/Models/Info.cs ================================================ using System.Collections.Generic; using Newtonsoft.Json; namespace SwaggerWcf.Models { public class Info { public string Version { get; set; } public string Title { get; set; } public string Description { get; set; } public string TermsOfService { get; set; } public InfoContact Contact { get; set; } public InfoLicense License { get; set; } internal void Serialize(JsonWriter writer) { writer.WriteStartObject(); if (!string.IsNullOrWhiteSpace(Version)) { writer.WritePropertyName("version"); writer.WriteValue(Version); } if (!string.IsNullOrWhiteSpace(Title)) { writer.WritePropertyName("title"); writer.WriteValue(Title); } if (!string.IsNullOrWhiteSpace(Description)) { writer.WritePropertyName("description"); writer.WriteValue(Description); } if (!string.IsNullOrWhiteSpace(TermsOfService)) { writer.WritePropertyName("termsOfService"); writer.WriteValue(TermsOfService); } if (Contact != null) { writer.WritePropertyName("contact"); Contact.Serialize(writer); } if (License != null) { writer.WritePropertyName("license"); License.Serialize(writer); } writer.WriteEndObject(); } } } ================================================ FILE: src/SwaggerWcf/Models/InfoContact.cs ================================================ using System.Collections.Generic; using Newtonsoft.Json; using System; namespace SwaggerWcf.Models { public class InfoContact { public string Name { get; set; } public string Email { get; set; } public string Url { get => _url; set => _url = Uri.TryCreate(value, UriKind.Absolute, out Uri _) ? value : throw new ArgumentException("Value must be in the format of a URL", nameof(Url)); } private string _url; internal void Serialize(JsonWriter writer) { writer.WriteStartObject(); if (!string.IsNullOrWhiteSpace(Name)) { writer.WritePropertyName("name"); writer.WriteValue(Name); } if (!string.IsNullOrWhiteSpace(Email)) { writer.WritePropertyName("email"); writer.WriteValue(Email); } if (!string.IsNullOrWhiteSpace(Url)) { writer.WritePropertyName("url"); writer.WriteValue(Url); } writer.WriteEndObject(); } } } ================================================ FILE: src/SwaggerWcf/Models/InfoLicense.cs ================================================ using System.Collections.Generic; using Newtonsoft.Json; using System; namespace SwaggerWcf.Models { public class InfoLicense { public string Name { get; set; } public string Url { get => _url; set => _url = Uri.TryCreate(value, UriKind.Absolute, out Uri _) ? value : throw new ArgumentException("Value must be in the format of a URL", nameof(Url)); } private string _url; internal void Serialize(JsonWriter writer) { writer.WriteStartObject(); if (!string.IsNullOrWhiteSpace(Name)) { writer.WritePropertyName("name"); writer.WriteValue(Name); } if (!string.IsNullOrWhiteSpace(Url)) { writer.WritePropertyName("url"); writer.WriteValue(Url); } writer.WriteEndObject(); } } } ================================================ FILE: src/SwaggerWcf/Models/ParameterBase.cs ================================================ using System.Collections.Generic; using Newtonsoft.Json; namespace SwaggerWcf.Models { internal abstract class ParameterBase { public string Name { get; set; } // body, path, query, formData (query and formData can have CollectionFormat as multi) public InType In { get; set; } public string Description { get; set; } public bool Required { get; set; } public abstract void Serialize(JsonWriter writer); public abstract void Serialize(JsonWriter writer, bool skipStartEndObject); } } ================================================ FILE: src/SwaggerWcf/Models/ParameterItems.cs ================================================ using System.Collections.Generic; using Newtonsoft.Json; namespace SwaggerWcf.Models { internal class ParameterItems { public TypeFormat TypeFormat { get; set; } public ParameterBase Items { get; set; } public string Ref { get; set; } public void Serialize(JsonWriter writer) { writer.WriteStartObject(); if (TypeFormat.Type != ParameterType.Unknown) { writer.WritePropertyName("type"); writer.WriteValue(TypeFormat.Type.ToString().ToLower()); if (!string.IsNullOrWhiteSpace(TypeFormat.Format)) { writer.WritePropertyName("format"); writer.WriteValue(TypeFormat.Format); } } if (!string.IsNullOrWhiteSpace(Ref)) { writer.WritePropertyName("$ref"); writer.WriteValue($"#/definitions/{Ref}"); } Items?.Serialize(writer, true); writer.WriteEndObject(); } } } ================================================ FILE: src/SwaggerWcf/Models/ParameterPrimitive.cs ================================================ using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace SwaggerWcf.Models { internal class ParameterPrimitive : ParameterBase { public ParameterPrimitive() { Maximum = decimal.MaxValue; Minimum = decimal.MinValue; MaxLength = int.MaxValue; MinLength = int.MinValue; MaxItems = int.MaxValue; MinItems = int.MinValue; MultipleOf = decimal.MinValue; } public TypeFormat TypeFormat { get; set; } public bool AllowEmptyValue { get; set; } public ParameterItems Items { get; set; } public CollectionFormat CollectionFormat { get; set; } public string Default { get; set; } public decimal Maximum { get; set; } public bool ExclusiveMaximum { get; set; } public decimal Minimum { get; set; } public bool ExclusiveMinimum { get; set; } public int MaxLength { get; set; } public int MinLength { get; set; } public string Pattern { get; set; } public int MaxItems { get; set; } public int MinItems { get; set; } public bool UniqueItems { get; set; } public List Enum { get; set; } public decimal MultipleOf { get; set; } public override void Serialize(JsonWriter writer) { Serialize(writer, false); } public override void Serialize(JsonWriter writer, bool skipStartEndObject) { if (!skipStartEndObject) writer.WriteStartObject(); if (!string.IsNullOrWhiteSpace(Name)) { writer.WritePropertyName("name"); writer.WriteValue(Name); } if (In != InType.Unknown) { writer.WritePropertyName("in"); writer.WriteValue(In.ToString().ToLower()); } if (!string.IsNullOrWhiteSpace(Description)) { writer.WritePropertyName("description"); writer.WriteValue(Description); } if (Required) { writer.WritePropertyName("required"); writer.WriteValue(Required); } if (TypeFormat.Type != ParameterType.Unknown) { if (In == InType.Body) { writer.WritePropertyName("schema"); writer.WriteStartObject(); writer.WritePropertyName("type"); writer.WriteValue(TypeFormat.Type.ToString().ToLower()); if (TypeFormat.Type == ParameterType.Array && Items != null) { writer.WritePropertyName("items"); writer.WriteStartObject(); writer.WritePropertyName("$ref"); writer.WriteValue($"#/definitions/{Items?.Ref ?? (Items?.Items as ParameterSchema)?.SchemaRef}"); //writer.WriteValue($"#/definitions/{Items?.Ref}"); writer.WriteEndObject(); } if (!string.IsNullOrWhiteSpace(TypeFormat.Format)) { writer.WritePropertyName("format"); writer.WriteValue(TypeFormat.Format); } writer.WriteEndObject(); } else { writer.WritePropertyName("type"); writer.WriteValue(TypeFormat.Type.ToString().ToLower()); if (!string.IsNullOrWhiteSpace(TypeFormat.Format)) { writer.WritePropertyName("format"); writer.WriteValue(TypeFormat.Format); } } } if (AllowEmptyValue) { writer.WritePropertyName("allowEmptyValue"); writer.WriteValue(AllowEmptyValue); } if (In != InType.Body && TypeFormat.Type == ParameterType.Array && Items != null) { writer.WritePropertyName("items"); Items.Serialize(writer); } if (In != InType.Body && TypeFormat.Type == ParameterType.Array && Items != null) { writer.WritePropertyName("collectionFormat"); writer.WriteValue(CollectionFormat); } if (!string.IsNullOrWhiteSpace(Default)) { writer.WritePropertyName("default"); writer.WriteValue(Default); } if (Maximum != decimal.MaxValue) { writer.WritePropertyName("maximum"); writer.WriteValue(Maximum); writer.WritePropertyName("exclusiveMaximum"); writer.WriteValue(ExclusiveMaximum); } if (Minimum != decimal.MinValue) { writer.WritePropertyName("minimum"); writer.WriteValue(Minimum); writer.WritePropertyName("exclusiveMinimum"); writer.WriteValue(ExclusiveMinimum); } if (MaxLength != int.MaxValue) { writer.WritePropertyName("maxLength"); writer.WriteValue(MaxLength); } if (MinLength != int.MinValue) { writer.WritePropertyName("minLength"); writer.WriteValue(MinLength); } if (!string.IsNullOrWhiteSpace(Pattern)) { writer.WritePropertyName("pattern"); writer.WriteValue(Pattern); } if (MaxItems != int.MaxValue) { writer.WritePropertyName("maxItems"); writer.WriteValue(MaxItems); } if (MinItems != int.MinValue) { writer.WritePropertyName("minItems"); writer.WriteValue(MinItems); } if (UniqueItems) { writer.WritePropertyName("uniqueItems"); writer.WriteValue(UniqueItems); } if (Enum != null && Enum.Any()) { writer.WritePropertyName("enum"); writer.WriteStartArray(); foreach (int e in Enum) { writer.WriteValue(e); } writer.WriteEndArray(); } if (MultipleOf != decimal.MinValue) { writer.WritePropertyName("multipleOf"); writer.WriteValue(MultipleOf); } if (!skipStartEndObject) writer.WriteEndObject(); } } } ================================================ FILE: src/SwaggerWcf/Models/ParameterSchema.cs ================================================ using System.Collections.Generic; using Newtonsoft.Json; namespace SwaggerWcf.Models { internal class ParameterSchema : ParameterBase { public string SchemaRef { get; set; } public override void Serialize(JsonWriter writer) { Serialize(writer, false); } public override void Serialize(JsonWriter writer, bool skipStartEndObject) { if (!skipStartEndObject) writer.WriteStartObject(); if (!string.IsNullOrWhiteSpace(Name)) { writer.WritePropertyName("name"); writer.WriteValue(Name); } if (In != InType.Unknown) { writer.WritePropertyName("in"); writer.WriteValue(In.ToString().ToLower()); } if (!string.IsNullOrWhiteSpace(Description)) { writer.WritePropertyName("description"); writer.WriteValue(Description); } if (Required) { writer.WritePropertyName("required"); writer.WriteValue(Required); } if (!string.IsNullOrWhiteSpace(SchemaRef)) { writer.WritePropertyName("schema"); writer.WriteStartObject(); writer.WritePropertyName("$ref"); writer.WriteValue(string.Format("#/definitions/{0}", SchemaRef)); writer.WriteEndObject(); } if (!skipStartEndObject) writer.WriteEndObject(); } } } ================================================ FILE: src/SwaggerWcf/Models/ParameterType.cs ================================================ namespace SwaggerWcf.Models { public enum ParameterType { Unknown = 0, Void = 1, String = 2, Number = 3, Integer = 4, Boolean = 5, Array = 6, File = 7, Object = 8 } } ================================================ FILE: src/SwaggerWcf/Models/Path.cs ================================================ using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace SwaggerWcf.Models { internal class Path { public Path() { Actions = new List(); } public string Id { get; set; } public List Actions { get; set; } public void Serialize(JsonWriter writer) { writer.WritePropertyName(Id); writer.WriteStartObject(); foreach (PathAction pathAction in Actions) { pathAction.Serialize(writer); } writer.WriteEndObject(); } } } ================================================ FILE: src/SwaggerWcf/Models/PathAction.cs ================================================ using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace SwaggerWcf.Models { internal class PathAction { public PathAction() { Tags = new List(); Consumes = new List(); Produces = new List(); Parameters = new List(); Responses = new List(); Schemes = new List(); } public string Id { get; set; } public List Tags { get; set; } public string Summary { get; set; } public string Description { get; set; } public ExternalDocumentation ExternalDocs { get; set; } public string OperationId { get; set; } public List Consumes { get; set; } public List Produces { get; set; } public List Parameters { get; set; } public List Responses { get; set; } public List Schemes { get; set; } public bool Deprecated { get; set; } public List> Security { get; set; } public void Serialize(JsonWriter writer) { writer.WritePropertyName(Id); writer.WriteStartObject(); if (Tags != null && Tags.Any()) { writer.WritePropertyName("tags"); writer.WriteStartArray(); foreach (string tag in Tags) { writer.WriteValue(tag); } writer.WriteEndArray(); } if (!string.IsNullOrWhiteSpace(Summary)) { writer.WritePropertyName("summary"); writer.WriteValue(Summary); } if (!string.IsNullOrWhiteSpace(Description)) { writer.WritePropertyName("description"); writer.WriteValue(Description); } if (ExternalDocs != null) { writer.WritePropertyName("externalDocs"); ExternalDocs.Serialize(writer); } if (!string.IsNullOrWhiteSpace(OperationId)) { writer.WritePropertyName("operationId"); writer.WriteValue(OperationId); } if (Consumes != null && Consumes.Any()) { writer.WritePropertyName("consumes"); writer.WriteStartArray(); foreach (string cons in Consumes) { writer.WriteValue(cons); } writer.WriteEndArray(); } if (Produces != null && Produces.Any()) { writer.WritePropertyName("produces"); writer.WriteStartArray(); foreach (string prod in Produces) { writer.WriteValue(prod); } writer.WriteEndArray(); } if (Parameters != null && Parameters.Any()) { writer.WritePropertyName("parameters"); writer.WriteStartArray(); foreach (ParameterBase p in Parameters) { p.Serialize(writer); } writer.WriteEndArray(); } if (Responses != null && Responses.Any()) { writer.WritePropertyName("responses"); writer.WriteStartObject(); foreach (Response r in Responses) { r.Serialize(writer); } writer.WriteEndObject(); } if (Schemes != null && Schemes.Any()) { writer.WritePropertyName("schemes"); writer.WriteStartArray(); foreach (string sch in Schemes) { writer.WriteValue(sch); } writer.WriteEndArray(); } if (Deprecated) { writer.WritePropertyName("deprecated"); writer.WriteValue(Deprecated); } if (Security != null && Security.Any()) { writer.WritePropertyName("security"); writer.WriteStartArray(); foreach (var security in Security) { writer.WriteStartObject(); writer.WritePropertyName(security.Key); writer.WriteStartArray(); if (security.Value != null && security.Value.Any()) { foreach (var scopename in security.Value) { writer.WriteValue(scopename); } } writer.WriteEndArray(); writer.WriteEndObject(); } writer.WriteEndArray(); } writer.WriteEndObject(); } } } ================================================ FILE: src/SwaggerWcf/Models/Property.cs ================================================ using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace SwaggerWcf.Models { internal class Property { public Property() { Maximum = decimal.MaxValue; Minimum = decimal.MinValue; MaxLength = int.MaxValue; MinLength = int.MinValue; MaxItems = int.MaxValue; MinItems = int.MinValue; MultipleOf = decimal.MinValue; } public string Title { get; set; } public string Description { get; set; } public bool Required { get; set; } public TypeFormat TypeFormat { get; set; } public bool AllowEmptyValue { get; set; } public ParameterItems Items { get; set; } public CollectionFormat CollectionFormat { get; set; } public string Default { get; set; } public decimal Maximum { get; set; } public bool ExclusiveMaximum { get; set; } public decimal Minimum { get; set; } public bool ExclusiveMinimum { get; set; } public int MaxLength { get; set; } public int MinLength { get; set; } public string Pattern { get; set; } public int MaxItems { get; set; } public int MinItems { get; set; } public bool UniqueItems { get; set; } public List Enum { get; set; } public decimal MultipleOf { get; set; } public void Serialize(JsonWriter writer) { writer.WriteStartObject(); if (!string.IsNullOrWhiteSpace(Title)) { writer.WritePropertyName("title"); writer.WriteValue(Title); } if (!string.IsNullOrWhiteSpace(Description)) { writer.WritePropertyName("description"); writer.WriteValue(Description); } writer.WritePropertyName("required"); writer.WriteValue(Required); if (TypeFormat.Type != ParameterType.Unknown) { writer.WritePropertyName("type"); writer.WriteValue(TypeFormat.Type.ToString().ToLower()); if (!string.IsNullOrWhiteSpace(TypeFormat.Format)) { writer.WritePropertyName("format"); writer.WriteValue(TypeFormat.Format); } } writer.WritePropertyName("allowEmptyValue"); writer.WriteValue(AllowEmptyValue); if (TypeFormat.Type == ParameterType.Array && Items != null) { writer.WritePropertyName("items"); Items.Serialize(writer); } if (TypeFormat.Type == ParameterType.Array) { writer.WritePropertyName("collectionFormat"); writer.WriteValue(CollectionFormat); } if (!string.IsNullOrWhiteSpace(Default)) { writer.WritePropertyName("default"); writer.WriteValue(Default); } if (Maximum != decimal.MaxValue) { writer.WritePropertyName("maximum"); writer.WriteValue(Maximum); writer.WritePropertyName("exclusiveMaximum"); writer.WriteValue(ExclusiveMaximum); } if (Minimum != decimal.MinValue) { writer.WritePropertyName("minimum"); writer.WriteValue(Minimum); writer.WritePropertyName("exclusiveMinimum"); writer.WriteValue(ExclusiveMinimum); } if (MaxLength != int.MaxValue) { writer.WritePropertyName("maxLength"); writer.WriteValue(MaxLength); } if (MinLength != int.MinValue) { writer.WritePropertyName("minLength"); writer.WriteValue(MinLength); } if (!string.IsNullOrWhiteSpace(Pattern)) { writer.WritePropertyName("pattern"); writer.WriteValue(Pattern); } if (MaxItems != int.MaxValue) { writer.WritePropertyName("maxItems"); writer.WriteValue(MaxItems); } if (MinItems != int.MinValue) { writer.WritePropertyName("minItems"); writer.WriteValue(MinItems); } writer.WritePropertyName("uniqueItems"); writer.WriteValue(UniqueItems); if (Enum != null && Enum.Any()) { writer.WritePropertyName("enum"); writer.WriteStartArray(); foreach (int e in Enum) { writer.WriteValue(e); } writer.WriteEndArray(); } if (MultipleOf != decimal.MinValue) { writer.WritePropertyName("multipleOf"); writer.WriteValue(MultipleOf); } writer.WriteEndObject(); } } } ================================================ FILE: src/SwaggerWcf/Models/Response.cs ================================================ using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace SwaggerWcf.Models { internal class Response { public string Code { get; set; } public string Description { get; set; } public Schema Schema { get; set; } public List Headers { get; set; } public Example Example { get; set; } public void Serialize(JsonWriter writer) { writer.WritePropertyName(Code); writer.WriteStartObject(); if (!string.IsNullOrWhiteSpace(Description)) { writer.WritePropertyName("description"); writer.WriteValue(Description); } else { writer.WritePropertyName("description"); writer.WriteValue("not available"); } if (Schema != null) { writer.WritePropertyName("schema"); writer.WriteStartObject(); Schema.Serialize(writer); writer.WriteEndObject(); } if (Example != null) { writer.WritePropertyName("examples"); writer.WriteStartObject(); writer.WritePropertyName(Example.MimeType); writer.WriteRawValue(Example.Content); writer.WriteEndObject(); } if (Headers != null && Headers.Any()) { writer.WritePropertyName("headers"); writer.WriteStartObject(); foreach (var header in Headers) { writer.WritePropertyName(header); writer.WriteStartObject(); writer.WritePropertyName("type"); writer.WriteValue("string"); writer.WriteEndObject(); } writer.WriteEndObject(); } writer.WriteEndObject(); } } } ================================================ FILE: src/SwaggerWcf/Models/Schema.cs ================================================ using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace SwaggerWcf.Models { internal class Schema { public TypeFormat TypeFormat { get; set; } // for primitives public TypeFormat ArrayTypeFormat { get; set; } // for primitives public string Ref { get; set; } // for references public string Name { get; set; } public string Description { get; set; } public Schema ParentSchema { get; set; } //TODO: Composition and Polymorphism Support public ExternalDocumentation ExternalDocumentation { get; set; } public List Required { get; set; } public List Properties { get; set; } public void Serialize(JsonWriter writer) { if (TypeFormat.Type == ParameterType.Object) { // complex object if (!string.IsNullOrWhiteSpace(Description)) { writer.WritePropertyName("description"); writer.WriteValue(Description); } if (ParentSchema != null) { writer.WritePropertyName("allOf"); writer.WriteStartArray(); writer.WritePropertyName("$ref"); writer.WriteValue(string.Format("#/definitions/{0}", ParentSchema.Name)); writer.WriteStartObject(); } SerializeRequired(writer); SerializeExternalDocs(writer); SerializeProperties(writer); if (ParentSchema != null) { writer.WriteEndObject(); writer.WriteEndArray(); } } if (TypeFormat.Type != ParameterType.Unknown) { writer.WritePropertyName("type"); writer.WriteValue(TypeFormat.Type.ToString().ToLower()); if (!string.IsNullOrWhiteSpace(TypeFormat.Format)) { writer.WritePropertyName("format"); writer.WriteValue(TypeFormat.Format); } if (TypeFormat.Type == ParameterType.Array) { writer.WritePropertyName("items"); writer.WriteStartObject(); if (ArrayTypeFormat.IsPrimitiveType) { writer.WritePropertyName("type"); writer.WriteValue(ArrayTypeFormat.Type.ToString().ToLower()); if (!string.IsNullOrWhiteSpace(ArrayTypeFormat.Format)) { writer.WritePropertyName("format"); writer.WriteValue(ArrayTypeFormat.Format); } } else { writer.WritePropertyName("$ref"); writer.WriteValue(string.Format("#/definitions/{0}", Ref)); } writer.WriteEndObject(); } } else if (!string.IsNullOrWhiteSpace(Ref)) { writer.WritePropertyName("$ref"); writer.WriteValue(string.Format("#/definitions/{0}", Ref)); } } private void SerializeRequired(JsonWriter writer) { if (Required != null && Required.Any()) { writer.WritePropertyName("required"); writer.WriteStartArray(); foreach (string req in Required) { writer.WriteValue(req); } writer.WriteEndArray(); } } private void SerializeExternalDocs(JsonWriter writer) { if (ExternalDocumentation != null) { writer.WritePropertyName("externalDocs"); ExternalDocumentation.Serialize(writer); } } private void SerializeProperties(JsonWriter writer) { if (Properties != null && Properties.Any()) { writer.WritePropertyName("properties"); writer.WriteStartArray(); foreach (Property p in Properties) { p.Serialize(writer); } writer.WriteEndArray(); } } } } ================================================ FILE: src/SwaggerWcf/Models/SecurityAuthorization.cs ================================================ using System.Collections.Generic; using Newtonsoft.Json; namespace SwaggerWcf.Models { public class SecurityAuthorization { /// /// (Required) The type of the security scheme. Valid values are "basic", "apiKey" or "oauth2". /// public string Type { get; set; } /// /// A short description for security scheme. /// public string Description { get; set; } /// /// (Required) The name of the header or query parameter to be used. /// WARNING: Use only, when equals "apiKey" /// public string Name { get; set; } /// /// (Required) The location of the API key. Valid values are "query" or "header". /// WARNING: Use only, when equals "apiKey" /// public string In { get; set; } /// /// (Required) The flow used by the OAuth2 security scheme. Valid values are "implicit", "password", "application" or "accessCode". /// WARNING: Use only, when equals "oauth2" /// public string Flow { get; set; } /// /// (Required) The authorization URL to be used for this flow. This SHOULD be in the form of a URL. /// WARNING: Use only, when equals "oauth2" and equals "implicit" or "accessCode" /// public string AuthorizationUrl { get; set; } /// /// (Required) The token URL to be used for this flow. This SHOULD be in the form of a URL. /// WARNING: Use only, when equals "oauth2" and equals "password" or "application" or "accessCode" /// public string TokenUrl { get; set; } /// /// (Required) The available scopes for the OAuth2 security scheme. /// This maps between a name of a scope to a short description of it (as the value of the property). /// WARNING: Use only, when equals "oauth2" /// public Dictionary Scopes { get; set; } public void Serialize(JsonWriter writer) { writer.WriteStartObject(); if (Type != null) { writer.WritePropertyName("type"); writer.WriteValue(Type); } if (Description != null) { writer.WritePropertyName("description"); writer.WriteValue(Description); } if (Name != null) { writer.WritePropertyName("name"); writer.WriteValue(Name); } if (In != null) { writer.WritePropertyName("in"); writer.WriteValue(In); } if (Flow != null) { writer.WritePropertyName("flow"); writer.WriteValue(Flow); } if (AuthorizationUrl != null) { writer.WritePropertyName("authorizationUrl"); writer.WriteValue(AuthorizationUrl); } if (TokenUrl != null) { writer.WritePropertyName("tokenUrl"); writer.WriteValue(TokenUrl); } if (Scopes != null) { writer.WritePropertyName("scopes"); writer.WriteStartObject(); foreach (var scope in Scopes) { writer.WritePropertyName(scope.Key); writer.WriteValue(scope.Value); } writer.WriteEndObject(); } writer.WriteEndObject(); } } } ================================================ FILE: src/SwaggerWcf/Models/SecurityDefinitions.cs ================================================ using System.Collections.Generic; namespace SwaggerWcf.Models { public class SecurityDefinitions : Dictionary { //This is just a wrapper } } ================================================ FILE: src/SwaggerWcf/Models/Service.cs ================================================ using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace SwaggerWcf.Models { internal sealed class Service { public Service() { Swagger = "2.0"; Paths = new List(); Definitions = new List(); } public string Swagger { get; set; } public Info Info { get; set; } public string Host { get; set; } public string BasePath { get; set; } public List Schemes { get; set; } public List Paths { get; set; } public List Definitions { get; set; } public SecurityDefinitions SecurityDefinitions { get; set; } public void Serialize(JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("swagger"); writer.WriteValue(Swagger); if (Info != null) { writer.WritePropertyName("info"); Info.Serialize(writer); } if (Host != null) { writer.WritePropertyName("host"); writer.WriteValue(Host); } if (BasePath != null) { writer.WritePropertyName("basePath"); writer.WriteValue(BasePath); } if (Schemes != null && Schemes.Any()) { writer.WritePropertyName("schemes"); writer.WriteStartArray(); foreach (string sch in Schemes) { writer.WriteValue(sch); } writer.WriteEndArray(); } if (Paths != null && Paths.Any()) { writer.WritePropertyName("paths"); WritePaths(writer); } if (Definitions != null && Definitions.Any()) { writer.WritePropertyName("definitions"); WriteDefinitions(writer); } if (SecurityDefinitions != null && SecurityDefinitions.Any()) { writer.WritePropertyName("securityDefinitions"); WriteSecurityDefinitions(writer); } writer.WriteEndObject(); } private void WritePaths(JsonWriter writer) { writer.WriteStartObject(); foreach (Path p in Paths.OrderBy(p => p.Id)) { p.Serialize(writer); } writer.WriteEndObject(); } private void WriteDefinitions(JsonWriter writer) { writer.WriteStartObject(); foreach (Definition d in Definitions.OrderBy(d => d.Schema.Name)) { d.Serialize(writer); } writer.WriteEndObject(); } private void WriteSecurityDefinitions(JsonWriter writer) { writer.WriteStartObject(); foreach (var d in SecurityDefinitions) { writer.WritePropertyName(d.Key); d.Value.Serialize(writer); } writer.WriteEndObject(); } } } ================================================ FILE: src/SwaggerWcf/Models/TypeFormat.cs ================================================ namespace SwaggerWcf.Models { public struct TypeFormat { public ParameterType Type; public string Format; public TypeFormat(ParameterType type, string format) { Type = type; Format = format; } internal bool IsPrimitiveType => Type == ParameterType.Boolean || Type == ParameterType.Integer || Type == ParameterType.Number || Type == ParameterType.String && !string.Equals(Format, "stream"); // possible that enum should be included in primitive type? internal bool IsEnum => Type == ParameterType.Integer && Format == "enum"; } } ================================================ FILE: src/SwaggerWcf/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SwaggerWcf")] [assembly: AssemblyDescription("Swagger for WCF")] [assembly: AssemblyCompany("abelsilva")] [assembly: AssemblyProduct("SwaggerWcf")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d2eeaa63-60e5-4fda-8b62-e05dc8be8b5f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.2.15")] [assembly: AssemblyFileVersion("0.2.15")] [assembly: AssemblyInformationalVersion("0.2.15")] ================================================ FILE: src/SwaggerWcf/Support/DefinitionsBuilder.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using SwaggerWcf.Attributes; using SwaggerWcf.Models; namespace SwaggerWcf.Support { internal sealed class DefinitionsBuilder { public static List Process(IList hiddenTags, IList visibleTags, List definitionsTypes) { if (definitionsTypes == null || !definitionsTypes.Any()) return new List(0); List definitions = new List(); List processedTypes = new List(); Stack typesStack = new Stack(definitionsTypes.GroupBy(t => t.FullName).Select(grp => grp.First())); while (typesStack.Any()) { Type t = typesStack.Pop(); if (IsHidden(t, hiddenTags, visibleTags) || processedTypes.Contains(t)) continue; processedTypes.Add(t); Definition definition = ConvertTypeToDefinition(t, hiddenTags, typesStack); if (definition != null) definitions.Add(definition); } return definitions; } private static bool IsHidden(Type type, ICollection hiddenTags, ICollection visibleTags) { if (hiddenTags.Contains(type.FullName)) return true; if (type.GetCustomAttribute() != null) { return !type.GetCustomAttributes().Select(t => t.TagName).Any(visibleTags.Contains); } return type.GetCustomAttributes().Select(t => t.TagName).Any(hiddenTags.Contains); } private static Definition ConvertTypeToDefinition(Type definitionType, IList hiddenTags, Stack typesStack) { DefinitionSchema schema = new DefinitionSchema { Name = definitionType.GetModelName() }; ProcessTypeAttributes(definitionType, schema); // process schema.TypeFormat = Helpers.MapSwaggerType(definitionType, null); if (schema.TypeFormat.IsPrimitiveType) return null; if (schema.TypeFormat.Type == ParameterType.Integer && schema.TypeFormat.Format == "enum") { schema.Enum = new List(); Type propType = definitionType; if (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(Nullable<>)) propType = propType.GetEnumerableType(); List listOfEnumNames = propType.GetEnumNames().ToList(); foreach (string enumName in listOfEnumNames) { schema.Enum.Add(GetEnumMemberValue(propType, enumName)); } } else if (schema.TypeFormat.Type == ParameterType.Array) { Type t = GetEnumerableType(definitionType); if (t != null) { schema.Ref = definitionType.GetModelName(); typesStack.Push(t); } } else { schema.Properties = new List(); TypePropertiesProcessor.ProcessProperties(definitionType, schema, hiddenTags, typesStack); TypeFieldsProcessor.ProcessFields(definitionType, schema, hiddenTags, typesStack); } return new Definition { Schema = schema }; } private static void ProcessTypeAttributes(Type definitionType, DefinitionSchema schema) { DescriptionAttribute descAttr = definitionType.GetCustomAttribute(); if (descAttr != null) schema.Description = descAttr.Description; SwaggerWcfDefinitionAttribute definitionAttr = definitionType.GetCustomAttribute(); if (definitionAttr != null) { if (!string.IsNullOrWhiteSpace(definitionAttr.ExternalDocsDescription) || !string.IsNullOrWhiteSpace(definitionAttr.ExternalDocsUrl)) { schema.ExternalDocumentation = new ExternalDocumentation { Description = definitionAttr.ExternalDocsDescription, Url = definitionAttr.ExternalDocsUrl }; } if (!string.IsNullOrWhiteSpace(definitionAttr.ModelName)) schema.Name = definitionAttr.ModelName; } } public static Type GetEnumerableType(Type type) { if (type == null) return null; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>)) return type.GetGenericArguments()[0]; Type iface = (from i in type.GetInterfaces() where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>) select i).FirstOrDefault(); return iface == null ? null : GetEnumerableType(iface); } private static T LastValidValue(IEnumerable attrs, Func getter) { return attrs.Select(getter).LastOrDefault(x => x != null); } private static void ApplyIfValid(T opt, Action setter) { if (opt != null) { setter(opt); } } public static void ApplyAttributeOptions(PropertyInfo propertyInfo, DefinitionProperty prop) { // Use the DataContract [DefaultValue] as the default, by default var defAttr = propertyInfo.GetCustomAttributes().LastOrDefault(); if (defAttr != null) { prop.Default = defAttr.Value.ToString(); } // Apply any [SwaggerWcfProperty]s in order. var attrs = propertyInfo.GetCustomAttributes().ToList(); if (!attrs.Any()) { return; } ApplyAttributeOptions(attrs, prop); } public static void ApplyAttributeOptions(FieldInfo fieldInfo, DefinitionProperty prop) { // Use the DataContract [DefaultValue] as the default, by default var defAttr = fieldInfo.GetCustomAttributes().LastOrDefault(); if (defAttr != null) { prop.Default = defAttr.Value.ToString(); } // Apply any [SwaggerWcfProperty]s in order. var attrs = fieldInfo.GetCustomAttributes().ToList(); if (!attrs.Any()) { return; } ApplyAttributeOptions(attrs, prop); } public static void ApplyAttributeOptions(IEnumerable attrs, DefinitionProperty prop) { ApplyIfValid(LastValidValue(attrs, a => a.Title), x => prop.Title = x); ApplyIfValid(LastValidValue(attrs, a => a.Description), x => prop.Description = x); ApplyIfValid(LastValidValue(attrs, a => a._Required), x => prop.Required = x.Value); //ApplyIfValid(LastValidValue(attrs, a => a._AllowEmptyValue), x => prop.AllowEmptyValue = x.Value); //ApplyIfValid(LastValidValue(attrs, a => a._CollectionFormat), x => prop.CollectionFormat = x.Value); ApplyIfValid(LastValidValue(attrs, a => a.Default), x => prop.Default = x); ApplyIfValid(LastValidValue(attrs, a => a.Example), x => prop.Example = x); ApplyIfValid(LastValidValue(attrs, a => a._Maximum), x => prop.Maximum = x.Value); ApplyIfValid(LastValidValue(attrs, a => a._ExclusiveMaximum), x => prop.ExclusiveMaximum = x.Value); ApplyIfValid(LastValidValue(attrs, a => a._Minimum), x => prop.Minimum = x.Value); ApplyIfValid(LastValidValue(attrs, a => a._ExclusiveMinimum), x => prop.ExclusiveMinimum = x.Value); ApplyIfValid(LastValidValue(attrs, a => a._MaxLength), x => prop.MaxLength = x.Value); ApplyIfValid(LastValidValue(attrs, a => a._MinLength), x => prop.MinLength = x.Value); ApplyIfValid(LastValidValue(attrs, a => a.Pattern), x => prop.Pattern = x); ApplyIfValid(LastValidValue(attrs, a => a._MaxItems), x => prop.MaxItems = x.Value); ApplyIfValid(LastValidValue(attrs, a => a._MinItems), x => prop.MinItems = x.Value); ApplyIfValid(LastValidValue(attrs, a => a._UniqueItems), x => prop.UniqueItems = x.Value); ApplyIfValid(LastValidValue(attrs, a => a._MultipleOf), x => prop.MultipleOf = x.Value); } public static int GetEnumMemberValue(Type enumType, string enumName) { if (string.IsNullOrWhiteSpace(enumName)) return 0; var enumVal = Enum.Parse(enumType, enumName, true); var underlyingType = Enum.GetUnderlyingType(enumType); var val = Convert.ChangeType(enumVal, underlyingType); return Convert.ToInt32(val); } public static string GetEnumDescription(Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes.Length > 0) { return attributes[0].Description; } return ""; } } } ================================================ FILE: src/SwaggerWcf/Support/EnumerableExtensions.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SwaggerWcf.Support { public static class EnumerableExtensions { public static IEnumerable FilterUnique(this IEnumerable list) { return list.GroupBy(e => e).Select(g => g.Key); } } } ================================================ FILE: src/SwaggerWcf/Support/Helpers.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Web; using SwaggerWcf.Configuration; using SwaggerWcf.Models; namespace SwaggerWcf.Support { internal static class Helpers { public static TypeFormat MapSwaggerType(Type type, IList definitions = null) { //built-in types if (type == typeof(bool)) { return new TypeFormat(ParameterType.Boolean, null); } if (type == typeof(byte)) { return new TypeFormat(ParameterType.String, "byte"); } if (type == typeof(sbyte)) { return new TypeFormat(ParameterType.String, "sbyte"); } if (type == typeof(char)) { return new TypeFormat(ParameterType.String, "char"); } if (type == typeof(decimal)) { return new TypeFormat(ParameterType.Number, "decimal"); } if (type == typeof(double)) { return new TypeFormat(ParameterType.Number, "double"); } if (type == typeof(float)) { return new TypeFormat(ParameterType.Number, "float"); } if (type == typeof(int)) { return new TypeFormat(ParameterType.Integer, "int32"); } if (type == typeof(uint)) { return new TypeFormat(ParameterType.Number, "uint32"); } if (type == typeof(long)) { return new TypeFormat(ParameterType.Integer, "int64"); } if (type == typeof(ulong)) { return new TypeFormat(ParameterType.Integer, "uint64"); } if (type == typeof(short)) { return new TypeFormat(ParameterType.Integer, "int16"); } if (type == typeof(ushort)) { return new TypeFormat(ParameterType.Integer, "uint16"); } if (type == typeof(string)) { return new TypeFormat(ParameterType.String, null); } if (type == typeof(DateTime)) { return new TypeFormat(ParameterType.String, "date-time"); } if (type == typeof(DateTimeOffset)) { return new TypeFormat(ParameterType.String, "date-time"); } if (type == typeof(Guid)) { return new TypeFormat(ParameterType.String, "guid"); } if (type == typeof(Stream)) { return new TypeFormat(ParameterType.String, "stream"); } if (type == typeof(void)) { return new TypeFormat(ParameterType.Void, null); } //it's an enum, use string as the property type and enum values will be serialized later if (type.IsEnum) { return new TypeFormat(ParameterType.Integer, "enum"); } //it's a collection/array, so it will use the swagger "container" syntax if (type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>))) { return new TypeFormat(ParameterType.Array, null); } //it's a collection/array, so it will use the swagger "container" syntax if (type.GetInterfaces().Any(i => i == typeof(System.Collections.IEnumerable))) { return new TypeFormat(ParameterType.Array, null); } //it's a Nullable so treat it as T - we'll handle making it not-required later if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { return MapSwaggerType(type.GenericTypeArguments[0], definitions); } //it's a complex type, so we'll need to map it later if (definitions != null && !definitions.Contains(type)) { definitions.Add(type); } return new TypeFormat(ParameterType.Object, HttpUtility.HtmlEncode(type.GetModelName())); } private static string BuildTypeString(string typeName, string defaultNote = null, string typeNote = null) { const string resultFormat = "{0}({1})"; if (string.IsNullOrEmpty(defaultNote) && string.IsNullOrEmpty(typeNote)) { return typeName; } return string.IsNullOrEmpty(typeNote) ? string.Format(resultFormat, typeName, defaultNote) : string.Format(resultFormat, typeName, typeNote); } public static T1 GetCustomAttributeValue(MethodInfo method, string propertyName) where T1 : class where T2 : Attribute { var attr = method.GetCustomAttribute(); if (attr == null) { return null; } PropertyInfo prop = typeof(T2).GetProperty(propertyName); if (prop == null || prop.PropertyType != typeof(T1)) { return null; } return prop.GetValue(attr) as T1; } public static bool GetCustomAttributeValue(MethodInfo method, string propertyName, bool defaultVal = false) where T : Attribute { var attr = method.GetCustomAttribute(); if (attr == null) { return defaultVal; } PropertyInfo prop = typeof(T).GetProperty(propertyName); if (prop == null || prop.PropertyType != typeof(bool)) { return defaultVal; } return (bool)prop.GetValue(attr); } internal static TypeFormat MapElementType(Type type, List definitions) { Type enumType = type.GetInterfaces() .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>)); if (enumType == null) { throw new ArgumentException("Type must be an IEnumerable."); } Type elementType = enumType.GetGenericArguments().First(); return MapSwaggerType(elementType, definitions); } internal static bool TagIsHidden(this Dictionary tagConfigurations, IEnumerable itemTags) { return tagConfigurations.Values.Any(t => t.Visibile.Equals(false) && itemTags.Contains(t.Name)); } } } ================================================ FILE: src/SwaggerWcf/Support/ListExtensions.cs ================================================ using System; using System.Collections.Generic; namespace SwaggerWcf.Support { public static class ListExtensions { public static string ClosestMatch(this List list, string value) { int matchValue = int.MaxValue; string result = null; foreach (string s in list) { int val = Compute(s, value); if (val > matchValue) continue; matchValue = val; result = s; } return result; } // from https://stackoverflow.com/a/13793600/4309405 /// /// Compute the distance between two strings. /// private static int Compute(string s, string t) { int n = s.Length; int m = t.Length; int[,] d = new int[n + 1, m + 1]; // Step 1 if (n == 0) return m; if (m == 0) return n; // Step 2 for (int i = 0; i <= n; d[i, 0] = i++) { } for (int j = 0; j <= m; d[0, j] = j++) { } // Step 3 for (int i = 1; i <= n; i++) { //Step 4 for (int j = 1; j <= m; j++) { // Step 5 int cost = (t[j - 1] == s[i - 1]) ? 0 : 1; // Step 6 d[i, j] = Math.Min(Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost); } } // Step 7 return d[n, m]; } } } ================================================ FILE: src/SwaggerWcf/Support/Mapper.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Web; using SwaggerWcf.Attributes; using SwaggerWcf.Models; namespace SwaggerWcf.Support { internal class Mapper { internal Mapper(IList hiddenTags, List visibleTags) { HiddenTags = hiddenTags ?? new List(); VisibleTags = visibleTags ?? new List(); } internal readonly IEnumerable HiddenTags; internal readonly IEnumerable VisibleTags; internal IEnumerable FindMethods(Type markedType, IList definitionsTypesList, string basePath = null) { List paths = new List(); List> pathActions = new List>(); List types; Type serviceType; if (markedType.IsInterface) { //search for service impl type var allTypes = AppDomain.CurrentDomain .GetAssemblies() .SelectMany(s => s.GetTypes()) .Where(type => markedType.IsAssignableFrom(type) && !type.IsInterface) .ToList(); serviceType = allTypes.Except(allTypes.Select(type => type.BaseType)).Single(); types = new List { markedType }; } else { serviceType = markedType; //search all interfaces for this type for potential DataContracts, and build a set of items types = serviceType.GetInterfaces().ToList(); types.Add(serviceType); } foreach (Type i in types) { Attribute dc = i.GetCustomAttribute(typeof(ServiceContractAttribute)); if (dc == null) continue; //found a DataContract, now get a service map and inspect the methods for WebGet/WebInvoke if (i.IsInterface) { InterfaceMapping map = serviceType.GetInterfaceMap(i); pathActions.AddRange(GetActions(map.TargetMethods, map.InterfaceMethods, definitionsTypesList)); //Nested Interface var baseInterfaces = i.GetInterfaces(); if (baseInterfaces != null) { foreach (var baseInterface in baseInterfaces) { var _map = serviceType.GetInterfaceMap(baseInterface); pathActions.AddRange(GetActions(_map.TargetMethods, _map.InterfaceMethods, definitionsTypesList)); } } } else { pathActions.AddRange(GetActions(i.GetMethods(), i.GetMethods(), definitionsTypesList)); } } foreach (var pathAction in pathActions) { var path = pathAction.Item1; if (!path.StartsWith("/")) path = "/" + path; if (string.IsNullOrWhiteSpace(basePath) == false) path = basePath + path; GetPath(path, paths).Actions.Add(pathAction.Item2); } return paths; } private Path GetPath(string id, List paths) { var path = paths.FirstOrDefault(p => p.Id == id); if (path == null) { path = new Path { Id = id, Actions = new List() }; paths.Add(path); } return path; } private static string ConcatPaths(string basePath, string pathUrl) { string path = basePath; if (basePath.EndsWith("/") && pathUrl.StartsWith("/")) path += pathUrl.Substring(1); else if (!basePath.EndsWith("/") && !string.IsNullOrWhiteSpace(pathUrl) && !pathUrl.StartsWith("/")) path += "/" + pathUrl; else path += pathUrl; return path; } internal IEnumerable> GetActions(MethodInfo[] targetMethods, MethodInfo[] interfaceMethods, IList definitionsTypesList) { int methodsCounts = interfaceMethods.Count(); for (int index = 0; index < methodsCounts; index++) { MethodInfo implementation = targetMethods[index]; MethodInfo declaration = interfaceMethods[index]; //if a tag from either implementation or declaration is marked as not visible, skip it List methodTags = implementation.GetCustomAttributes().ToList(); methodTags = methodTags.Concat(declaration.GetCustomAttributes()).ToList(); methodTags = methodTags.Distinct().ToList(); if (methodTags.Select(t => t.TagName).Any(HiddenTags.Contains)) continue; //if the method is marked Hidden anywhere, skip it if ((implementation.GetCustomAttribute() != null || declaration.GetCustomAttribute() != null) && !methodTags.Select(t => t.TagName).Any(VisibleTags.Contains)) continue; //find the WebGet/Invoke attributes, or skip if neither is present WebGetAttribute wg = declaration.GetCustomAttribute(); WebInvokeAttribute wi = declaration.GetCustomAttribute(); if (wg == null && wi == null) continue; string httpMethod = (wi == null) ? "GET" : wi.Method ?? "POST"; string uriTemplate = GetUriTemplate(wi, wg, declaration); bool wrappedRequest = IsRequestWrapped(wg, wi); bool wrappedResponse = IsResponseWrapped(wg, wi); //implementation description overrides interface description string description = Helpers.GetCustomAttributeValue(implementation, "Description") ?? Helpers.GetCustomAttributeValue(declaration, "Description") ?? Helpers.GetCustomAttributeValue(implementation, "Description") ?? Helpers.GetCustomAttributeValue(declaration, "Description") ?? ""; string summary = Helpers.GetCustomAttributeValue(implementation, "Summary") ?? Helpers.GetCustomAttributeValue(declaration, "Summary") ?? ""; string operationId = Helpers.GetCustomAttributeValue(implementation, "OperationId") ?? Helpers.GetCustomAttributeValue(declaration, "OperationId") ?? ""; if (operationId == "") { if (implementation.DeclaringType != null) operationId = implementation.DeclaringType.FullName + "."; operationId += implementation.Name; } string externalDocsDescription = Helpers.GetCustomAttributeValue(implementation, "ExternalDocsDescription") ?? Helpers.GetCustomAttributeValue(declaration, "ExternalDocsDescription") ?? ""; string externalDocsUrl = Helpers.GetCustomAttributeValue(implementation, "ExternalDocsUrl") ?? Helpers.GetCustomAttributeValue(declaration, "ExternalDocsUrl") ?? ""; ExternalDocumentation externalDocs = null; if (!string.IsNullOrWhiteSpace(externalDocsDescription) || !string.IsNullOrWhiteSpace(externalDocsUrl)) { externalDocs = new ExternalDocumentation { Description = externalDocsDescription, Url = HttpUtility.HtmlEncode(externalDocsUrl) }; } bool deprecated = Helpers.GetCustomAttributeValue(implementation, "Deprecated"); if (!deprecated) deprecated = Helpers.GetCustomAttributeValue(declaration, "Deprecated"); string operationPath = Helpers.GetCustomAttributeValue(implementation, "OperationPath") ?? Helpers.GetCustomAttributeValue(declaration, "OperationPath"); if (!string.IsNullOrWhiteSpace(operationPath)) { uriTemplate = ConcatPaths(operationPath, uriTemplate); } PathAction operation = new PathAction { Id = httpMethod.ToLowerInvariant(), Summary = summary, Description = description, Tags = methodTags.Where(t => !t.HideFromSpec).Select(t => HttpUtility.HtmlEncode(t.TagName)).ToList(), Consumes = new List(GetConsumes(implementation, declaration)), Produces = new List(GetProduces(implementation, declaration)), Deprecated = deprecated, OperationId = HttpUtility.HtmlEncode(operationId), ExternalDocs = externalDocs, Responses = GetResponseCodes(implementation, declaration, wrappedResponse, definitionsTypesList), Security = GetMethodSecurity(implementation, declaration) // Schemes = TODO: how to get available schemes for this WCF service? (schemes: http/https) }; //try to map each implementation parameter to the uriTemplate. ParameterInfo[] parameters = declaration.GetParameters(); if (parameters.Any()) operation.Parameters = new List(); List headers = implementation.GetCustomAttributes().ToList(); headers = headers.Concat(declaration.GetCustomAttributes()).ToList(); // remove duplicates headers = headers.GroupBy(h => h.Name).Select(g => g.First()).ToList(); // parameters - headers foreach (SwaggerWcfHeaderAttribute attr in headers) { operation.Parameters.Add(new ParameterPrimitive { Name = attr.Name, Description = attr.Description, Default = attr.DefaultValue, In = InType.Header, Required = attr.Required, TypeFormat = new TypeFormat(ParameterType.String, null) }); } bool isGetRequest = httpMethod == "GET"; int bodyParameterCount = parameters.Where(p => GetInType(uriTemplate, p.Name) == InType.Body).Count(); TypeBuilder typeBuilder = null; if (!wrappedRequest && !isGetRequest && bodyParameterCount > 1) { wrappedRequest = true; } if (wrappedRequest) { typeBuilder = new TypeBuilder(implementation.GetWrappedName(declaration)); } var declarationName = declaration.Name; foreach (ParameterInfo parameter in parameters) { SwaggerWcfParameterAttribute settings = implementation.GetParameters() .First(p => p.Position.Equals(parameter.Position)) .GetCustomAttribute() ?? parameter.GetCustomAttribute(); if (implementation.GetParameters() .First(p => p.Position.Equals(parameter.Position)) .GetCustomAttribute() != null || parameter.GetCustomAttribute() != null) continue; List piTags = methodTags.Concat(parameter.GetCustomAttributes()) .ToList(); InType inType = GetInType(uriTemplate, parameter.Name); if (inType == InType.Body && wrappedRequest) { bool required = settings != null && settings.Required; if (!required && !parameter.HasDefaultValue) required = true; typeBuilder.AddField(parameter.Name, parameter.ParameterType, required); continue; } if (piTags.Select(t => t.TagName).Any(HiddenTags.Contains)) continue; Type type = settings == null || settings.ParameterType == null ? parameter.ParameterType : settings.ParameterType; TypeFormat typeFormat = Helpers.MapSwaggerType(type, definitionsTypesList); operation.Parameters.Add(GetParameter(typeFormat, declaration, implementation, parameter, settings, uriTemplate, wrappedRequest, definitionsTypesList, inType)); } if (wrappedRequest) { TypeFormat typeFormat = Helpers.MapSwaggerType(typeBuilder.Type, definitionsTypesList); operation.Parameters.Add(new ParameterSchema { Name = implementation.GetWrappedName(declaration) + "Wrapper", In = InType.Body, Required = true, SchemaRef = typeFormat.Format }); } if (!string.IsNullOrWhiteSpace(uriTemplate)) { int indexOfQuestionMark = uriTemplate.IndexOf('?'); if (indexOfQuestionMark >= 0) uriTemplate = uriTemplate.Substring(0, indexOfQuestionMark); uriTemplate = RemoveParametersDefaultValuesFromUri(uriTemplate); } yield return new Tuple(uriTemplate, operation); } } private string GetUriTemplate(WebInvokeAttribute wi, WebGetAttribute wg, MethodInfo declaration) { return ((wi == null) ? wg.UriTemplate : wi.UriTemplate) ?? declaration.Name; } private string RemoveParametersDefaultValuesFromUri(string uriTemplate) { Regex regWithDefaultValue = new Regex(@"\{[a-zA-Z0-9_]+(=[a-zA-Z0-9_]+)\}"); if (!regWithDefaultValue.Match(uriTemplate).Success) return uriTemplate; string res = uriTemplate; int currIndex = 0; Match match; while ((match = regWithDefaultValue.Match(res)).Success) { res = res.Substring(currIndex, match.Groups[1].Index) + res.Substring(match.Groups[1].Index + match.Groups[1].Length); } return res; } private static bool IsRequestWrapped(WebGetAttribute wg, WebInvokeAttribute wi) { return (wg != null) && (wg.BodyStyle == WebMessageBodyStyle.Wrapped || wg.BodyStyle == WebMessageBodyStyle.WrappedRequest) || (wi != null) && (wi.BodyStyle == WebMessageBodyStyle.Wrapped || wi.BodyStyle == WebMessageBodyStyle.WrappedRequest); } private static bool IsResponseWrapped(WebGetAttribute wg, WebInvokeAttribute wi) { return (wg != null) && (wg.BodyStyle == WebMessageBodyStyle.Wrapped || wg.BodyStyle == WebMessageBodyStyle.WrappedResponse) || (wi != null) && (wi.BodyStyle == WebMessageBodyStyle.Wrapped || wi.BodyStyle == WebMessageBodyStyle.WrappedResponse); } private ParameterBase GetParameter(TypeFormat typeFormat, MethodInfo declaration, MethodInfo implementation, ParameterInfo parameter, SwaggerWcfParameterAttribute settings, string uriTemplate, bool wrappedRequest, IList definitionsTypesList, InType inType) { string description = settings?.Description; bool required = settings != null && settings.Required; string name = inType == InType.Query ? ResolveParameterNameFromUri(uriTemplate, parameter) : parameter.Name; if (inType == InType.Path) required = true; if (!required && !parameter.HasDefaultValue) required = true; Type paramType = settings == null || settings.ParameterType == null ? parameter.ParameterType : settings.ParameterType; if (paramType.IsGenericType && paramType.GetGenericTypeDefinition() == typeof(Nullable<>)) { required = false; paramType = paramType.GenericTypeArguments[0]; } if (typeFormat.Type == ParameterType.Object) { return new ParameterSchema { Name = name, Description = description, In = inType, Required = required, SchemaRef = typeFormat.Format }; } if (inType == InType.Body) { if (typeFormat.Type == ParameterType.Array) { Type t = paramType.GetElementType() ?? GetEnumerableType(paramType); TypeFormat subTypeFormat = Helpers.MapSwaggerType(t); ParameterItems items; if (subTypeFormat.IsPrimitiveType || subTypeFormat.IsEnum) { items = new ParameterItems { TypeFormat = subTypeFormat }; } else { items = new ParameterItems { Items = new ParameterSchema { SchemaRef = t.GetModelName() } }; } ParameterPrimitive arrayParam = new ParameterPrimitive { Name = name, Description = description, In = inType, Required = required, TypeFormat = typeFormat, Items = items, CollectionFormat = CollectionFormat.Csv }; //it's a complex type, so we'll need to map it later if (definitionsTypesList != null && !definitionsTypesList.Contains(t)) { definitionsTypesList.Add(t); } return arrayParam; } if (typeFormat.IsPrimitiveType || typeFormat.IsEnum) { bool isGetRequest = implementation.GetCustomAttributes().Any() || declaration.GetCustomAttributes().Any(); if (!isGetRequest) { WebInvokeAttribute webInvoke = implementation.GetCustomAttribute() ?? declaration.GetCustomAttribute(); if (webInvoke != null && webInvoke.Method == "GET") isGetRequest = true; } if (!wrappedRequest && isGetRequest) { ParameterPrimitive paramPrimitive = new ParameterPrimitive { Name = name, Description = description, In = InType.Query, Required = required, TypeFormat = typeFormat }; return paramPrimitive; } else { ParameterPrimitive paramPrimitive = new ParameterPrimitive { Name = name, Description = description, In = inType, Required = required, TypeFormat = typeFormat }; return paramPrimitive; } } //it's a complex type, so we'll need to map it later if (definitionsTypesList != null && !definitionsTypesList.Contains(paramType)) { definitionsTypesList.Add(paramType); } typeFormat = new TypeFormat(ParameterType.Object, HttpUtility.HtmlEncode(paramType.GetModelName())); return new ParameterSchema { Name = name, Description = description, In = inType, Required = required, SchemaRef = typeFormat.Format }; } ParameterPrimitive param = new ParameterPrimitive { Name = name, Description = description, In = inType, Required = required, TypeFormat = typeFormat }; return param; } private static string ResolveParameterNameFromUri(string uriTemplate, ParameterInfo parameter) { int questionMarkPosition = uriTemplate.IndexOf("?", StringComparison.Ordinal); var uriParameters = HttpUtility.ParseQueryString(uriTemplate.Substring(questionMarkPosition + 1)); string parameterTemplate = GetParameterNameTemplate(parameter.Name); var resolvedParameter = uriParameters .AllKeys .Select(k => new { Name = k, Template = uriParameters.Get(k) }) .FirstOrDefault(p => p.Template.Equals(parameterTemplate, StringComparison.Ordinal)); return resolvedParameter != null ? resolvedParameter.Name : parameter.Name; } private static string GetParameterNameTemplate(string parameterName) { return $"{{{parameterName}}}"; } private InType GetInType(string uriTemplate, string parameterName) { Match match = new Regex(GetParameterNameTemplate(parameterName)).Match(uriTemplate); if (!match.Success) return InType.Body; int questionMarkPosition = uriTemplate.IndexOf("?", StringComparison.Ordinal); if (questionMarkPosition == -1) return InType.Path; return questionMarkPosition > match.Index ? InType.Path : InType.Query; } private IEnumerable GetConsumes(MethodInfo implementation, MethodInfo declaration) { string[] overrides = implementation .GetCustomAttributes() .Concat(declaration.GetCustomAttributes()) .Select(attr => attr.ConsumeTypes) .FirstOrDefault(types => types != null && types.Length > 0); if (overrides != null) { return overrides; } List contentTypes = new List(); if (declaration.GetCustomAttributes().Any(a => a.IsRequestFormatSetExplicitly)) { contentTypes.AddRange( declaration.GetCustomAttributes() .Select(a => ConvertWebMessageFormatToContentType(a.RequestFormat))); } else if (declaration.GetCustomAttributes().Any(a => a.IsRequestFormatSetExplicitly)) { contentTypes.AddRange( declaration.GetCustomAttributes() .Select(a => ConvertWebMessageFormatToContentType(a.RequestFormat))); } if (!contentTypes.Any()) contentTypes.AddRange(new[] { "application/json", "application/xml" }); return contentTypes; } private IEnumerable GetProduces(MethodInfo implementation, MethodInfo declaration) { string[] overrides = implementation.GetCustomAttributes() .Concat(declaration.GetCustomAttributes()) .Select(attr => attr.ProduceTypes) .FirstOrDefault(types => types != null && types.Length > 0); if (overrides != null) { return overrides; } List contentTypes = new List(); if (declaration.GetCustomAttributes().Any(a => a.IsResponseFormatSetExplicitly)) { contentTypes.AddRange( declaration.GetCustomAttributes() .Select(a => ConvertWebMessageFormatToContentType(a.ResponseFormat))); } else if (declaration.GetCustomAttributes().Any(a => a.IsResponseFormatSetExplicitly)) { contentTypes.AddRange( declaration.GetCustomAttributes() .Select(a => ConvertWebMessageFormatToContentType(a.ResponseFormat))); } if (!contentTypes.Any()) contentTypes.AddRange(new[] { "application/json", "application/xml" }); return contentTypes; } private string ConvertWebMessageFormatToContentType(WebMessageFormat format) { switch (format) { case WebMessageFormat.Xml: return "application/xml"; case WebMessageFormat.Json: default: return "application/json"; } } private List GetResponseCodes(MethodInfo implementation, MethodInfo declaration, bool wrappedResponse, IList definitionsTypesList) { Type returnType = implementation.GetCustomAttributes() .Concat(declaration.GetCustomAttributes()) .Select(attr => attr.ReturnType) .FirstOrDefault() ?? declaration.ReturnType; if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Nullable<>)) returnType = returnType.GenericTypeArguments[0]; Schema schema = returnType.IsEnum ? BuildSchemaForEnum(returnType, definitionsTypesList) : BuildSchema(returnType, implementation, declaration, wrappedResponse, definitionsTypesList); List responses = implementation.GetCustomAttributes().ToList(); responses = responses.Concat(declaration.GetCustomAttributes()).FilterUnique().ToList(); List res = responses.Select(ra => ConvertResponse(ra, schema, implementation, declaration, wrappedResponse, definitionsTypesList)) .ToList(); if (!res.Any()) { res.Add(new Response { Code = "default", Schema = schema }); } return res; } private Response ConvertResponse(SwaggerWcfResponseAttribute ra, Schema schema, MethodInfo implementation, MethodInfo declaration, bool wrappedResponse, IList definitionsTypesList) { Schema s = schema; if (ra.EmptyResponseOverride) s = null; else if (ra.ResponseTypeOverride != null) s = BuildSchema(ra.ResponseTypeOverride, implementation, declaration, wrappedResponse, definitionsTypesList); else if (schema != null && schema.TypeFormat.Type == ParameterType.Array) { Type type = schema.Ref != null ? Type.GetType(schema.Ref) : null; if (type != null) { TypeFormat arrayTypeFormat = Helpers.MapSwaggerType(type); if (arrayTypeFormat.IsPrimitiveType) { schema.ArrayTypeFormat = arrayTypeFormat; } } } return new Response { Code = ra.Code, Description = ra.Description, Schema = s, Headers = (ra.Headers != null) ? ra.Headers.ToList() : null, Example = GetExample(ra) }; } private Example GetExample(SwaggerWcfResponseAttribute ra) { if (string.IsNullOrWhiteSpace(ra.ExampleContent)) return null; return new Example { MimeType = ra.ExampleMimeType, Content = ra.ExampleContent }; } private Schema BuildSchemaForEnum(Type returnType, IList definitionsTypesList) { //it's a complex type, so we'll need to map it later if (definitionsTypesList != null && !definitionsTypesList.Contains(returnType)) { definitionsTypesList.Add(returnType); } TypeFormat typeFormat = new TypeFormat(ParameterType.Unknown, null); return new Schema { TypeFormat = typeFormat, Ref = HttpUtility.HtmlEncode(returnType.GetModelName()) }; } private Schema BuildSchema(Type type, MethodInfo implementation, MethodInfo declaration, bool wrappedResponse, IList definitionsTypesList) { if (type == typeof(void) || type == typeof(Task)) return null; if (type.BaseType == typeof(Task)) type = GetTaskInnerType(type); TypeFormat typeFormat; if (wrappedResponse) { string funcName = implementation.Name; string typeName = implementation.GetCustomAttribute()?.Name ?? declaration.GetCustomAttribute()?.Name ?? funcName + "Result"; TypeBuilder typeBuilder = new TypeBuilder(typeName + "Wrapper"); typeBuilder.AddField(typeName, type, true); typeFormat = Helpers.MapSwaggerType(typeBuilder.Type, definitionsTypesList); } else { typeFormat = Helpers.MapSwaggerType(type, definitionsTypesList); } switch (typeFormat.Type) { case ParameterType.Object: return new Schema { Ref = typeFormat.Format }; case ParameterType.Array: Type t = type.GetElementType() ?? GetEnumerableType(type); if (t == null) return null; TypeFormat arrayTypeFormat = Helpers.MapSwaggerType(t); if (arrayTypeFormat.IsPrimitiveType) { return new Schema { TypeFormat = typeFormat, ArrayTypeFormat = arrayTypeFormat }; } else { definitionsTypesList.Add(t); return new Schema { TypeFormat = typeFormat, Ref = HttpUtility.HtmlEncode(t.GetModelName()) }; } default: definitionsTypesList.Add(type); return new Schema { TypeFormat = typeFormat }; } } private static object GetDefaultValue(Type type) { try { return Activator.CreateInstance(type); } catch (Exception) { return null; } } private static Type GetTaskInnerType(Type type) { if (type == null) return null; return type.BaseType == typeof(Task) ? type.GetGenericArguments()[0] : type; } private static List> GetMethodSecurity(MethodInfo implementation, MethodInfo declaration) { var securityMethodAttributes = implementation.GetCustomAttributes().ToList(); var securityInterfaceAttributes = declaration.GetCustomAttributes().ToList(); var securityAttributes = securityMethodAttributes.Concat(securityInterfaceAttributes).ToList(); if (securityAttributes.Any() == false) return null; var security = new List>(); foreach (var securityAttribute in securityAttributes) { security.Add(new KeyValuePair(securityAttribute.SecurityDefinitionName, securityAttribute.SecurityDefinitionScopes)); } return security; } public static Type GetEnumerableType(Type type) { if (type == null) return null; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>)) return type.GetGenericArguments()[0]; Type iface = (from i in type.GetInterfaces() where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>) select i).FirstOrDefault(); return iface == null ? null : GetEnumerableType(iface); } } } ================================================ FILE: src/SwaggerWcf/Support/MethodInfoExtensions.cs ================================================ using System; using System.Linq; using System.Reflection; using SwaggerWcf.Attributes; namespace SwaggerWcf.Support { public static class MethodInfoExtensions { public static string GetWrappedName(this MethodInfo implementation, MethodInfo declaration) { return implementation.GetCustomAttribute()?.Name ?? declaration.GetCustomAttribute()?.Name ?? (implementation.Name.Contains('.') ? implementation.Name.Substring(implementation.Name.LastIndexOf(".", StringComparison.Ordinal) + 1) : implementation.Name); } } } ================================================ FILE: src/SwaggerWcf/Support/Serializer.cs ================================================ using System.Collections.Generic; using System.IO; using System.Text; using Newtonsoft.Json; using SwaggerWcf.Models; namespace SwaggerWcf.Support { internal class Serializer { internal static string Process(Service service) { var sb = new StringBuilder(); var sw = new StringWriter(sb); using (JsonWriter writer = new JsonTextWriter(sw)) { service.Serialize(writer); } return sb.ToString(); } } } ================================================ FILE: src/SwaggerWcf/Support/ServiceBuilder.cs ================================================ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Reflection; using Newtonsoft.Json; using SwaggerWcf.Attributes; using SwaggerWcf.Configuration; using SwaggerWcf.Models; using SettingElement = SwaggerWcf.Configuration.SettingElement; namespace SwaggerWcf.Support { internal class ServiceBuilder { public static Service Build(string path) { return BuildServiceCommon(path, BuildPaths); } public static Service Build(string path) { return BuildServiceCommon(path, BuildPaths); } private static Service BuildServiceCommon(string path, Action, List, IList> buildPaths) { const string sectionName = "swaggerwcf"; SwaggerWcfSection config = (SwaggerWcfSection)(ConfigurationManager.GetSection(sectionName) ?? new SwaggerWcfSection()); List definitionsTypesList = new List(); Service service = new Service(); List hiddenTags = SwaggerWcfEndpoint.FilterHiddenTags(path, GetHiddenTags(config)); List visibleTags = SwaggerWcfEndpoint.FilterVisibleTags(path, GetVisibleTags(config)); IReadOnlyDictionary settings = GetSettings(config); ProcessSettings(service, settings); buildPaths(service, hiddenTags, visibleTags, definitionsTypesList); service.Definitions = DefinitionsBuilder.Process(hiddenTags, visibleTags, definitionsTypesList); return service; } private static List GetHiddenTags(SwaggerWcfSection config) { return config.Tags?.OfType() .Where(t => t.Visibile.Equals(false)) .Select(t => t.Name) .ToList() ?? new List(); } private static List GetVisibleTags(SwaggerWcfSection config) { return config.Tags?.OfType() .Where(t => t.Visibile.Equals(true)) .Select(t => t.Name) .ToList() ?? new List(); } private static IReadOnlyDictionary GetSettings(SwaggerWcfSection config) { return config.Settings?.OfType().ToDictionary(se => se.Name, se => se.Value) ?? new Dictionary(); } private static void ProcessSettings(Service service, IReadOnlyDictionary settings) { if (settings.ContainsKey("BasePath")) service.BasePath = settings["BasePath"]; if (settings.ContainsKey("Host")) service.Host = settings["Host"]; if (settings.ContainsKey("Schemes")) service.Schemes = settings["Schemes"].Split(';').ToList(); if (settings.Keys.Any(k => k.StartsWith("Info"))) service.Info = new Info(); if (settings.ContainsKey("InfoDescription")) service.Info.Description = settings["InfoDescription"]; if (settings.ContainsKey("InfoVersion")) service.Info.Version = settings["InfoVersion"]; if (settings.ContainsKey("InfoTermsOfService")) service.Info.TermsOfService = settings["InfoTermsOfService"]; if (settings.ContainsKey("InfoTitle")) service.Info.Title = settings["InfoTitle"]; if (settings.Keys.Any(k => k.StartsWith("InfoContact"))) service.Info.Contact = new InfoContact(); if (settings.ContainsKey("InfoContactName")) service.Info.Contact.Name = settings["InfoContactName"]; if (settings.ContainsKey("InfoContactUrl")) service.Info.Contact.Url = settings["InfoContactUrl"]; if (settings.ContainsKey("InfoContactEmail")) service.Info.Contact.Email = settings["InfoContactEmail"]; if (settings.Keys.Any(k => k.StartsWith("InfoLicense"))) service.Info.License = new InfoLicense(); if (settings.ContainsKey("InfoLicenseUrl")) service.Info.License.Url = settings["InfoLicenseUrl"]; if (settings.ContainsKey("InfoLicenseName")) service.Info.License.Name = settings["InfoLicenseName"]; } private static void BuildPaths(Service service, IList hiddenTags, List visibleTags, IList definitionsTypesList) { service.Paths = new List(); var types = GetAssemblyTypes(hiddenTags); var useBasePathProperty = types.Select(t => t.GetCustomAttribute().ServicePath) .Distinct() .Count() == 1; foreach (var ti in types) { var da = ti.GetCustomAttribute(); if (service.Info is null) service.Info = ti.GetServiceInfo(); var mapper = new Mapper(hiddenTags, visibleTags); if (string.IsNullOrWhiteSpace(service.BasePath) && useBasePathProperty) service.BasePath = da.ServicePath; if (service.BasePath != null && service.BasePath.EndsWith("/")) service.BasePath = service.BasePath.Substring(0, service.BasePath.Length - 1); string basePath = null; if (!useBasePathProperty) { basePath = da.ServicePath; if (basePath != null && basePath.EndsWith("/")) basePath = basePath.Substring(0, basePath.Length - 1); if (basePath != null && basePath.StartsWith("/") == false) basePath = "/" + basePath; } var paths = mapper.FindMethods(ti.AsType(), definitionsTypesList, basePath); service.Paths.AddRange(paths); } } private static IEnumerable GetAssemblyTypes(IList hiddenTags) { var assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var assembly in assemblies) { IEnumerable types; try { types = assembly.DefinedTypes; } catch (Exception) { // ignore assembly and continue continue; } foreach (TypeInfo ti in types) { var da = ti.GetCustomAttribute(); if (da == null || hiddenTags.Any(ht => ht == ti.AsType().Name)) continue; yield return ti; } } } private static void BuildPaths(Service service, IList hiddenTags, List visibleTags, IList definitionsTypesList) { var type = typeof(TBusiness); service.Paths = new List(); var da = type.GetCustomAttribute(); if (da == null || hiddenTags.Any(ht => ht == type.Name)) return; var mapper = new Mapper(hiddenTags, visibleTags); if (string.IsNullOrWhiteSpace(service.BasePath)) service.BasePath = da.ServicePath; if (service.BasePath.EndsWith("/")) service.BasePath = service.BasePath.Substring(0, service.BasePath.Length - 1); var paths = mapper.FindMethods(type, definitionsTypesList); service.Paths.AddRange(paths); } } } ================================================ FILE: src/SwaggerWcf/Support/StaticContent.cs ================================================ using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; namespace SwaggerWcf.Support { public class StaticContent { private const string ZipFileName = "SwaggerWcf.www.swagger-ui.zip"; private static readonly ZipArchive Archive; private static ZipArchive _archiveCustom; internal static GetFileCustomDelegate GetFileCustom; static StaticContent() { try { Assembly assembly = Assembly.GetAssembly(typeof(StaticContent)); Stream zipStream = assembly.GetManifestResourceStream(ZipFileName); if (zipStream == null) return; Archive = new ZipArchive(zipStream); } catch { } } internal static void SetArchiveCustom(Stream zipCustomStream) { try { if (zipCustomStream == null) return; _archiveCustom = new ZipArchive(zipCustomStream); } catch { } } public static Stream GetFile(string filename, out string contentType, out long contentLength) { if (GetFileCustom != null) { Stream output = GetFileCustom(filename, out contentType, out contentLength); if (output != null) return output; } contentType = GetContentType(filename); if (_archiveCustom != null) { ZipArchiveEntry file = _archiveCustom.Entries.FirstOrDefault(entry => entry.FullName == filename); if (file != null && contentType != null) { contentLength = file.Length; return file.Open(); } } if (Archive != null) { ZipArchiveEntry file = Archive.Entries.FirstOrDefault(entry => entry.FullName == filename); if (file != null && contentType != null) { contentLength = file.Length; return file.Open(); } } return ReturnError(out contentType, out contentLength); } private static Stream ReturnError(out string contentType, out long contentLength) { contentType = ""; contentLength = 0; return Stream.Null; } private static string GetContentType(string filename) { int lastIndexOfDot = filename.LastIndexOf('.'); if (lastIndexOfDot < 0) return null; string extension = filename.Substring(lastIndexOfDot + 1); switch (extension.ToLower()) { case "html": return "text/html"; case "js": return "application/javascript"; case "css": return "text/css"; case "svg": return "image/svg+xml"; case "ttf": return "application/x-font-ttf"; case "eot": return "application/vnd.ms-fontobject"; case "woff": return "application/font-woff"; case "woff2": return "application/font-woff2"; case "gif": return "image/gif"; case "ico": return "image/x-icon"; case "png": return "image/png"; default: return null; } } } } ================================================ FILE: src/SwaggerWcf/Support/TypeBuilder.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using System.Reflection.Emit; using System.Runtime.Serialization; namespace SwaggerWcf.Support { public class TypeBuilder { public TypeBuilder(string typeName) { TypeName = typeName; Fields = new Dictionary>(); } private string TypeName { get; set; } private Dictionary> Fields { get; set; } public Type Type { get { return CompileResultType(); } } public void AddField(string fieldName, Type fieldType, bool required) { if (Fields.ContainsKey(fieldName)) Fields[fieldName] = new Tuple(fieldType, required); else Fields.Add(fieldName, new Tuple(fieldType, required)); } public Type CompileResultType() { System.Reflection.Emit.TypeBuilder tb = GetTypeBuilder(); ConstructorBuilder constructor = tb.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); // NOTE: assuming your list contains Field objects with fields FieldName(string) and FieldType(Type) foreach (KeyValuePair> field in Fields) CreateProperty(tb, field.Key, field.Value.Item1, field.Value.Item2); Type objectType = tb.CreateType(); return objectType; } private System.Reflection.Emit.TypeBuilder GetTypeBuilder() { string typeSignature = TypeName; AssemblyName an = new AssemblyName(typeSignature); AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule"); System.Reflection.Emit.TypeBuilder tb = moduleBuilder.DefineType(typeSignature, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout, null); return tb; } private static void CreateProperty(System.Reflection.Emit.TypeBuilder tb, string propertyName, Type propertyType, bool required) { FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private); PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null); MethodBuilder getPropMthdBldr = tb.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes); ILGenerator getIl = getPropMthdBldr.GetILGenerator(); getIl.Emit(OpCodes.Ldarg_0); getIl.Emit(OpCodes.Ldfld, fieldBuilder); getIl.Emit(OpCodes.Ret); MethodBuilder setPropMthdBldr = tb.DefineMethod("set_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, null, new[] { propertyType }); ILGenerator setIl = setPropMthdBldr.GetILGenerator(); Label modifyProperty = setIl.DefineLabel(); Label exitSet = setIl.DefineLabel(); setIl.MarkLabel(modifyProperty); setIl.Emit(OpCodes.Ldarg_0); setIl.Emit(OpCodes.Ldarg_1); setIl.Emit(OpCodes.Stfld, fieldBuilder); setIl.Emit(OpCodes.Nop); setIl.MarkLabel(exitSet); setIl.Emit(OpCodes.Ret); Type[] ctorParams = { }; ConstructorInfo contructorInfo = typeof(DataMemberAttribute).GetConstructor(ctorParams); CustomAttributeBuilder customAttrBuilder = new CustomAttributeBuilder(contructorInfo, new object[] { }); //TODO: set IsRequired here ?? propertyBuilder.SetCustomAttribute(customAttrBuilder); propertyBuilder.SetGetMethod(getPropMthdBldr); propertyBuilder.SetSetMethod(setPropMthdBldr); } } } ================================================ FILE: src/SwaggerWcf/Support/TypeExtensions.cs ================================================ using SwaggerWcf.Attributes; using SwaggerWcf.Models; using System; using System.Linq; using System.Reflection; namespace SwaggerWcf.Support { internal static class TypeExtensions { public static Type GetEnumerableType(this Type type) { Type elementType = type.GetElementType(); if (elementType != null) return elementType; Type[] genericArguments = type.GetGenericArguments(); return genericArguments.Any() ? genericArguments[0] : null; } public static string GetModelName(this Type type) => type.GetCustomAttribute()?.ModelName ?? type.FullName; public static string GetModelWrappedName(this Type type) => type.GetCustomAttribute()?.ModelName ?? type.FullName; internal static Info GetServiceInfo(this TypeInfo typeInfo) { var infoAttr = typeInfo.GetCustomAttribute() ?? throw new ArgumentException($"{typeInfo.FullName} does not have {nameof(SwaggerWcfServiceInfoAttribute)}"); var info = (Info)infoAttr; var contactAttr = typeInfo.GetCustomAttribute(); if (contactAttr != null) { info.Contact = (InfoContact)contactAttr; } var licenseAttr = typeInfo.GetCustomAttribute(); if (licenseAttr != null) { info.License = (InfoLicense)licenseAttr; } return info; } } } ================================================ FILE: src/SwaggerWcf/Support/TypeFieldsProcessor.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using SwaggerWcf.Attributes; using SwaggerWcf.Models; namespace SwaggerWcf.Support { internal static class TypeFieldsProcessor { public static void ProcessFields(Type definitionType, DefinitionSchema schema, IList hiddenTags, Stack typesStack) { var properties = definitionType.GetFields(); foreach (var fieldInfo in properties) { DefinitionProperty prop = ProcessField(fieldInfo, hiddenTags, typesStack); if (prop == null) continue; if (prop.TypeFormat.Type == ParameterType.Array) { Type propType = fieldInfo.FieldType; Type t = propType.GetElementType() ?? DefinitionsBuilder.GetEnumerableType(propType); if (t != null) { //prop.TypeFormat = new TypeFormat(prop.TypeFormat.Type, HttpUtility.HtmlEncode(t.FullName)); prop.TypeFormat = new TypeFormat(prop.TypeFormat.Type, null); TypeFormat st = Helpers.MapSwaggerType(t); if (st.Type == ParameterType.Array || st.Type == ParameterType.Object) { prop.Items.TypeFormat = new TypeFormat(ParameterType.Unknown, null); prop.Items.Ref = t.GetModelName(); } else { prop.Items.TypeFormat = st; } } } if (prop.Required) { if (schema.Required == null) schema.Required = new List(); schema.Required.Add(prop.Title); } schema.Properties.Add(prop); } } private static DefinitionProperty ProcessField(FieldInfo propertyInfo, IList hiddenTags, Stack typesStack) { if (propertyInfo.GetCustomAttribute() != null || propertyInfo.GetCustomAttributes() .Select(t => t.TagName) .Any(hiddenTags.Contains)) return null; TypeFormat typeFormat = Helpers.MapSwaggerType(propertyInfo.FieldType, null); DefinitionProperty prop = new DefinitionProperty { Title = propertyInfo.Name }; DataMemberAttribute dataMemberAttribute = propertyInfo.GetCustomAttribute(); if (dataMemberAttribute != null) { if (!string.IsNullOrEmpty(dataMemberAttribute.Name)) prop.Title = dataMemberAttribute.Name; prop.Required = dataMemberAttribute.IsRequired; } // Special case - if it came out required, but we unwrapped a null-able type, // then it's necessarily not required. Ideally this would only set the default, // but we can't tell the difference between an explicit declaration of // IsRequired =false on the DataMember attribute and no declaration at all. if (prop.Required && propertyInfo.FieldType.IsGenericType && propertyInfo.FieldType.GetGenericTypeDefinition() == typeof(Nullable<>)) { prop.Required = false; } DescriptionAttribute descriptionAttribute = propertyInfo.GetCustomAttribute(); if (descriptionAttribute != null) prop.Description = descriptionAttribute.Description; SwaggerWcfRegexAttribute regexAttr = propertyInfo.GetCustomAttribute(); if (regexAttr != null) prop.Pattern = regexAttr.Regex; prop.TypeFormat = typeFormat; if (prop.TypeFormat.Type == ParameterType.Object) { typesStack.Push(propertyInfo.FieldType); prop.Ref = propertyInfo.FieldType.GetModelName(); return prop; } if (prop.TypeFormat.Type == ParameterType.Array) { Type subType = DefinitionsBuilder.GetEnumerableType(propertyInfo.FieldType); if (subType != null) { TypeFormat subTypeFormat = Helpers.MapSwaggerType(subType, null); if (subTypeFormat.Type == ParameterType.Object) typesStack.Push(subType); prop.Items = new ParameterItems { TypeFormat = subTypeFormat }; } } if ((prop.TypeFormat.Type == ParameterType.Integer && prop.TypeFormat.Format == "enum") || (prop.TypeFormat.Type == ParameterType.Array && prop.Items.TypeFormat.Format == "enum")) { prop.Enum = new List(); Type propType = propertyInfo.FieldType; if (propType.IsGenericType && (propType.GetGenericTypeDefinition() == typeof(Nullable<>) || propType.GetGenericTypeDefinition() == typeof(List<>))) propType = propType.GetEnumerableType(); string enumDescription = ""; List listOfEnumNames = propType.GetEnumNames().ToList(); foreach (string enumName in listOfEnumNames) { var enumMemberItem = Enum.Parse(propType, enumName, true); string enumMemberDescription = DefinitionsBuilder.GetEnumDescription((Enum)enumMemberItem); enumMemberDescription = (string.IsNullOrWhiteSpace(enumMemberDescription)) ? "" : $"({enumMemberDescription})"; int enumMemberValue = DefinitionsBuilder.GetEnumMemberValue(propType, enumName); if (prop.Description != null) prop.Enum.Add(enumMemberValue); enumDescription += $" {enumName}{System.Web.HttpUtility.HtmlEncode(" = ")}{enumMemberValue} {enumMemberDescription}\r\n"; } if (enumDescription != "") { prop.Description += $"\r\n\r\n{enumDescription}"; } } // Apply any options set in a [SwaggerWcfProperty] DefinitionsBuilder.ApplyAttributeOptions(propertyInfo, prop); return prop; } } } ================================================ FILE: src/SwaggerWcf/Support/TypePropertiesProcessor.cs ================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using SwaggerWcf.Attributes; using SwaggerWcf.Models; namespace SwaggerWcf.Support { internal static class TypePropertiesProcessor { public static void ProcessProperties(Type definitionType, DefinitionSchema schema, IList hiddenTags, Stack typesStack) { PropertyInfo[] properties = definitionType.GetProperties(); foreach (PropertyInfo propertyInfo in properties) { DefinitionProperty prop = ProcessProperty(propertyInfo, hiddenTags, typesStack); if (prop == null) continue; if (prop.TypeFormat.Type == ParameterType.Array) { Type propType = propertyInfo.PropertyType; Type t = propType.GetElementType() ?? DefinitionsBuilder.GetEnumerableType(propType); if (t != null) { //prop.TypeFormat = new TypeFormat(prop.TypeFormat.Type, HttpUtility.HtmlEncode(t.FullName)); prop.TypeFormat = new TypeFormat(prop.TypeFormat.Type, null); TypeFormat st = Helpers.MapSwaggerType(t); if (st.Type == ParameterType.Array || st.Type == ParameterType.Object) { prop.Items.TypeFormat = new TypeFormat(ParameterType.Unknown, null); prop.Items.Ref = t.GetModelName(); } else { prop.Items.TypeFormat = st; } } } if (prop.Required) { if (schema.Required == null) schema.Required = new List(); schema.Required.Add(prop.Title); } schema.Properties.Add(prop); } } private static DefinitionProperty ProcessProperty(PropertyInfo propertyInfo, IList hiddenTags, Stack typesStack) { if (propertyInfo.GetCustomAttribute() != null || propertyInfo.GetCustomAttributes() .Select(t => t.TagName) .Any(hiddenTags.Contains)) return null; TypeFormat typeFormat = Helpers.MapSwaggerType(propertyInfo.PropertyType, null); DefinitionProperty prop = new DefinitionProperty { Title = propertyInfo.Name }; DataMemberAttribute dataMemberAttribute = propertyInfo.GetCustomAttribute(); if (dataMemberAttribute != null) { if (!string.IsNullOrEmpty(dataMemberAttribute.Name)) prop.Title = dataMemberAttribute.Name; prop.Required = dataMemberAttribute.IsRequired; } // Special case - if it came out required, but we unwrapped a null-able type, // then it's necessarily not required. Ideally this would only set the default, // but we can't tell the difference between an explicit declaration of // IsRequired =false on the DataMember attribute and no declaration at all. if (prop.Required && propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { prop.Required = false; } DescriptionAttribute descriptionAttribute = propertyInfo.GetCustomAttribute(); if (descriptionAttribute != null) prop.Description = descriptionAttribute.Description; SwaggerWcfRegexAttribute regexAttr = propertyInfo.GetCustomAttribute(); if (regexAttr != null) prop.Pattern = regexAttr.Regex; prop.TypeFormat = typeFormat; if (prop.TypeFormat.Type == ParameterType.Object) { typesStack.Push(propertyInfo.PropertyType); prop.Ref = propertyInfo.PropertyType.GetModelName(); return prop; } if (prop.TypeFormat.Type == ParameterType.Array) { Type subType = DefinitionsBuilder.GetEnumerableType(propertyInfo.PropertyType); if (subType != null) { TypeFormat subTypeFormat = Helpers.MapSwaggerType(subType, null); if (subTypeFormat.Type == ParameterType.Object) typesStack.Push(subType); prop.Items = new ParameterItems { TypeFormat = subTypeFormat }; } } if ((prop.TypeFormat.Type == ParameterType.Integer && prop.TypeFormat.Format == "enum") || (prop.TypeFormat.Type == ParameterType.Array && prop.Items.TypeFormat.Format == "enum")) { prop.Enum = new List(); Type propType = propertyInfo.PropertyType; if (propType.IsGenericType && (propType.GetGenericTypeDefinition() == typeof(Nullable<>) || propType.GetGenericTypeDefinition() == typeof(List<>))) propType = propType.GetEnumerableType(); string enumDescription = ""; List listOfEnumNames = propType.GetEnumNames().ToList(); foreach (string enumName in listOfEnumNames) { var enumMemberItem = Enum.Parse(propType, enumName, true); string enumMemberDescription = DefinitionsBuilder.GetEnumDescription((Enum)enumMemberItem); enumMemberDescription = (string.IsNullOrWhiteSpace(enumMemberDescription)) ? "" : $"({enumMemberDescription})"; int enumMemberValue = DefinitionsBuilder.GetEnumMemberValue(propType, enumName); if (prop.Description != null) prop.Enum.Add(enumMemberValue); enumDescription += $" {enumName}{System.Web.HttpUtility.HtmlEncode(" = ")}{enumMemberValue} {enumMemberDescription}\r\n"; } if (enumDescription != "") { prop.Description += $"\r\n\r\n{enumDescription}"; } } // Apply any options set in a [SwaggerWcfProperty] DefinitionsBuilder.ApplyAttributeOptions(propertyInfo, prop); return prop; } } } ================================================ FILE: src/SwaggerWcf/SwaggerWcf.csproj ================================================  Release AnyCPU {0AD6EFBC-412F-4C0E-8E0A-0FAF28151B55} Library Properties SwaggerWcf SwaggerWcf v4.5 512 ..\ true full false bin\Debug\ DEBUG;TRACE prompt 4 pdbonly true bin\Release\ TRACE prompt 4 ..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll True ================================================ FILE: src/SwaggerWcf/SwaggerWcf.csproj.DotSettings ================================================  CSharp70 ================================================ FILE: src/SwaggerWcf/SwaggerWcf.nuspec ================================================  $title$ $version$ $title$ $author$ $author$ https://raw.githubusercontent.com/abelsilva/swaggerwcf/master/LICENSE https://github.com/abelsilva/swaggerwcf false $description$ #160 Copyright 2018 swagger wcf .net c# ================================================ FILE: src/SwaggerWcf/SwaggerWcfEndpoint.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Web; using System.Text; using SwaggerWcf.Models; using SwaggerWcf.Support; using System.Runtime.CompilerServices; namespace SwaggerWcf { public delegate Stream GetFileCustomDelegate(string filename, out string contentType, out long contentLength); [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class SwaggerWcfEndpoint : ISwaggerWcfEndpoint { public SwaggerWcfEndpoint() { Init(ServiceBuilder.Build); } internal SwaggerWcfEndpoint(Func buildService) { Init(buildService); } internal static Info Info { get; private set; } internal static SecurityDefinitions SecurityDefinitions { get; private set; } internal static string BasePath { get; private set; } private static Dictionary SwaggerFiles { get; } = new Dictionary(); public static bool DisableSwaggerUI { get; set; } public static Func, List> FilterVisibleTags { get; set; } = (string path, List visibleTags) => visibleTags; public static Func, List> FilterHiddenTags { get; set; } = (string path, List hiddenTags) => hiddenTags; public static void Configure(Info info, SecurityDefinitions securityDefinitions = null, string basePath = null) { Info = info; SecurityDefinitions = securityDefinitions; BasePath = basePath; } [MethodImpl(MethodImplOptions.Synchronized)] internal static void Init(Func buildService) { string[] paths = GetAllPaths().Where(p => !SwaggerFiles.Keys.Contains(p)).ToArray(); foreach (string path in paths) { Service service = buildService(path); if (Info != null) service.Info = Info; if (SecurityDefinitions != null) service.SecurityDefinitions = SecurityDefinitions; if (BasePath != null) service.BasePath = BasePath; string swagger = Serializer.Process(service); if (SwaggerFiles.ContainsKey(path) == false) SwaggerFiles.Add(path, swagger); } } private static string[] GetAllPaths() { return OperationContext.Current?.Host?.BaseAddresses.Select(ba => ba.AbsolutePath).ToArray() ?? new[] { "" }; } private static string GetSwaggerFileContents() { string fullPath = WebOperationContext.Current?.IncomingRequest.UriTemplateMatch?.RequestUri?.AbsolutePath ?? ""; string key = SwaggerFiles.Keys.ToList().ClosestMatch(fullPath); return key != null ? SwaggerFiles[key] : ""; } public static void SetCustomZip(Stream customSwaggerUiZipStream) { if (customSwaggerUiZipStream != null) Support.StaticContent.SetArchiveCustom(customSwaggerUiZipStream); } public static void SetCustomGetFile(GetFileCustomDelegate getFileCustom) { Support.StaticContent.GetFileCustom = getFileCustom; } public Stream GetSwaggerFile() { WebOperationContext woc = WebOperationContext.Current; if (woc != null) { //TODO: create a parameter in settings to configure this woc.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*"); woc.OutgoingResponse.ContentType = "application/json"; } return new MemoryStream(Encoding.UTF8.GetBytes(GetSwaggerFileContents())); } public Stream StaticContent(string content) { WebOperationContext woc = WebOperationContext.Current; if (woc == null) return Stream.Null; if (DisableSwaggerUI) { woc.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; return null; } if (string.IsNullOrWhiteSpace(content)) { string swaggerUrl = woc.IncomingRequest.UriTemplateMatch.BaseUri.LocalPath + "/swagger.json"; woc.OutgoingResponse.StatusCode = HttpStatusCode.Redirect; woc.OutgoingResponse.Location = "index.html?url=" + swaggerUrl; return null; } string filename = content.Contains("?") ? content.Substring(0, content.IndexOf("?", StringComparison.Ordinal)) : content; string contentType; long contentLength; Stream stream = Support.StaticContent.GetFile(filename, out contentType, out contentLength); if (stream == Stream.Null) { woc.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; return null; } woc.OutgoingResponse.StatusCode = HttpStatusCode.OK; woc.OutgoingResponse.ContentLength = contentLength; woc.OutgoingResponse.ContentType = contentType; return stream; } } } ================================================ FILE: src/SwaggerWcf/SwaggerWcfEndpointGeneric.cs ================================================ using System.ServiceModel.Activation; using SwaggerWcf.Support; namespace SwaggerWcf { [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class SwaggerWcfEndpoint : SwaggerWcfEndpoint { public SwaggerWcfEndpoint() : base(ServiceBuilder.Build) { } } } ================================================ FILE: src/SwaggerWcf/packages.config ================================================  ================================================ FILE: src/SwaggerWcf.Test.Service/AuthorService.cs ================================================ using SwaggerWcf.Attributes; using SwaggerWcf.Test.Service.Data; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace SwaggerWcf.Test.Service { [SwaggerWcf("/v1/authors")] [SwaggerWcfTag("Authors")] [SwaggerWcfServiceInfo( title: "SampleAuthorService", version: "0.0.1", Description = "Sample Author Service to test SwaggerWCF", TermsOfService = "Terms of Service" )] [SwaggerWcfContactInfo( Name = "Abel Silva", Url = "http://github.com/abelsilva", Email = "no@e.mail" )] [SwaggerWcfLicenseInfo( name: "Apache License 2.0", Url = "https://github.com/abelsilva/SwaggerWCF/blob/master/LICENSE" )] public class AuthorService : BaseService, IAuthorService { [SwaggerWcfTag("GenericAuthor")] public override Author Get(string id) { return new Author { Id = id }; } [SwaggerWcfTag("GenericAuthor")] public override Author Create(Author item) { return item; } [SwaggerWcfTag("GenericAuthor")] public override Author Update(string id, Author item) { return new Author { Id = id }; } [SwaggerWcfTag("GenericAuthor")] public override Author Delete(string id) { return new Author { Id = id }; } } } ================================================ FILE: src/SwaggerWcf.Test.Service/BaseService.cs ================================================ using SwaggerWcf.Test.Service.Data; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace SwaggerWcf.Test.Service { public abstract class BaseService : IBaseService, IBaseCRUDService { public abstract T Create(T item); public abstract T Delete(string id); public abstract T Get(string id); public abstract T Update(string id, T item); public virtual string TestService(string input) { return $"input = {input}. Now = {DateTime.Now}"; } public string TestServicePost(string input, string postObj) { return $"input = {input}. Now = {DateTime.Now}"; } } } ================================================ FILE: src/SwaggerWcf.Test.Service/Data/Author.cs ================================================ using System.Runtime.Serialization; using SwaggerWcf.Attributes; namespace SwaggerWcf.Test.Service.Data { [DataContract] [SwaggerWcfDefinition("author")] public class Author { [DataMember] public string Id { get; set; } [DataMember] public string Name { get; set; } } } ================================================ FILE: src/SwaggerWcf.Test.Service/Data/Book.cs ================================================ using System.ComponentModel; using System.Runtime.Serialization; using SwaggerWcf.Attributes; namespace SwaggerWcf.Test.Service.Data { [DataContract] [Description("Book with title, first publish date, author and language")] [SwaggerWcfDefinition(ExternalDocsUrl = "http://en.wikipedia.org/wiki/Book", ExternalDocsDescription = "Description of a book")] public class Book { [DataMember] [Description("Book ID")] [SwaggerWcfRegex("[\\w\\d]*")] public string Id { get; set; } [DataMember] [Description("Book Title")] public string Title { get; set; } [DataMember] [Description("Book First Publish Date")] public int FirstPublished { get; set; } [DataMember] [Description("Book Author")] public Author Author { get; set; } [DataMember] [Description("Book Language")] public Language Language { get; set; } [DataMember] [Description("Book Tags")] public string[] Tags { get; set; } } } ================================================ FILE: src/SwaggerWcf.Test.Service/Data/Language.cs ================================================ using System.ComponentModel; using System.Runtime.Serialization; namespace SwaggerWcf.Test.Service.Data { [DataContract(Name = "language")] public enum Language { [Description("Undefined language")] Unknown = 0, English = 1, Spanish = 2, French = 3, Chinese = 4, } } ================================================ FILE: src/SwaggerWcf.Test.Service/Data/Store.cs ================================================ using System; using System.Collections.Generic; namespace SwaggerWcf.Test.Service.Data { public class Store { static Store() { Books = new List(); Authors = new List(); var authorMiguelCervantes = new Author { Id = Guid.NewGuid().ToString("N"), Name = "Miguel de Cervantes" }; var authorCharlesDickens = new Author { Id = Guid.NewGuid().ToString("N"), Name = "Charles Dickens" }; var authorJRRTolkien = new Author { Id = Guid.NewGuid().ToString("N"), Name = "J. R. R. Tolkien" }; var authorAntoineSaintExupery = new Author { Id = Guid.NewGuid().ToString("N"), Name = "Antoine de Saint-Exupéry" }; var authorJKRowling = new Author { Id = Guid.NewGuid().ToString("N"), Name = "J. K. Rowling" }; var authorAgathaChristie = new Author { Id = Guid.NewGuid().ToString("N"), Name = "Agatha Christie" }; var authorCaoXueqin = new Author { Id = Guid.NewGuid().ToString("N"), Name = "Cao Xueqin" }; var authorHRiderHaggard = new Author { Id = Guid.NewGuid().ToString("N"), Name = "H. Rider Haggard" }; Authors.Add(authorMiguelCervantes); Authors.Add(authorCharlesDickens); Authors.Add(authorJRRTolkien); Authors.Add(authorAntoineSaintExupery); Authors.Add(authorJKRowling); Authors.Add(authorAgathaChristie); Authors.Add(authorCaoXueqin); Authors.Add(authorHRiderHaggard); var bookDonQuixote = new Book { Id = Guid.NewGuid().ToString("N"), Title = "Don Quixote", Author = authorMiguelCervantes, FirstPublished = 1605, Language = Language.Spanish }; var bookATaleOfTwoCities = new Book { Id = Guid.NewGuid().ToString("N"), Title = "A Tale Of Two Cities", Author = authorCharlesDickens, FirstPublished = 1859, Language = Language.English }; var bookTheLordOfTheRings = new Book { Id = Guid.NewGuid().ToString("N"), Title = "The Lord of the Rings", Author = authorJRRTolkien, FirstPublished = 1954, Language = Language.English }; var bookTheHobbit = new Book { Id = Guid.NewGuid().ToString("N"), Title = "The Hobbit", Author = authorJRRTolkien, FirstPublished = 1937, Language = Language.English }; var bookLePetitPrince = new Book { Id = Guid.NewGuid().ToString("N"), Title = "Le Petit Prince", Author = authorAntoineSaintExupery, FirstPublished = 1943, Language = Language.French }; var bookHarryPotterAndThePhilosopherStone = new Book { Id = Guid.NewGuid().ToString("N"), Title = "Harry Potter and the Philosopher's Stone", Author = authorJKRowling, FirstPublished = 1997, Language = Language.English }; var bookAndThenThereWereNone = new Book { Id = Guid.NewGuid().ToString("N"), Title = "And Then There Were None", Author = authorAgathaChristie, FirstPublished = 1939, Language = Language.English }; var bookDreamOfTheRedChamber = new Book { Id = Guid.NewGuid().ToString("N"), Title = "紅樓夢/红楼梦 (Dream of the Red Chamber)", Author = authorCaoXueqin, FirstPublished = 1754, Language = Language.Chinese }; var bookSheAHistoryOfAdventure = new Book { Id = Guid.NewGuid().ToString("N"), Title = "She: A History of Adventure", Author = authorHRiderHaggard, FirstPublished = 1887, Language = Language.English }; Books.Add(bookDonQuixote); Books.Add(bookATaleOfTwoCities); Books.Add(bookTheLordOfTheRings); Books.Add(bookTheHobbit); Books.Add(bookLePetitPrince); Books.Add(bookHarryPotterAndThePhilosopherStone); Books.Add(bookAndThenThereWereNone); Books.Add(bookDreamOfTheRedChamber); Books.Add(bookSheAHistoryOfAdventure); } public static readonly List Books; public static readonly List Authors; } } ================================================ FILE: src/SwaggerWcf.Test.Service/Global.asax ================================================ <%@ Application Codebehind="Global.asax.cs" Inherits="SwaggerWcf.Test.Service.Global" Language="C#" %> ================================================ FILE: src/SwaggerWcf.Test.Service/Global.asax.cs ================================================ using System; using System.Collections.Generic; using System.ServiceModel.Activation; using System.Web; using System.Web.Routing; using SwaggerWcf.Models; namespace SwaggerWcf.Test.Service { public class Global : HttpApplication { protected void Application_Start(object sender, EventArgs e) { SwaggerWcfEndpoint.FilterVisibleTags = FilterVisibleTags; SwaggerWcfEndpoint.FilterHiddenTags = FilterHiddenTags; SwaggerWcfEndpoint.DisableSwaggerUI = false; // route with a simple class RouteTable.Routes.Add(new ServiceRoute("v1/rest", new WebServiceHostFactory(), typeof(BookStore))); // route with inherited methods on a base class RouteTable.Routes.Add(new ServiceRoute("v1/authors", new WebServiceHostFactory(), typeof(AuthorService))); RouteTable.Routes.Add(new ServiceRoute("api-docs", new WebServiceHostFactory(), typeof(SwaggerWcfEndpoint))); } private static List FilterVisibleTags(string path, List visibleTags) { return visibleTags; } private static List FilterHiddenTags(string path, List hiddenTags) { return hiddenTags; } protected void Session_Start(object sender, EventArgs e) { } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { } protected void Session_End(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { } } } ================================================ FILE: src/SwaggerWcf.Test.Service/IAuthorService.cs ================================================ using SwaggerWcf.Test.Service.Data; using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Web; namespace SwaggerWcf.Test.Service { [ServiceContract] public interface IAuthorService : IBaseService, IBaseCRUDService { } } ================================================ FILE: src/SwaggerWcf.Test.Service/IBaseCRUDService.cs ================================================ using SwaggerWcf.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; using System.Threading.Tasks; namespace SwaggerWcf.Test.Service { [ServiceContract] public interface IBaseCRUDService { [SwaggerWcfPath("Get Operation")] [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "get/{id}")] T Get(string id); [SwaggerWcfPath("Create Operation")] [OperationContract] [WebInvoke(Method = "PUT", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "")] T Create(T item); [SwaggerWcfPath("Update Operation")] [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "{id}")] T Update(string id, T item); [SwaggerWcfPath("Delete Operation")] [OperationContract] [WebInvoke(Method = "DELETE", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "{id}")] T Delete(string id); } } ================================================ FILE: src/SwaggerWcf.Test.Service/IBaseService.cs ================================================ using SwaggerWcf.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; using System.Threading.Tasks; namespace SwaggerWcf.Test.Service { [ServiceContract] public interface IBaseService { [SwaggerWcfPath("Test Service")] [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "testService?input={input}")] string TestService(string input); [SwaggerWcfPath("Test Service")] [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "testServicePost?input={input}")] string TestServicePost(string input, string postObj); } } ================================================ FILE: src/SwaggerWcf.Test.Service/IStore.cs ================================================ using System; using System.Collections.Generic; using System.Net; using System.ServiceModel; using System.ServiceModel.Web; using SwaggerWcf.Attributes; using SwaggerWcf.Test.Service.Data; namespace SwaggerWcf.Test.Service { [ServiceContract] public interface IStore { #region /books [SwaggerWcfPath("Create book", "Create a book on the store")] // default Method for WebInvoke is POST [WebInvoke(UriTemplate = "/books", BodyStyle = WebMessageBodyStyle.Wrapped, //Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] [OperationContract] Book CreateBook([SwaggerWcfParameter(Description = "Book to be created, the id will be replaced")] Book value); [SwaggerWcfPath("Get books", "Retrieve all books from the store")] [WebGet(UriTemplate = "/books?filter={filterText}", BodyStyle = WebMessageBodyStyle.Bare)] [OperationContract] Book[] ReadBooks(string filterText = null); [SwaggerWcfPath("Get book", "Retrieve a book from the store using its id")] [WebGet(UriTemplate = "/books/{id}", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] [OperationContract] Book ReadBook(string id); [SwaggerWcfPath("Update book", "Update a book on the store")] [WebInvoke(UriTemplate = "/books/{id}", BodyStyle = WebMessageBodyStyle.Bare, Method = "PUT", RequestFormat = WebMessageFormat.Json)] [OperationContract] void UpdateBook(string id, [SwaggerWcfParameter( Description = "Book to be updated, make sure the id in the book matches the id in the path parameter")] Book value); [SwaggerWcfPath("Delete book", "Delete a book on the store")] [WebInvoke(UriTemplate = "/books/{id}", BodyStyle = WebMessageBodyStyle.Bare, Method = "DELETE")] [OperationContract] void DeleteBook(string id); [SwaggerWcfPath("Get book author", "Retrieve the author of a book using the book id")] [WebGet(UriTemplate = "/books/{id}/author", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] [OperationContract] Author ReadBookAuthor(string id); #endregion #region /authors [SwaggerWcfPath("Create author", "Create an author on the store")] [WebInvoke(UriTemplate = "/authors", BodyStyle = WebMessageBodyStyle.Bare, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Xml)] [OperationContract] Author CreateAuthor( [SwaggerWcfParameter(Description = "Author to be created, the id will be replaced")] Author value); [SwaggerWcfPath("Get authors", "Retrieve all authors from the store")] [WebGet(UriTemplate = "/authors", BodyStyle = WebMessageBodyStyle.Bare)] [OperationContract] IList ReadAuthors(); [SwaggerWcfPath("Get author", "Retrieve an author from the store using its id")] [WebGet(UriTemplate = "/authors/{id}", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Xml)] [OperationContract] Author ReadAuthor(string id); [SwaggerWcfPath("Update author", "Update an author on the store")] [WebInvoke(UriTemplate = "/authors/{id}", BodyStyle = WebMessageBodyStyle.Bare, Method = "PUT", RequestFormat = WebMessageFormat.Json)] [OperationContract] void UpdateAuthor(string id, [SwaggerWcfParameter( Description = "Author to be updated, make sure the id in the author matches the id in the path parameter" )] Author value); [SwaggerWcfPath("Delete author", "Delete an author on the store")] [WebInvoke(UriTemplate = "/authors/{id}", BodyStyle = WebMessageBodyStyle.Bare, Method = "DELETE")] [OperationContract] void DeleteAuthor(string id); [SwaggerWcfPath("Get author books", "Retrieve the author books using the author id")] [WebGet(UriTemplate = "/authors/{id}/books", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Xml)] [OperationContract] Book[] ReadAuthorBooks(string id); #endregion #region /languages [SwaggerWcfPath("Create language", "Create an language on the store")] [WebInvoke(UriTemplate = "/languages", BodyStyle = WebMessageBodyStyle.Bare, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Xml)] [OperationContract] Language CreateLanguage( [SwaggerWcfParameter(Description = "Language to be created, the id will be replaced")] Language value); [SwaggerWcfPath("Get languages", "Retrieve all languages from the store")] [WebGet(UriTemplate = "/languages", BodyStyle = WebMessageBodyStyle.Bare)] [OperationContract] Language[] ReadLanguages(); [SwaggerWcfPath("Get language", "Retrieve an language from the store using its id")] [WebGet(UriTemplate = "/languages/{id}", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Xml)] [OperationContract] Language ReadLanguage(string id); [SwaggerWcfPath("Update language", "Update an language on the store")] [WebInvoke(UriTemplate = "/languages/{id}", BodyStyle = WebMessageBodyStyle.Bare, Method = "PUT", RequestFormat = WebMessageFormat.Json)] [OperationContract] void UpdateLanguage(string id, [SwaggerWcfParameter( Description = "Language to be updated, make sure the id in the language matches the id in the path parameter" )] Language value); [SwaggerWcfPath("Delete language", "Delete an language on the store")] [WebInvoke(UriTemplate = "/languages/{id}", BodyStyle = WebMessageBodyStyle.Bare, Method = "DELETE")] [OperationContract] void DeleteLanguage(string id); #endregion } } ================================================ FILE: src/SwaggerWcf.Test.Service/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SwaggerWcf.Test.Service")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SwaggerWcf.Test.Service")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fd02752a-614d-4faf-8994-519c754107b1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: src/SwaggerWcf.Test.Service/Store.svc ================================================ <%@ ServiceHost Language="C#" Debug="true" Service="SwaggerWcf.Test.Service.BookStore" CodeBehind="Store.svc.cs" %> ================================================ FILE: src/SwaggerWcf.Test.Service/Store.svc.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.ServiceModel.Web; using SwaggerWcf.Attributes; using SwaggerWcf.Test.Service.Data; namespace SwaggerWcf.Test.Service { [SwaggerWcf("/v1/rest")] [SwaggerWcfTag("BookStore")] [SwaggerWcfServiceInfo( title: "SampleService", version: "0.0.1", Description = "Sample Service to test SwaggerWCF", TermsOfService = "Terms of Service" )] [SwaggerWcfContactInfo( Name = "Abel Silva", Url = "http://github.com/abelsilva", Email = "no@e.mail" )] [SwaggerWcfLicenseInfo( name: "Apache License 2.0", Url = "https://github.com/abelsilva/SwaggerWCF/blob/master/LICENSE" )] public class BookStore : IStore { #region /books [SwaggerWcfTag("Books")] [SwaggerWcfHeader("clientId", false, "Client ID", "000")] [SwaggerWcfResponse(HttpStatusCode.Created, "Book created, value in the response body with id updated", ExampleMimeType = "application/json", ExampleContent = "{\"Author\": {\"Id\": \"1dacefd76d3f443d802d326dba990ab0\",\"Name\": \"Miguel de Cervantes\"},\"FirstPublished\": 1605,\"Id\": \"017b1d907db64a868cb5d2c4d47d6077\",\"Language\": 2,\"Title\":\"Don Quixote\"}")] [SwaggerWcfResponse(HttpStatusCode.BadRequest, "Bad request", true, ExampleMimeType = "application/json", ExampleContent = "{\"error:\": \"error description\"}")] [SwaggerWcfResponse(HttpStatusCode.InternalServerError, "Internal error (can be forced using ERROR_500 as book title)", true, ExampleMimeType = "application/json", ExampleContent = "{\"error:\": \"error description\"}")] public Book CreateBook(Book value) { WebOperationContext woc = WebOperationContext.Current; if (woc == null) return null; if (value == null) { woc.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest; return null; } if (!string.IsNullOrWhiteSpace(value.Title) && value.Title == "ERROR_500") { woc.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError; return null; } value.Id = Guid.NewGuid().ToString("N"); Store.Books.Add(value); woc.OutgoingResponse.StatusCode = HttpStatusCode.Created; return value; } [SwaggerWcfTag("Books")] [SwaggerWcfResponse(HttpStatusCode.OK, "Books found, values in the response body")] [SwaggerWcfResponse(HttpStatusCode.NotFound, "Book not found", true)] [SwaggerWcfResponse(HttpStatusCode.InternalServerError, "Internal error (can be forced using ERROR_500 as book id)", true)] public Book ReadBook(string id) { WebOperationContext woc = WebOperationContext.Current; if (woc == null) return null; Book book = Store.Books.FirstOrDefault(b => b.Id == id); if (book != null) { woc.OutgoingResponse.StatusCode = HttpStatusCode.OK; return book; } if (id == "ERROR_500") { woc.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError; return null; } woc.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; return null; } [SwaggerWcfTag("Books")] [SwaggerWcfResponse(HttpStatusCode.OK, "Book found, value in the response body")] [SwaggerWcfResponse(HttpStatusCode.NoContent, "No books", true)] public Book[] ReadBooks(string filterText = null) { WebOperationContext woc = WebOperationContext.Current; if (woc == null) return null; if (Store.Books.Any()) { woc.OutgoingResponse.StatusCode = HttpStatusCode.OK; return string.IsNullOrEmpty(filterText) ? Store.Books.ToArray() : Store.Books.Where(b => b.Author.Name.Contains(filterText) || b.Title.Contains(filterText)).ToArray(); } woc.OutgoingResponse.StatusCode = HttpStatusCode.NoContent; return null; } [SwaggerWcfTag("Books")] [SwaggerWcfResponse(HttpStatusCode.NoContent, "Book updated")] [SwaggerWcfResponse(HttpStatusCode.BadRequest, "Bad request")] [SwaggerWcfResponse(HttpStatusCode.NotFound, "Book not found")] [SwaggerWcfResponse(HttpStatusCode.InternalServerError, "Internal error (can be forced using ERROR_500 as book id)")] public void UpdateBook(string id, Book value) { WebOperationContext woc = WebOperationContext.Current; if (woc == null) return; if (value == null || value.Id != id) { woc.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest; return; } Book book = Store.Books.FirstOrDefault(b => b.Id == id); if (book != null) { woc.OutgoingResponse.StatusCode = HttpStatusCode.NoContent; Store.Books.Remove(book); Store.Books.Add(value); } else if (id == "ERROR_500") { woc.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError; } else { woc.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; } } [SwaggerWcfTag("Books")] [SwaggerWcfResponse(HttpStatusCode.NoContent, "Book deleted")] [SwaggerWcfResponse(HttpStatusCode.NotFound, "Book not found")] [SwaggerWcfResponse(HttpStatusCode.InternalServerError, "Internal error (can be forced using ERROR_500 as book id)")] public void DeleteBook(string id) { WebOperationContext woc = WebOperationContext.Current; if (woc == null) return; Book book = Store.Books.FirstOrDefault(b => b.Id == id); if (book != null) { woc.OutgoingResponse.StatusCode = HttpStatusCode.NoContent; Store.Books.Remove(book); } else if (id == "ERROR_500") { woc.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError; } else { woc.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; } } [SwaggerWcfTag("LowPerformance", true)] [SwaggerWcfTag("Books")] [SwaggerWcfResponse(HttpStatusCode.OK, "Book found, author value in the response body")] [SwaggerWcfResponse(HttpStatusCode.NoContent, "Book found, author value in the response body")] [SwaggerWcfResponse(HttpStatusCode.NotFound, "Book not found", true)] [SwaggerWcfResponse(HttpStatusCode.InternalServerError, "Internal error (can be forced using ERROR_500 as book id)", true)] public Author ReadBookAuthor(string id) { WebOperationContext woc = WebOperationContext.Current; if (woc == null) return null; Book book = Store.Books.FirstOrDefault(b => b.Id == id); if (book != null) { if (book.Author == null) { woc.OutgoingResponse.StatusCode = HttpStatusCode.NoContent; return null; } woc.OutgoingResponse.StatusCode = HttpStatusCode.OK; return book.Author; } if (id == "ERROR_500") { woc.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError; return null; } woc.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; return null; } #endregion #region /authors [SwaggerWcfTag("Authors")] [SwaggerWcfResponse(201, "Author created, value in the response body with id updated")] [SwaggerWcfResponse(400, "Bad request", true)] [SwaggerWcfResponse(500, "Internal error (can be forced using ERROR_500 as author name)", true)] public Author CreateAuthor(Author value) { WebOperationContext woc = WebOperationContext.Current; if (woc == null) return null; if (value == null) { woc.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest; return null; } if (!string.IsNullOrWhiteSpace(value.Name) && value.Name == "ERROR_500") { woc.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError; return null; } value.Id = Guid.NewGuid().ToString("N"); Store.Authors.Add(value); woc.OutgoingResponse.StatusCode = HttpStatusCode.Created; return value; } [SwaggerWcfTag("Authors")] [SwaggerWcfResponse(200, "Author found, value in the response body")] [SwaggerWcfResponse(404, "Author not found", true)] [SwaggerWcfResponse(500, "Internal error (can be forced using ERROR_500 as author id)", true)] public Author ReadAuthor(string id) { WebOperationContext woc = WebOperationContext.Current; if (woc == null) return null; Author author = Store.Authors.FirstOrDefault(b => b.Id == id); if (author != null) { woc.OutgoingResponse.StatusCode = HttpStatusCode.OK; return author; } if (id == "ERROR_500") { woc.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError; return null; } woc.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; return null; } [SwaggerWcfTag("Authors")] [SwaggerWcfResponse(200, "Authors found, values in the response body")] [SwaggerWcfResponse(204, "No authors", true)] public IList ReadAuthors() { WebOperationContext woc = WebOperationContext.Current; if (woc == null) return null; if (Store.Authors.Any()) { woc.OutgoingResponse.StatusCode = HttpStatusCode.OK; return Store.Authors; } woc.OutgoingResponse.StatusCode = HttpStatusCode.NoContent; return null; } [SwaggerWcfTag("Authors")] [SwaggerWcfResponse(204, "Author updated")] [SwaggerWcfResponse(400, "Bad request")] [SwaggerWcfResponse(404, "Author not found")] [SwaggerWcfResponse(500, "Internal error (can be forced using ERROR_500 as author id)")] public void UpdateAuthor(string id, Author value) { WebOperationContext woc = WebOperationContext.Current; if (woc == null) return; if (value == null || value.Id != id) { woc.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest; return; } Author author = Store.Authors.FirstOrDefault(b => b.Id == id); if (author != null) { woc.OutgoingResponse.StatusCode = HttpStatusCode.NoContent; Store.Authors.Remove(author); Store.Authors.Add(value); } else if (id == "ERROR_500") { woc.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError; } else { woc.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; } } [SwaggerWcfTag("Authors")] [SwaggerWcfResponse(204, "Author deleted")] [SwaggerWcfResponse(404, "Author not found")] [SwaggerWcfResponse(500, "Internal error (can be forced using ERROR_500 as author id)")] public void DeleteAuthor(string id) { WebOperationContext woc = WebOperationContext.Current; if (woc == null) return; Author author = Store.Authors.FirstOrDefault(b => b.Id == id); if (author != null) { woc.OutgoingResponse.StatusCode = HttpStatusCode.NoContent; Store.Authors.Remove(author); } else if (id == "ERROR_500") { woc.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError; } else { woc.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; } } [SwaggerWcfTag("LowPerformance", true)] [SwaggerWcfTag("Authors")] [SwaggerWcfResponse(200, "Book found, author value in the response body")] [SwaggerWcfResponse(204, "Book found, author value in the response body")] [SwaggerWcfResponse(404, "Book not found", true)] [SwaggerWcfResponse(500, "Internal error (can be forced using ERROR_500 as book id)", true)] public Book[] ReadAuthorBooks(string id) { WebOperationContext woc = WebOperationContext.Current; if (woc == null) return null; Author author = Store.Authors.FirstOrDefault(b => b.Id == id); if (author != null) { Book[] books = Store.Books.Where(b => b.Author.Id == id).ToArray(); if (!books.Any()) { woc.OutgoingResponse.StatusCode = HttpStatusCode.NoContent; return null; } woc.OutgoingResponse.StatusCode = HttpStatusCode.OK; return books; } if (id == "ERROR_500") { woc.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError; return null; } woc.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; return null; } #endregion #region /languages [SwaggerWcfHidden] [SwaggerWcfTag("Languages")] [SwaggerWcfResponse(201, "Language created, value in the response body with id updated")] [SwaggerWcfResponse(400, "Bad request", true)] [SwaggerWcfResponse(500, "Internal error (can be forced using ERROR_500 as language name)", true)] public Language CreateLanguage(Language value) { throw new NotImplementedException(); } [SwaggerWcfHidden] [SwaggerWcfTag("Languages")] [SwaggerWcfResponse(200, "Language found, value in the response body")] [SwaggerWcfResponse(404, "Language not found", true)] [SwaggerWcfResponse(500, "Internal error (can be forced using ERROR_500 as language id)", true)] public Language ReadLanguage(string id) { throw new NotImplementedException(); } [SwaggerWcfTag("Languages")] [SwaggerWcfResponse(200, "Language found, value in the response body")] [SwaggerWcfResponse(204, "No languages", true)] public Language[] ReadLanguages() { WebOperationContext woc = WebOperationContext.Current; if (woc == null) return null; woc.OutgoingResponse.StatusCode = HttpStatusCode.OK; return Enum.GetValues(typeof(Language)).Cast().ToArray(); } [SwaggerWcfHidden] [SwaggerWcfTag("Languages")] [SwaggerWcfResponse(204, "Language updated")] [SwaggerWcfResponse(400, "Bad request")] [SwaggerWcfResponse(404, "Language not found")] [SwaggerWcfResponse(500, "Internal error (can be forced using ERROR_500 as language id)")] public void UpdateLanguage(string id, Language value) { throw new NotImplementedException(); } [SwaggerWcfHidden] [SwaggerWcfTag("Languages")] [SwaggerWcfResponse(204, "Language deleted")] [SwaggerWcfResponse(404, "Language not found")] [SwaggerWcfResponse(500, "Internal error (can be forced using ERROR_500 as language id)")] public void DeleteLanguage(string id) { throw new NotImplementedException(); } #endregion } } ================================================ FILE: src/SwaggerWcf.Test.Service/SwaggerWcf.Test.Service.csproj ================================================  Debug AnyCPU 2.0 {FD02752A-614D-4FAF-8994-519C754107B1} {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} Library Properties SwaggerWcf.Test.Service SwaggerWcf.Test.Service v4.5 True true true true full false bin\ DEBUG;TRACE prompt 4 pdbonly true bin\ TRACE prompt 4 Store.svc Global.asax Web.config Web.config {0ad6efbc-412f-4c0e-8e0a-0faf28151b55} SwaggerWcf 10.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) True True 52331 / http://localhost:52331/ False False False ================================================ FILE: src/SwaggerWcf.Test.Service/SwaggerWcf.Test.Service.csproj.DotSettings ================================================  CSharp70 ================================================ FILE: src/SwaggerWcf.Test.Service/Web.Debug.config ================================================ ================================================ FILE: src/SwaggerWcf.Test.Service/Web.Release.config ================================================ ================================================ FILE: src/SwaggerWcf.Test.Service/Web.config ================================================  ================================================ FILE: src/SwaggerWcf.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.24720.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SwaggerWcf", "SwaggerWcf\SwaggerWcf.csproj", "{0AD6EFBC-412F-4C0E-8E0A-0FAF28151B55}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{479EF2BE-93C9-4DE8-ACDD-538BB2203DB4}" ProjectSection(SolutionItems) = preProject ..\README.md = ..\README.md ..\notes\spec-2.0.md = ..\notes\spec-2.0.md EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SwaggerWcf.Test.Service", "SwaggerWcf.Test.Service\SwaggerWcf.Test.Service.csproj", "{FD02752A-614D-4FAF-8994-519C754107B1}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {0AD6EFBC-412F-4C0E-8E0A-0FAF28151B55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0AD6EFBC-412F-4C0E-8E0A-0FAF28151B55}.Debug|Any CPU.Build.0 = Debug|Any CPU {0AD6EFBC-412F-4C0E-8E0A-0FAF28151B55}.Release|Any CPU.ActiveCfg = Release|Any CPU {0AD6EFBC-412F-4C0E-8E0A-0FAF28151B55}.Release|Any CPU.Build.0 = Release|Any CPU {FD02752A-614D-4FAF-8994-519C754107B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FD02752A-614D-4FAF-8994-519C754107B1}.Debug|Any CPU.Build.0 = Debug|Any CPU {FD02752A-614D-4FAF-8994-519C754107B1}.Release|Any CPU.ActiveCfg = Release|Any CPU {FD02752A-614D-4FAF-8994-519C754107B1}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: src/SwaggerWcf.sln.DotSettings ================================================  UI WCF ================================================ FILE: src/packages/.gitignore ================================================ * !repositories.config !.gitignore ================================================ FILE: src/packages/repositories.config ================================================