From 303e2215d03a467a064fba4b2ea50cd27540773d Mon Sep 17 00:00:00 2001 From: Johannes Bader Date: Wed, 30 Aug 2017 10:57:56 -0700 Subject: [PATCH] consolidate doc with autorest repo (#1440) --- .../x-ms-code-generation-settings/rawcode.txt | 609 ------------- .../x-ms-code-generation-settings/readme.md | 14 - .../x-ms-code-generation-settings.yaml | 40 - .../x-ms-discriminator-value/rawcode.txt | 499 ----------- .../x-ms-discriminator-value/readme.md | 18 - .../x-ms-discriminator.yaml | 70 -- .../x-ms-parameterized-host.json | 61 -- documentation/swagger-extensions.md | 839 +----------------- 8 files changed, 2 insertions(+), 2148 deletions(-) delete mode 100644 documentation/swagger-extensions-examples/x-ms-code-generation-settings/rawcode.txt delete mode 100644 documentation/swagger-extensions-examples/x-ms-code-generation-settings/readme.md delete mode 100644 documentation/swagger-extensions-examples/x-ms-code-generation-settings/x-ms-code-generation-settings.yaml delete mode 100644 documentation/swagger-extensions-examples/x-ms-discriminator-value/rawcode.txt delete mode 100644 documentation/swagger-extensions-examples/x-ms-discriminator-value/readme.md delete mode 100644 documentation/swagger-extensions-examples/x-ms-discriminator-value/x-ms-discriminator.yaml delete mode 100644 documentation/swagger-extensions-examples/x-ms-parameterized-host/x-ms-parameterized-host.json diff --git a/documentation/swagger-extensions-examples/x-ms-code-generation-settings/rawcode.txt b/documentation/swagger-extensions-examples/x-ms-code-generation-settings/rawcode.txt deleted file mode 100644 index c3accead246d..000000000000 --- a/documentation/swagger-extensions-examples/x-ms-code-generation-settings/rawcode.txt +++ /dev/null @@ -1,609 +0,0 @@ -// -// GeneratedCode\PetStoreInc.cs -// - -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. - -namespace Test -{ - using System.Linq; - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Models; - - /// - /// Pets online. - /// - public partial class PetStoreInc : Microsoft.Rest.ServiceClient, IPetStoreInc, IAzureClient - { - /// - /// The base URI of the service. - /// - internal string BaseUri {get; set;} - - /// - /// Gets or sets json serialization settings. - /// - public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } - - /// - /// Gets or sets json deserialization settings. - /// - public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } - - /// - /// Credentials needed for the client to connect to Azure. - /// - public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; } - - /// - /// Gets or sets the preferred language for the response. - /// - public string AcceptLanguage { get; set; } - - /// - /// Gets or sets the retry timeout in seconds for Long Running Operations. - /// Default value is 30. - /// - public int? LongRunningOperationRetryTimeout { get; set; } - - /// - /// When set to true a unique x-ms-client-request-id value is generated and - /// included in each request. Default is true. - /// - public bool? GenerateClientRequestId { get; set; } - - /// - /// Gets the IPetOperations. - /// - public virtual IPetOperations Pet { get; private set; } - - /// - /// Initializes a new instance of the PetStoreInc class. - /// - /// - /// Optional. The delegating handlers to add to the http client pipeline. - /// - protected PetStoreInc(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) - { - this.Initialize(); - } - - /// - /// Initializes a new instance of the PetStoreInc class. - /// - /// - /// Optional. The http client handler used to handle http transport. - /// - /// - /// Optional. The delegating handlers to add to the http client pipeline. - /// - protected PetStoreInc(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) - { - this.Initialize(); - } - - /// - /// Initializes a new instance of the PetStoreInc class. - /// - /// - /// Required. Credentials needed for the client to connect to Azure. - /// - /// - /// Optional. The delegating handlers to add to the http client pipeline. - /// - /// - /// Thrown when a required parameter is null - /// - public PetStoreInc(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) - { - if (credentials == null) - { - throw new System.ArgumentNullException("credentials"); - } - this.Credentials = credentials; - if (this.Credentials != null) - { - this.Credentials.InitializeServiceClient(this); - } - } - - /// - /// Initializes a new instance of the PetStoreInc class. - /// - /// - /// Required. Credentials needed for the client to connect to Azure. - /// - /// - /// Optional. The http client handler used to handle http transport. - /// - /// - /// Optional. The delegating handlers to add to the http client pipeline. - /// - /// - /// Thrown when a required parameter is null - /// - public PetStoreInc(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) - { - if (credentials == null) - { - throw new System.ArgumentNullException("credentials"); - } - this.Credentials = credentials; - if (this.Credentials != null) - { - this.Credentials.InitializeServiceClient(this); - } - } - - /// - /// An optional partial-method to perform custom initialization. - /// - partial void CustomInitialize(); - /// - /// Initializes client properties. - /// - private void Initialize() - { - this.Pet = new PetOperations(this); - this.BaseUri = "http://localhost"; - this.AcceptLanguage = "en-US"; - this.LongRunningOperationRetryTimeout = 30; - this.GenerateClientRequestId = true; - SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings - { - Formatting = Newtonsoft.Json.Formatting.Indented, - DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, - DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, - NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, - ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, - ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), - Converters = new System.Collections.Generic.List - { - new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() - } - }; - DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings - { - DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, - DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, - NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, - ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, - ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), - Converters = new System.Collections.Generic.List - { - new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() - } - }; - CustomInitialize(); - DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter()); - } - } -} - - - -// -// GeneratedCode\IPetStoreInc.cs -// - -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. - -namespace Test -{ - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Models; - - /// - /// Pets online. - /// - public partial interface IPetStoreInc : System.IDisposable - { - /// - /// The base URI of the service. - /// - - /// - /// Gets or sets json serialization settings. - /// - Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; } - - /// - /// Gets or sets json deserialization settings. - /// - Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; } - - /// - /// Credentials needed for the client to connect to Azure. - /// - Microsoft.Rest.ServiceClientCredentials Credentials { get; } - - /// - /// Gets or sets the preferred language for the response. - /// - string AcceptLanguage { get; set; } - - /// - /// Gets or sets the retry timeout in seconds for Long Running - /// Operations. Default value is 30. - /// - int? LongRunningOperationRetryTimeout { get; set; } - - /// - /// When set to true a unique x-ms-client-request-id value is generated - /// and included in each request. Default is true. - /// - bool? GenerateClientRequestId { get; set; } - - - /// - /// Gets the IPetOperations. - /// - IPetOperations Pet { get; } - - } -} - - - -// -// GeneratedCode\PetOperations.cs -// - -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. - -namespace Test -{ - using System.Linq; - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Models; - - /// - /// PetOperations operations. - /// - internal partial class PetOperations : Microsoft.Rest.IServiceOperations, IPetOperations - { - /// - /// Initializes a new instance of the PetOperations class. - /// - /// - /// Reference to the service client. - /// - /// - /// Thrown when a required parameter is null - /// - internal PetOperations(PetStoreInc client) - { - if (client == null) - { - throw new System.ArgumentNullException("client"); - } - this.Client = client; - } - - /// - /// Gets a reference to the PetStoreInc - /// - public PetStoreInc Client { get; private set; } - - /// - /// Gets pets by id. - /// - /// - /// pet id - /// - /// - /// Headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// A response object containing the response body and response headers. - /// - public async System.Threading.Tasks.Task> GetPetByIdWithHttpMessagesAsync(string petId, System.Collections.Generic.Dictionary> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) - { - if (petId == null) - { - throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "petId"); - } - // Tracing - bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; - string _invocationId = null; - if (_shouldTrace) - { - _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); - System.Collections.Generic.Dictionary tracingParameters = new System.Collections.Generic.Dictionary(); - tracingParameters.Add("petId", petId); - tracingParameters.Add("cancellationToken", cancellationToken); - Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetPetById", tracingParameters); - } - // Construct URL - var _baseUrl = this.Client.BaseUri; - var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "Pets/{petId}/GetPet"; - _url = _url.Replace("{petId}", System.Uri.EscapeDataString(petId)); - System.Collections.Generic.List _queryParameters = new System.Collections.Generic.List(); - if (_queryParameters.Count > 0) - { - _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); - } - // Create HTTP transport objects - var _httpRequest = new System.Net.Http.HttpRequestMessage(); - System.Net.Http.HttpResponseMessage _httpResponse = null; - _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); - _httpRequest.RequestUri = new System.Uri(_url); - // Set Headers - if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) - { - _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); - } - if (this.Client.AcceptLanguage != null) - { - if (_httpRequest.Headers.Contains("accept-language")) - { - _httpRequest.Headers.Remove("accept-language"); - } - _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); - } - if (customHeaders != null) - { - foreach(var _header in customHeaders) - { - if (_httpRequest.Headers.Contains(_header.Key)) - { - _httpRequest.Headers.Remove(_header.Key); - } - _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); - } - } - - // Serialize Request - string _requestContent = null; - // Set Credentials - if (this.Client.Credentials != null) - { - cancellationToken.ThrowIfCancellationRequested(); - await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - } - // Send Request - if (_shouldTrace) - { - Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); - } - cancellationToken.ThrowIfCancellationRequested(); - _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - if (_shouldTrace) - { - Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); - } - System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; - cancellationToken.ThrowIfCancellationRequested(); - string _responseContent = null; - if ((int)_statusCode != 200) - { - var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); - try - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); - if (_errorBody != null) - { - ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); - ex.Body = _errorBody; - } - } - catch (Newtonsoft.Json.JsonException) - { - // Ignore the exception - } - ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); - ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); - if (_httpResponse.Headers.Contains("x-ms-request-id")) - { - ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); - } - if (_shouldTrace) - { - Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); - } - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw ex; - } - // Create Result - var _result = new Microsoft.Rest.Azure.AzureOperationResponse(); - _result.Request = _httpRequest; - _result.Response = _httpResponse; - if (_httpResponse.Headers.Contains("x-ms-request-id")) - { - _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); - } - // Deserialize Response - if ((int)_statusCode == 200) - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - try - { - _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); - } - catch (Newtonsoft.Json.JsonException ex) - { - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); - } - } - if (_shouldTrace) - { - Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); - } - return _result; - } - - } -} - - - -// -// GeneratedCode\IPetOperations.cs -// - -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. - -namespace Test -{ - using Microsoft.Rest.Azure; - using Models; - - /// - /// PetOperations operations. - /// - public partial interface IPetOperations - { - /// - /// Gets pets by id. - /// - /// - /// pet id - /// - /// - /// The headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - System.Threading.Tasks.Task> GetPetByIdWithHttpMessagesAsync(string petId, System.Collections.Generic.Dictionary> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); - } -} - - - -// -// GeneratedCode\PetOperationsExtensions.cs -// - -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. - -namespace Test -{ - using System.Threading.Tasks; - using Microsoft.Rest.Azure; - using Models; - - /// - /// Extension methods for PetOperations. - /// - public static partial class PetOperationsExtensions - { - /// - /// Gets pets by id. - /// - /// - /// The operations group for this extension method. - /// - /// - /// pet id - /// - public static object GetPetById(this IPetOperations operations, string petId) - { - return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPetOperations)s).GetPetByIdAsync(petId), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); - } - - /// - /// Gets pets by id. - /// - /// - /// The operations group for this extension method. - /// - /// - /// pet id - /// - /// - /// The cancellation token. - /// - public static async System.Threading.Tasks.Task GetPetByIdAsync(this IPetOperations operations, string petId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) - { - using (var _result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false)) - { - return _result.Body; - } - } - - } -} - - - -// -// GeneratedCode\Models\Pet.cs -// - -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. - -namespace Test.Models -{ - using System.Linq; - - public partial class Pet - { - /// - /// Initializes a new instance of the Pet class. - /// - public Pet() { } - - /// - /// Initializes a new instance of the Pet class. - /// - /// Gets the Pet by id. - public Pet(string name = default(string)) - { - Name = name; - } - - /// - /// Gets the Pet by id. - /// - [Newtonsoft.Json.JsonProperty(PropertyName = "name")] - public string Name { get; private set; } - - } -} \ No newline at end of file diff --git a/documentation/swagger-extensions-examples/x-ms-code-generation-settings/readme.md b/documentation/swagger-extensions-examples/x-ms-code-generation-settings/readme.md deleted file mode 100644 index 8c01c07b4d22..000000000000 --- a/documentation/swagger-extensions-examples/x-ms-code-generation-settings/readme.md +++ /dev/null @@ -1,14 +0,0 @@ -# x-ms-code-generation-settings -The x-ms-code-generation-settings allows options like code headers, date-time offset and generating internal constructors for the operations - -### Example -Consider the petstore example as described in [x-ms-discriminator.yaml]() The service Pet_GetPetById takes in the id in of the pet and gets details about it. The code generated will have internal constructors when the corresponding flag is set to "true" - - - -``` -internal PetOperations(PetStoreInc client) -{ - if (client == null) - { -``` \ No newline at end of file diff --git a/documentation/swagger-extensions-examples/x-ms-code-generation-settings/x-ms-code-generation-settings.yaml b/documentation/swagger-extensions-examples/x-ms-code-generation-settings/x-ms-code-generation-settings.yaml deleted file mode 100644 index f852f55a9491..000000000000 --- a/documentation/swagger-extensions-examples/x-ms-code-generation-settings/x-ms-code-generation-settings.yaml +++ /dev/null @@ -1,40 +0,0 @@ ---- -swagger: '2.0' -info: - title: PetStore Inc. - description: Pets online. - version: 0.0.0 - x-ms-code-generation-settings: - useDateTimeOffset: true - internalConstructors: true -x-ms-parameterized-host: - hostTemplate: "{petBaseUrl}" - parameters: - - name: petBaseUrl - required: true - type: string - in: path - x-ms-skip-url-encoding: true -paths: - "/Pets/{petId}/GetPet": - post: - operationId: Pet_GetPetById - description: Gets pets by id. - parameters: - - name: petId - in: path - required: true - type: string - description: pet id - responses: - '200': - description: '' - schema: - "$ref": "#/definitions/Pet" -definitions: - Pet: - properties: - name: - type: string - readOnly: true - description: Gets the Pet by id. \ No newline at end of file diff --git a/documentation/swagger-extensions-examples/x-ms-discriminator-value/rawcode.txt b/documentation/swagger-extensions-examples/x-ms-discriminator-value/rawcode.txt deleted file mode 100644 index 75947129a1a7..000000000000 --- a/documentation/swagger-extensions-examples/x-ms-discriminator-value/rawcode.txt +++ /dev/null @@ -1,499 +0,0 @@ -// -// GeneratedCode\SwaggerPetstore.cs -// - -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. - -namespace Test -{ - using Microsoft.Rest; - using Models; - - public partial class SwaggerPetstore : Microsoft.Rest.ServiceClient, ISwaggerPetstore - { - /// - /// The base URI of the service. - /// - public System.Uri BaseUri { get; set; } - - /// - /// Gets or sets json serialization settings. - /// - public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } - - /// - /// Gets or sets json deserialization settings. - /// - public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } - - /// - /// Initializes a new instance of the SwaggerPetstore class. - /// - /// - /// Optional. The delegating handlers to add to the http client pipeline. - /// - public SwaggerPetstore(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) - { - this.Initialize(); - } - - /// - /// Initializes a new instance of the SwaggerPetstore class. - /// - /// - /// Optional. The http client handler used to handle http transport. - /// - /// - /// Optional. The delegating handlers to add to the http client pipeline. - /// - public SwaggerPetstore(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) - { - this.Initialize(); - } - - /// - /// Initializes a new instance of the SwaggerPetstore class. - /// - /// - /// Optional. The base URI of the service. - /// - /// - /// Optional. The delegating handlers to add to the http client pipeline. - /// - /// - /// Thrown when a required parameter is null - /// - public SwaggerPetstore(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) - { - if (baseUri == null) - { - throw new System.ArgumentNullException("baseUri"); - } - this.BaseUri = baseUri; - } - - /// - /// Initializes a new instance of the SwaggerPetstore class. - /// - /// - /// Optional. The base URI of the service. - /// - /// - /// Optional. The http client handler used to handle http transport. - /// - /// - /// Optional. The delegating handlers to add to the http client pipeline. - /// - /// - /// Thrown when a required parameter is null - /// - public SwaggerPetstore(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) - { - if (baseUri == null) - { - throw new System.ArgumentNullException("baseUri"); - } - this.BaseUri = baseUri; - } - - /// - /// An optional partial-method to perform custom initialization. - /// - partial void CustomInitialize(); - /// - /// Initializes client properties. - /// - private void Initialize() - { - this.BaseUri = new System.Uri("https://petstore.swagger.io/v1"); - SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings - { - Formatting = Newtonsoft.Json.Formatting.Indented, - DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, - DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, - NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, - ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, - ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), - Converters = new System.Collections.Generic.List - { - new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() - } - }; - DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings - { - DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, - DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, - NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, - ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, - ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), - Converters = new System.Collections.Generic.List - { - new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() - } - }; - SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicSerializeJsonConverter("petKind")); - DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicDeserializeJsonConverter("petKind")); - CustomInitialize(); - } - /// - /// Add a pet - /// - /// - /// Headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// A response object containing the response body and response headers. - /// - public async System.Threading.Tasks.Task AddPetWithHttpMessagesAsync(System.Collections.Generic.Dictionary> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) - { - // Tracing - bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; - string _invocationId = null; - if (_shouldTrace) - { - _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); - System.Collections.Generic.Dictionary tracingParameters = new System.Collections.Generic.Dictionary(); - tracingParameters.Add("cancellationToken", cancellationToken); - Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "AddPet", tracingParameters); - } - // Construct URL - var _baseUrl = this.BaseUri.AbsoluteUri; - var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pets").ToString(); - // Create HTTP transport objects - var _httpRequest = new System.Net.Http.HttpRequestMessage(); - System.Net.Http.HttpResponseMessage _httpResponse = null; - _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); - _httpRequest.RequestUri = new System.Uri(_url); - // Set Headers - if (customHeaders != null) - { - foreach(var _header in customHeaders) - { - if (_httpRequest.Headers.Contains(_header.Key)) - { - _httpRequest.Headers.Remove(_header.Key); - } - _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); - } - } - - // Serialize Request - string _requestContent = null; - // Send Request - if (_shouldTrace) - { - Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); - } - cancellationToken.ThrowIfCancellationRequested(); - _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - if (_shouldTrace) - { - Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); - } - System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; - cancellationToken.ThrowIfCancellationRequested(); - string _responseContent = null; - if ((int)_statusCode != 200) - { - var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); - if (_httpResponse.Content != null) { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - } - else { - _responseContent = string.Empty; - } - ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); - ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); - if (_shouldTrace) - { - Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); - } - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw ex; - } - // Create Result - var _result = new Microsoft.Rest.HttpOperationResponse(); - _result.Request = _httpRequest; - _result.Response = _httpResponse; - if (_shouldTrace) - { - Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); - } - return _result; - } - - } -} - - - -// -// GeneratedCode\ISwaggerPetstore.cs -// - -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. - -namespace Test -{ - using Models; - - /// - /// - public partial interface ISwaggerPetstore : System.IDisposable - { - /// - /// The base URI of the service. - /// - System.Uri BaseUri { get; set; } - - /// - /// Gets or sets json serialization settings. - /// - Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; } - - /// - /// Gets or sets json deserialization settings. - /// - Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; } - - - /// - /// Add a pet - /// - /// - /// The headers that will be added to request. - /// - /// - /// The cancellation token. - /// - System.Threading.Tasks.Task AddPetWithHttpMessagesAsync(System.Collections.Generic.Dictionary> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); - - } -} - - - -// -// GeneratedCode\SwaggerPetstoreExtensions.cs -// - -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. - -namespace Test -{ - using System.Threading.Tasks; - using Models; - - /// - /// Extension methods for SwaggerPetstore. - /// - public static partial class SwaggerPetstoreExtensions - { - /// - /// Add a pet - /// - /// - /// The operations group for this extension method. - /// - public static void AddPet(this ISwaggerPetstore operations) - { - System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstore)s).AddPetAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); - } - - /// - /// Add a pet - /// - /// - /// The operations group for this extension method. - /// - /// - /// The cancellation token. - /// - public static async System.Threading.Tasks.Task AddPetAsync(this ISwaggerPetstore operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) - { - await operations.AddPetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); - } - - } -} - - - -// -// GeneratedCode\Models\Pet.cs -// - -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. - -namespace Test.Models -{ - using System.Linq; - - public partial class Pet - { - /// - /// Initializes a new instance of the Pet class. - /// - public Pet() { } - - /// - /// Initializes a new instance of the Pet class. - /// - public Pet(string petType) - { - PetType = petType; - } - - /// - /// - [Newtonsoft.Json.JsonProperty(PropertyName = "petType")] - public string PetType { get; set; } - - /// - /// Validate the object. - /// - /// - /// Thrown if validation fails - /// - public virtual void Validate() - { - if (PetType == null) - { - throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "PetType"); - } - } - } -} - - - -// -// GeneratedCode\Models\Cat.cs -// - -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. - -namespace Test.Models -{ - using System.Linq; - - /// - /// A representation of a cat - /// - [Newtonsoft.Json.JsonObject("Microsoft.PetStore.PetType")] - public partial class Cat : Pet - { - /// - /// Initializes a new instance of the Cat class. - /// - public Cat() { } - - /// - /// Initializes a new instance of the Cat class. - /// - /// The measured skill for hunting. Possible - /// values include: 'clueless', 'lazy', 'adventurous', - /// 'aggressive' - public Cat(string petType, string huntingSkill = default(string)) - : base(petType) - { - HuntingSkill = huntingSkill; - } - - /// - /// Gets or sets the measured skill for hunting. Possible values - /// include: 'clueless', 'lazy', 'adventurous', 'aggressive' - /// - [Newtonsoft.Json.JsonProperty(PropertyName = "huntingSkill")] - public string HuntingSkill { get; set; } - - /// - /// Validate the object. - /// - /// - /// Thrown if validation fails - /// - public override void Validate() - { - base.Validate(); - } - } -} - - - -// -// GeneratedCode\Models\Dog.cs -// - -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. - -namespace Test.Models -{ - using System.Linq; - - /// - /// A representation of a dog - /// - [Newtonsoft.Json.JsonObject("Microsoft.PetStore.PetType")] - public partial class Dog : Pet - { - /// - /// Initializes a new instance of the Dog class. - /// - public Dog() { } - - /// - /// Initializes a new instance of the Dog class. - /// - /// the size of the pack the dog is from - public Dog(string petType, int? packSize = default(int?)) - : base(petType) - { - PackSize = packSize; - } - - /// - /// Gets or sets the size of the pack the dog is from - /// - [Newtonsoft.Json.JsonProperty(PropertyName = "packSize")] - public int? PackSize { get; set; } - - /// - /// Validate the object. - /// - /// - /// Thrown if validation fails - /// - public override void Validate() - { - base.Validate(); - if (this.PackSize < 0) - { - throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.InclusiveMinimum, "PackSize", 0); - } - } - } -} diff --git a/documentation/swagger-extensions-examples/x-ms-discriminator-value/readme.md b/documentation/swagger-extensions-examples/x-ms-discriminator-value/readme.md deleted file mode 100644 index 8532ea1a177f..000000000000 --- a/documentation/swagger-extensions-examples/x-ms-discriminator-value/readme.md +++ /dev/null @@ -1,18 +0,0 @@ -# x-ms-discriminator-value -The x-ms-discriminator-value extension is an add-on to the discriminator feature in swagger. This allows us to provide an alias for the base class type using which one can polymorphically capture from the data. For a detailed explanation about polymorphism in swagger, click [here](https://gist.github.com/leedm777/5730877#polymorphism) - -### Example -Consider the petstore example as described in [x-ms-discriminator.yaml]() The service addPet accepts any model of the kind "petKind". The model "Pet" is inherited by models "Cat" and "Dog" which in turn specify the x-ms-discriminator-value as "Microsoft.PetStore.PetType". This translates as types "Cat" and "Dog" will be polymorphically represented by "Microsoft.PetStore.PetType" instead of "petKind" - - - -``` -[Newtonsoft.Json.JsonObject("Microsoft.PetStore.PetType")] -public partial class Dog : Pet -{ -``` - -### When to use -At times the base class type name may not accurately describe the kind of data you are trying to pass/receive and needs to have a more verbose/different string to represent it. -Conversely certain base types, which may be x-ms-external may have quite a long name and may need to be shortened for better readability in the client code. -In either case, x-ms-discriminator-value is a useful option \ No newline at end of file diff --git a/documentation/swagger-extensions-examples/x-ms-discriminator-value/x-ms-discriminator.yaml b/documentation/swagger-extensions-examples/x-ms-discriminator-value/x-ms-discriminator.yaml deleted file mode 100644 index 94657c83533b..000000000000 --- a/documentation/swagger-extensions-examples/x-ms-discriminator-value/x-ms-discriminator.yaml +++ /dev/null @@ -1,70 +0,0 @@ ---- -swagger: '2.0' -info: - version: 1.0.0 - title: Swagger Petstore - license: - name: MIT -host: petstore.swagger.io -basePath: "/v1" -schemes: -- https -consumes: -- application/json -produces: -- application/json -paths: - "/pets": - put: - summary: Add a pet - operationId: addPet - tags: - - pets - parameters: - - schema: - "$ref": "#/definitions/Pet" - responses: - '200': - description: OK -definitions: - Pet: - properties: - petKind: - type: string - name: - type: string - discriminator: petKind - required: - - name - - petType - Cat: - description: A representation of a cat - x-ms-discriminator-value: Microsoft.PetStore.PetType - 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 - x-ms-discriminator-value: Microsoft.PetStore.PetType - 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 diff --git a/documentation/swagger-extensions-examples/x-ms-parameterized-host/x-ms-parameterized-host.json b/documentation/swagger-extensions-examples/x-ms-parameterized-host/x-ms-parameterized-host.json deleted file mode 100644 index 4115c9c76572..000000000000 --- a/documentation/swagger-extensions-examples/x-ms-parameterized-host/x-ms-parameterized-host.json +++ /dev/null @@ -1,61 +0,0 @@ ---- -swagger: '2.0' -info: - version: 1.0.0 - title: Swagger Petstore - license: - name: MIT -x-ms-parameterized-host: - hostTemplate: "{petStoreBaseUrl}" - useSchemePrefix: false - positionInOperation: last - parameters: - - name: petStoreBaseUrl - description: PetStore base url eg. https://mydomain.petstore - required: true - type: string - in: path - x-ms-skip-url-encoding: true -schemes: -- https -consumes: -- application/json -produces: -- application/json -paths: - "/pets/{opsPath}/{serverLoc}": - put: - description: Add a pet - summary: Add a pet - operationId: addPet - tags: - - pets - parameters: - - name: petReq - in: body - required: true - schema: - "$ref": "#/definitions/Pet" - - name: opsPath - in: path - required: true - type: string - - name: serverLoc - in: path - required: true - type: string - responses: - '200': - description: OK -definitions: - Pet: - description: The pet model - properties: - name: - type: string - petType: - type: string - discriminator: name - required: - - name - - petType diff --git a/documentation/swagger-extensions.md b/documentation/swagger-extensions.md index 98abd2eaa0c0..e9c051e4509f 100644 --- a/documentation/swagger-extensions.md +++ b/documentation/swagger-extensions.md @@ -1,838 +1,3 @@ +# AutoRest Extensions for OpenAPI 2.0 -# AutoRest Extensions for Swagger 2.0 - -## Introduction -The following documents describes AutoRest specific vendor extensions for [Swagger 2.0](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md) schema. Some of the extensions are only applicable to Microsoft Azure and as such are only available in Azure code generators (e.g. Azure.CSharp, Azure.NodeJS, etc.). - -## Generic Extensions -* [x-ms-code-generation-settings](#x-ms-code-generation-settings) - enables passing code generation settings via swagger document -* [x-ms-skip-url-encoding](#x-ms-skip-url-encoding) - skips URL encoding for path and query parameters -* [x-ms-enum](#x-ms-enum) - additional metadata for enums -* [x-ms-parameter-grouping](#x-ms-parameter-grouping) - groups method parameters in generated clients -* [x-ms-parameter-location](#x-ms-parameter-location) - provides a mechanism to specify that the global parameter is actually a parameter on the operation and not a client property. -* [x-ms-paths](#x-ms-paths) - alternative to [Paths Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#pathsObject) that allows [Path Item Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#pathItemObject) to have query parameters for non pure REST APIs -* [x-ms-client-name](#x-ms-client-name) - allows control over identifier names used in client-side code generation for parameters and schema properties. -* [x-ms-external](#x-ms-external) - allows specific [Definition Objects](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#definitionsObject) to be excluded from code generation -* [x-ms-discriminator-value](#x-ms-discriminator-value) - maps discriminator value on the wire with the definition name. -* [x-ms-client-flatten](#x-ms-client-flatten) - flattens client model property or parameter. -* [x-ms-parameterized-host](#x-ms-parameterized-host) - replaces the Swagger host with a host template that can be replaced with variable parameters. -* [x-ms-examples](#x-ms-examples) - describes the format for specifying examples for request and response of an operation in a swagger spec. - -## Microsoft Azure Extensions -* [x-ms-odata](#x-ms-odata) - indicates the operation includes one or more [OData](http://www.odata.org/) query parameters. -* [x-ms-pageable](#x-ms-pageable) - allows paging through lists of data. -* [x-ms-long-running-operation](#x-ms-long-running-operation) - indicates that the operation implemented Long Running Operation pattern as defined by the [Resource Managemer API](https://msdn.microsoft.com/en-us/library/azure/dn790568.aspx). -* [x-ms-azure-resource](#x-ms-azure-resource) - indicates that the [Definition Schema Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#schemaObject) is a resource as defined by the [Resource Managemer API](https://msdn.microsoft.com/en-us/library/azure/dn790568.aspx) -* [x-ms-request-id](#x-ms-request-id) - allows to overwrite the request id header name -* [x-ms-client-request-id](#x-ms-client-request-id) - allows to overwrite the client request id header name - -## x-ms-code-generation-settings -`x-ms-code-generation-settings` extension on `info` element enables passing code generation settings via swagger document. - -**Parent element**: [Info Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#infoObject) - -**Schema**: - -Field Name | Type | Description ----|:---:|--- -.*| `string` or `bool` | **Required**. Field name should be a valid autorest.exe parameter. Value should be a valid string value or boolean for flag parameters - -**Example**: -```js -"info": { - "x-ms-code-generation-settings": { - "header": "MIT", - "internalConstructors": true, - "useDateTimeOffset": true - } -} -``` - -## x-ms-skip-url-encoding -By default, `path` parameters will be URL-encoded automatically. This is a good default choice for user-provided values. This is not a good choice when the parameter is provided from a source where the value is known to be URL-encoded. The URL encoding is NOT an idempotent operation. For example, the percent character "%" is URL-encoded as "%25". If the parameter is URL-encoded again, "%25" becomes "%2525". Mark parameters where the source is KNOWN to be URL-encoded to prevent the automatic encoding behavior. - -**Parent element**: [Parameter Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#parameterObject) - -**Schema**: -`true|false` - -**Example**: -```js -"parameters": [ - { - "name": "databaseName", - "in": "path", - "type": "string", - "required": true, - "x-ms-skip-url-encoding": true - } -] -``` - -## x-ms-enum -Enum definitions in Swagger indicate that only a particular set of values may be used for a property or parameter. When the property is represented on the wire as a string, it would be a natural choice to represent the property type in C# and Java as an enum. However, not all enumeration values should necessarily be represented as strongly typed enums - there are additional considerations, such as how often expected values might change, since adding a new value to a strongly typed enum is a breaking change requiring an updated API version. Additionally, there is some metadata that is required to create a useful enum, such as a descriptive name, which is not represented in swagger. For this reason, enums are not automatically turned into strongly typed enum types - instead they are rendered in the documentation comments for the property or parameter to indicate allowed values. To indicate that an enum will rarely change and that C#/Java enum semantics are desired, use the `x-ms-enum` exension. Note that depending on the code generation language the behavior of this extension may differ. - -In C# and Java, an enum type is generated and is declared as the type of the related request/response object. The enum is serialized as the string expected by the REST API. - -**Parent element**: [Parameter Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#parameterObject), [Schema Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#schemaObject), [Items Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#itemsObject), or [Header Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#headerObject) - -**Schema**: - -Field Name | Type | Description ----|:---:|--- -name | `string` | **Required**. Specifies the name for the Enum. -modelAsString | `boolean` | **Default: false** When set to `true` the enum will be modeled as a string. No validation will happen. When set to `false`, it will be modeled as an enum if that language supports enums. Validation will happen, irrespective of support of enums in that language. - -**Example**: -```js - "accountType": { - "type": "string", - "enum": [ - "Standard_LRS", - "Standard_ZRS", - "Standard_GRS", - "Standard_RAGRS", - "Premium_LRS" - ], - "x-ms-enum": { - "name": "AccountType", - "modelAsString": false - } - } -``` - -### Single value enum as a constant -- If the **single value** enum is a **required** model property or a **required** parameter then it is always treated as a constant. The `x-ms-enum` extension **is ignored**. - - Explanation: The above condition specifies that the server always expects the model property or the parameter and with a specific value. Hence, it makes sense to treat it as a constant. In the future, if more values are added to the enum then, it is a breaking change to the API provided by the client library. -- If the **single value** enum is an **optional** model property or an **optional** parameter and if `x-ms-enum` extension is provided then it will be honoured. - -## x-ms-parameter-grouping -By default operation parameters are generated in the client as method arguments. This behavior can sometimes be undesirable when the number of parameters is high. `x-ms-parameter-grouping` extension is used to group multiple primitive parameters into a composite type to improve the API. - -**Parent element**: [Parameter Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#parameterObject) - -**Schema**: - -Field Name | Type | Description ----|:---:|--- -name | `string` | When set, specifies the name for the composite type. -postfix | `string` | Alternative to `name` parameter. If specified the name of the composite type will be generated as follows `{MethodGroup}{Method}{Postfix}`. - -If none of the parameters are set the name of the composite type is generated as follows `{MethodGroup}{Method}Parameters`. - -**Example**: -```js -"/some/{pathParam1}/{pathParam2}": { - "operationId": "Update", - "post": { - "parameters": [ - { - "name": "headerParam", - "in": "header", - "type": "string", - "required": false, - "x-ms-parameter-grouping": { - "name": "custom-parameter-group" - } - }, - { - "name": "pathParam1", - "in": "path", - "type": "string", - "required": true, - "x-ms-parameter-grouping": { - "name": "custom-parameter-group" - } - }, - { - "name": "pathParam2", - "in": "path", - "type": "string", - "required": true, - "x-ms-parameter-grouping": { - "name": "custom-parameter-group" - } - }] - } -} -``` -Above Swagger schema will produce a type CustomParameterGroup with 3 properties (if applicable in the generator language). - -## x-ms-parameter-location - -By default Autorest processes global parameters as properties on the client. For example `subscriptionId` and `apiVersion` which are defined in the global parameters section end up being properties of the client. It would be natural to define resourceGroupName once in the global parameters section and then reference it everywhere, rather than repeating the same definition inline everywhere. One **may not** want resourceGroupName as a property on the client, just because it is defined in the global parameters section. This extension helps you achieve that. You can add this extension with value "method" -`"x-ms-parameter-location": "method"` and resourceGroupName will not be a client property. - -Note: -- Valid values for this extension are: **"client", "method"**. -- **This extension can only be applied on global parameters. If this is applied on any parameter in an operation then it will be ignored.** - -**Example:** -``` -{ - "swagger": "2.0", - "host": "management.azure.com", - "info": { - "title": "AwesomeClient", - "version": "2015-05-01" - }, - "paths": { - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}": { - "put": { - "operationId": "StorageAccounts_Create", - . . . - "parameters": [ - { - "$ref": "#/parameters/ResourceGroupName" <<<<<<<<<<<<<<<<<<<< - }, - { - "name": "accountName", - "in": "path", - "required": true, - "type": "string", - "description": "The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. " - }, - { - "name": "parameters", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/StorageAccountCreateParameters" - }, - "description": "The parameters to provide for the created account." - }, - { - "$ref": "#/parameters/ApiVersionParameter" - }, - { - "$ref": "#/parameters/SubscriptionIdParameter" - } - ] - . . . - } - } - }, - . . . - "parameters": { - "SubscriptionIdParameter": { - "name": "subscriptionId", - "in": "path", - "required": true, - "type": "string", - "description": "Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call." - }, - "ApiVersionParameter": { - "name": "api-version", - "in": "query", - "required": true, - "type": "string", - "description": "Client Api Version." - }, - "ResourceGroupName": { - "description": "The name of the resource group within the user’s subscription.", - "in": "path", - "name": "resourceGroupName", - "required": true, - "type": "string", - "x-ms-parameter-location": "method" <<<<<<<<<<<<<<<<<<<<<<<<<<< - } - } -} -``` - -- After using the `"x-ms-parameter-location": "method"` extension the generated client will have a method that looks like this: - - Notice that `resourceGroupName` is the method parameter and not a client property -```csharp -public static StorageAccount Create(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters); -``` -- The client constructor looks like this: -```csharp -public partial class StorageManagementClient : ServiceClient, IStorageManagementClient, IAzureClient -{ - - public string SubscriptionId { get; set; } //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< - - public string ApiVersion { get; private set; } //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< - - public StorageManagementClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) - { - if (baseUri == null) - { - throw new ArgumentNullException("baseUri"); - } - if (credentials == null) - { - throw new ArgumentNullException("credentials"); - } - this.Credentials = credentials; - if (this.Credentials != null) - { - this.Credentials.InitializeServiceClient(this); - } - } - - private void Initialize() - { - this.StorageAccounts = new StorageAccountsOperations(this); - this.Usage = new UsageOperations(this); - this.BaseUri = new Uri("https://management.azure.com"); - this.ApiVersion = "2016-01-01"; - . . . - } -} -``` -## x-ms-paths - -Swagger 2.0 has a built-in limitation on paths. Only one operation can be mapped to a path and http method. There are some APIs, however, where multiple distinct operations are mapped to the same path and same http method. For example `GET /mypath/query-drive?op=file` and `GET /mypath/query-drive?op=folder` may return two different model types (stream in the first example and JSON model representing Folder in the second). Since Swagger does not treat query parameters as part of the path the above 2 operations may not co-exist in the standard "paths" element. - -To overcome this limitation an "x-ms-paths" extension was introduced parallel to "paths". Urls under "x-ms-paths" are allowed to have query parameters for disambiguation, however they are removed during model parsing. - -**Parent element**: [Swagger Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#swaggerObject) - -**Schema**: -The `x-ms-paths` extension has the same schema as [Paths Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#pathsObject) with exception that [Path Item Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#pathItemObject) can have query parameters. - -**Example**: -```js -"paths":{ - "/pets": { - "get": { - "parameters": [ - { - "name": "name", - "required": true - } - ] - } - } -}, -"x-ms-paths":{ - "/pets?color={color}": { - "get": {} - }, -} -``` -## x-ms-client-name - -In some situations, data passed by name, such as query parameters, entity headers, or elements of a JSON document body, are not suitable for use in client-side code. -For example, a header like 'x-ms-version' would turn out like xMsVersion, or x_ms_version, or XMsVersion, depending on the preferences of a particular code generator. -It may be better to allow a code generator to use 'version' as the name of the parameter in client code. - -By using the 'x-ms-client-name' extension, a name can be defined for use specifically in code generation, separately from the name on the wire. -It can be used for query parameters and header parameters, as well as properties of schemas. - -**Parameter Example**: -```js - "parameters": { - "ApiVersionParameter": { - "name": "x-ms-version", - "x-ms-client-name": "version", - "in": "header", - "required": false, - "type": "string", - "x-ms-global": true, - "enum": [ - "2015-04-05", - "2014-02-14", - "2013-08-15", - "2012-02-12", - "2011-08-18", - "2009-09-19", - "2009-07-17", - "2009-04-14" - ], - "default": "2015-04-05", - "description": "Specifies the version of the operation to use for this request." - } -``` - -**Property Example**: -```js -{ - "definitions": { - "Product": { - "x-ms-external" : true, - "properties": { - "product_id": { - "type": "string" - "x-ms-client-name": "SKU" - } - } - } -} -``` - -## x-ms-external -To allow generated clients to share models via shared libraries an `x-ms-external` extension was introduced. When a [Definition Objects](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#definitionsObject) contains this extensions it's definition will be excluded from generated library. Note that in strongly typed languages the code will not compile unless the assembly containing the type is referenced with the project/library. - -**Parent element**: [Definition Objects](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#definitionsObject) - -**Schema**: -`true|false` - -**Example**: -```js -{ - "definitions": { - "Product": { - "x-ms-external" : true, - "properties": { - "product_id": { - "type": "string" - } - } - } -} -``` - -## x-ms-discriminator-value -Swagger 2.0 specification requires that when used, the value of `discriminator` field MUST match the name of the schema or any schema that inherits it. To overcome this limitation `x-ms-discriminator-value` extension was introduced. - -**Schema**: -`string` - the expected value of the `discriminator` field on the wire. - -**Parent element**: [Schema Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#schemaObject) - -**Example**: -```js -"definitions": { - "SqlDefinition": { - "x-ms-discriminator-value": "USql", - "allOf": [ - { - "$ref": "#/definitions/SqlProperties" - } - ] - } -} -``` - -## x-ms-client-flatten -This extension allows to flatten deeply nested payloads into a more user friendly object. For example a payload that looks like this on the wire: -```js -{ - "template": { - "name": "some name", - "properties": { - "prop1": "value1", - "prop2": "value2", - "url": { - "value": "http://myurl" - } - } - } -} -``` -can be transformed into the following client model: -```cs -public class Template -{ - public string Name {get;set;} - public string Prop1 {get;set;} - public string Prop2 {get;set;} - public string UrlValue {get;set;} -} -``` -by using the following swagger definition: -```js -"definitions": { - "template": { - "properties": { - "name": { - "type": "string" - }, - "properties": { - "x-ms-client-flatten": true, - "$ref": "#/definitions/templateProperties" - } - } - } -} -``` -It's also possible to flatten body parameters so that the method will look like this: -```cs -client.DeployTemplate("some name", "value1", "value2", "http://myurl"); -``` -by using the following swagger definition: -```js -"post": { - "operationId": "DeployTemplate", - "parameters": [ - { - "name": "body", - "in": "body", - "x-ms-client-flatten": true, - "schema": { - "$ref": "#/definitions/template" - } - } - ] -} -``` - -**Parent element**: [Parameter Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterObject) or [Property on the Schema Definition](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject). In both cases the `type` of the parameter or property should be a complex schema with properties. - -**Schema**: -`true|false` - -**Example**: -```js -"definitions": { - "template": { - "properties": { - "name": { - "type": "string" - }, - "properties": { - "x-ms-client-flatten": true, - "$ref": "#/definitions/templateProperties" - } - } - } -} -``` -and -```js -"post": { - "operationId": "DeployTemplate", - "parameters": [ - { - "name": "body", - "in": "body", - "x-ms-client-flatten": true, - "schema": { - "$ref": "#/definitions/template" - } - } - ] -} -``` - -## x-ms-parameterized-host -When used, replaces the standard Swagger "host" attribute with a host that contains variables to be replaced as part of method execution or client construction, very similar to how path parameters work. - -**Parent element**: [Info Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#infoObject) - -**Schema**: - -Field Name | Type | Description ----|:---:|--- -hostTemplate | `string` | **Required**. Specifies the parameterized template for the host. -useSchemePrefix | `boolean` | **Optional, Default: true**. Specifes whether to prepend the default scheme a.k.a protocol to the base uri of client. -positionInOperation | `string` | **Optional, Default: first**. Specifies whether the list of parameters will appear in the beginning or in the end, in the method signature for every operation. The order within the parameters provided in the below mentioned array will be preserved. Either the array of parameters will be prepended or appended, based on the value provided over here. Valid values are **"first", "last"**. Every method/operation in any programming language has parameters categorized into two buckets **"required"** and **"optional"**. It is natural for optional paramaters to appear in the end in a method signature. **This aspect will be preserved, while prepending(first) or appending(last) hostTemplate parameters .** -parameters | [Array of Parameter Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterObject) | The list of parameters that are used within the hostTemplate. This can include both reference parameters as well as explicit parameters. Note that "in" is **required** and **must be** set to **"path"**. The reference parameters will be treated as **global parameters** and will end up as property of the client. - -**Example**: -- Using both explicit and reference parameters. - - Since "useSchemePrefix" is not specified, it's default value true will be applied. The user is expected to provide only the value of accountName. The generated code will fit it as a part of the url. - - Since "positionInOperation" with value "last" is specified, "accountName" will be the last required parameter in every method. "adlaJobDnsSuffixInPath" will be a property on the client as it is defined in the global parameters section and is referenced here. - -```js -"x-ms-parameterized-host": { - "hostTemplate": "{accountName}.{adlaJobDnsSuffix}", - "positionInOperation": "last", - "parameters": [ - { - "name": "accountName", - "description": "The Azure Data Lake Analytics account to execute job operations on.", - "required": true, - "type": "string", - "in": "path", - "x-ms-skip-url-encoding": true - }, - { - "$ref": "#/parameters/adlaJobDnsSuffixInPath" - } - ] - } -... -"adlaJobDnsSuffixInPath": { - "name": "adlaJobDnsSuffix", - "in": "path", - "required": true, - "type": "string", - "default": "azuredatalakeanalytics.net", - "x-ms-skip-url-encoding": true, - "description": "Gets the DNS suffix used as the base for all Azure Data Lake Analytics Job service requests." - } -``` -- Using explicit parameters and specifying the positionInOperation and schemePrefix. - - This means that accountName will be the first required parameter in all the methods and the user is expected to provide a url (protocol + accountName), since "useSchemePrfix" is set to false. -```js -"x-ms-parameterized-host": { - "hostTemplate": "{accountName}.mystaticsuffix.com", - "useSchemePrefix": false, - "positionInOperation": "first", - "parameters": [ - { - "name": "accountName", - "description": "The Azure Data Lake Analytics account to execute job operations on.", - "required": true, - "type": "string", - "in": "path", - "x-ms-skip-url-encoding": true - } - ] - } -``` - -## x-ms-examples -Describes the format for specifying examples for request and response of an operation in a swagger spec. It is a **dictionary** of different variations of the examples for a given operation. - -More information about this extension can be found [here](https://github.com/Azure/azure-rest-api-specs/tree/master/documentation/x-ms-examples.md). - -## x-ms-odata -When present the `x-ms-odata` extensions indicates the operation includes one or more [OData](http://www.odata.org/) query parameters. These parameters inlude `$filter`, `$top`, `$orderby`, `$skip`, and `$expand`. In some languages the generated method will expose these parameters as strongly types OData type. - -**Schema**: -[`ref`](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#referenceObject) to the definition that describes object used in filter. - -**Parent element**: [Operation Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#operationObject) - -**Example**: -```js -"paths": { - "/subscriptions/resource": { - "get": { - "x-ms-odata": "#/definitions/Product" - } - } -} -``` - -## x-ms-pageable -The REST API guidelines define a common pattern for paging through lists of data. The operation response is modeled in Swagger as a list of items (a "page") and a link to the next page, effectively resembling a singly linked list. Tag the operation as `x-ms-pageable` and the generated code will include methods for navigating between pages. - -**Schema**: - -Field Name | Type | Description ----|:---:|--- -itemName | `string` | Optional (default: `value`). Specifies the name of the property that provides the collection of pageable items. -nextLinkName| `string` | Required. Specifies the name of the property that provides the next link (common: `nextLink`). If the model does not have a next link property then specify `null`. This is useful for services that return an object that has an array referenced by `itemName`. The object is then flattened in a way that the array is *directly* returned, no paging is used. This provides a better client side API to the end user. -operationName | `string` | Optional (default: `Next`). Specifies the name of the operation for retrieving the next page. - -**Parent element**: [Operation Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#operationObject) - -**Example 1: Canonical** - -Basic use of `x-ms-pageable`: -```YAML -swagger: '2.0' -info: - version: 1.0.0 - title: Simple API -produces: - - application/json -paths: - /getIntegers: - get: - operationId: list - description: "Gets those integers." - x-ms-pageable: # EXTENSION - nextLinkName: nextLink # property name for next page URL - responses: - 200: - description: OK - schema: - $ref: '#/definitions/PagedIntegerCollection' -definitions: - PagedIntegerCollection: - description: "Page of integers." - type: object - properties: - value: # the current page - type: array - items: - type: integer - nextLink: # next page URL (referred to by "nextLinkName") - type: string -``` -Generated signatures: -```C# -IPage List(ISimpleAPIClient operations); -Task> ListAsync(ISimpleAPIClient operations, CancellationToken cancellationToken); -IPage ListNext(ISimpleAPIClient operations, string nextPageLink); -Task> ListNextAsync(ISimpleAPIClient operations, string nextPageLink, CancellationToken cancellationToken); -``` -Full code: -[example1.yaml](x-ms-pageable/example1.yaml), -[example1.cs](x-ms-pageable/example1.cs) - -**Example 2: Customized** - -Customizing code generation: -```YAML -swagger: '2.0' -info: - version: 1.0.0 - title: Simple API -produces: - - application/json -paths: - /getIntegers: - get: - operationId: list - description: "Gets those integers." - x-ms-pageable: # EXTENSION - nextLinkName: nextIntegersUrl # property name for next page URL - value: payload # property name for current page (overrides "value") - operationName: listMore # method name for retrieving next page (overrides "listNext") - responses: - 200: - description: OK - schema: - $ref: '#/definitions/PagedIntegerCollection' -definitions: - PagedIntegerCollection: - description: "Page of integers." - type: object - properties: - payload: # the current page (referred to by "value") - type: array - items: - type: integer - nextIntegersUrl: # next page URL (referred to by "nextLinkName") - type: string -``` -Generated signatures: -```C# -IPage List(ISimpleAPIClient operations); -Task> ListAsync(ISimpleAPIClient operations, CancellationToken cancellationToken); -IPage ListMore(ISimpleAPIClient operations, string nextPageLink); -Task> ListMoreAsync(ISimpleAPIClient operations, string nextPageLink, CancellationToken cancellationToken); -``` -Full code: -[example2.yaml](x-ms-pageable/example2.yaml), -[example2.cs](x-ms-pageable/example2.cs) - -**Example 3: Single page result** - -Providing a better user experience for single page response models: -```YAML -swagger: '2.0' -info: - version: 1.0.0 - title: Simple API -produces: - - application/json -paths: - /getIntegers: - get: - operationId: list - description: "Gets those integers." - x-ms-pageable: - nextLinkName: null # there are no further pages - value: payload # property name for the "page" (overrides "value") - responses: - 200: - description: OK - schema: - $ref: '#/definitions/PagedIntegerCollection' -definitions: - PagedIntegerCollection: - description: "Page of integers." - type: object - properties: - payload: # the only "page" (referred to by "value") - type: array - items: - type: integer -``` -Generated signatures: -```C# -IEnumerable List(ISimpleAPIClient operations); -Task> ListAsync(ISimpleAPIClient operations, CancellationToken cancellationToken); -``` -Full code: -[example3.yaml](x-ms-pageable/example3.yaml), -[example3.cs](x-ms-pageable/example3.cs) - - -## x-ms-long-running-operation -Some requests like creating/deleting a resource cannot be carried out immediately. In such a situation, the server sends a 201 (Created) or 202 (Accepted) and provides a link to monitor the status of the request. When such an operation is marked with extension `"x-ms-long-running-operation": true`, in Swagger, the generated code will know how to fetch the link to monitor the status. It will keep on polling at regular intervals till the request reaches one of the terminal states: Succeeded, Failed, or Canceled. - -**Parent element**: [Operation Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#operationObject) - -**Schema**: -`true|false` - -**Example**: -```js -"paths": { - "/products/{name}": { - "put": { - "operationId": "products_create", - "x-ms-long-running-operation": true, - "description": "A pageable list of Products." - } - } -} -``` - -## x-ms-azure-resource -Resource types as defined by the [Resource Managemer API](https://msdn.microsoft.com/en-us/library/azure/dn790568.aspx) are tagged by using a `x-ms-azure-resource` extension. - -**Parent element**: [Schema Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#schemaObject) - -**Schema**: -`true|false` - -**Example**: -```js -"Resource": { - "x-ms-azure-resource": true, - "properties": { - "id": { - "type": "string", - "readOnly": true, - "description": "Resource Id" - } - } -} -``` - -## x-ms-request-id -When set, allows to overwrite the `x-ms-request-id` response header (default is x-ms-request-id). - -**Parent element**: [Operation Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#operationObject) - -**Schema**: -`string` - the name of the request id header to use when setting Response.RequestId property. - -**Example**: -```js -"paths": { - "/products/{name}": { - "get": { - "operationId": "products_create", - "x-ms-request-id": "request-id" - } - } -} -``` - -## x-ms-client-request-id -When set, specifies the header parameter to be used instead of `x-ms-client-request-id` (default is x-ms-client-request-id). - -**Parent element**: [Header Parameter Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#parameterObject) - -**Schema**: -`string` - the name of the client request id header to use when setting sending request. - -**Example**: -```js -"paths": { - "/products/{name}": { - "get": { - "operationId": "products_create", - "parameters": [{ - "name": "x-ms-client-request-id", - "in": "header", - "type": "string", - "required": false, - "x-ms-client-request-id": true - }] - } - } -} -``` +See [https://github.com/Azure/autorest/blob/master/docs/extensions/readme.md](https://github.com/Azure/autorest/blob/master/docs/extensions/readme.md)