-
Notifications
You must be signed in to change notification settings - Fork 282
Expand file tree
/
Copy pathOpenApiDocument.cs
More file actions
348 lines (289 loc) · 12.5 KB
/
Copy pathOpenApiDocument.cs
File metadata and controls
348 lines (289 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Exceptions;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
namespace Microsoft.OpenApi.Models
{
/// <summary>
/// Describes an OpenAPI object (OpenAPI document). See: https://swagger.io/specification
/// </summary>
public class OpenApiDocument : IOpenApiSerializable, IOpenApiExtensible
{
/// <summary>
/// REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required.
/// </summary>
public OpenApiInfo Info { get; set; }
/// <summary>
/// An array of Server Objects, which provide connectivity information to a target server.
/// </summary>
public IList<OpenApiServer> Servers { get; set; } = new List<OpenApiServer>();
/// <summary>
/// REQUIRED. The available paths and operations for the API.
/// </summary>
public OpenApiPaths Paths { get; set; }
/// <summary>
/// An element to hold various schemas for the specification.
/// </summary>
public OpenApiComponents Components { get; set; }
/// <summary>
/// A declaration of which security mechanisms can be used across the API.
/// </summary>
public IList<OpenApiSecurityRequirement> SecurityRequirements { get; set; } =
new List<OpenApiSecurityRequirement>();
/// <summary>
/// A list of tags used by the specification with additional metadata.
/// </summary>
public IList<OpenApiTag> Tags { get; set; } = new List<OpenApiTag>();
/// <summary>
/// Additional external documentation.
/// </summary>
public OpenApiExternalDocs ExternalDocs { get; set; }
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
public IDictionary<string, IOpenApiExtension> Extensions { get; set; } = new Dictionary<string, IOpenApiExtension>();
/// <summary>
/// Serialize <see cref="OpenApiDocument"/> to the latest patch of OpenAPI object V3.0.
/// </summary>
public void SerializeAsV3(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// openapi
writer.WriteProperty(OpenApiConstants.OpenApi, "3.0.1");
// info
writer.WriteRequiredObject(OpenApiConstants.Info, Info, (w, i) => i.SerializeAsV3(w));
// servers
writer.WriteOptionalCollection(OpenApiConstants.Servers, Servers, (w, s) => s.SerializeAsV3(w));
// paths
writer.WriteRequiredObject(OpenApiConstants.Paths, Paths, (w, p) => p.SerializeAsV3(w));
// components
writer.WriteOptionalObject(OpenApiConstants.Components, Components, (w, c) => c.SerializeAsV3(w));
// security
writer.WriteOptionalCollection(
OpenApiConstants.Security,
SecurityRequirements,
(w, s) => s.SerializeAsV3(w));
// tags
writer.WriteOptionalCollection(OpenApiConstants.Tags, Tags, (w, t) => t.SerializeAsV3WithoutReference(w));
// external docs
writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, e) => e.SerializeAsV3(w));
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
/// <summary>
/// Serialize <see cref="OpenApiDocument"/> to OpenAPI object V2.0.
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)
{
if (writer == null)
{
throw Error.ArgumentNull(nameof(writer));
}
writer.WriteStartObject();
// swagger
writer.WriteProperty(OpenApiConstants.Swagger, "2.0");
// info
writer.WriteRequiredObject(OpenApiConstants.Info, Info, (w, i) => i.SerializeAsV2(w));
// host, basePath, schemes, consumes, produces
WriteHostInfoV2(writer, Servers);
// paths
writer.WriteRequiredObject(OpenApiConstants.Paths, Paths, (w, p) => p.SerializeAsV2(w));
// Serialize each referenceable object as full object without reference if the reference in the object points to itself.
// If the reference exists but points to other objects, the object is serialized to just that reference.
// definitions
writer.WriteOptionalMap(
OpenApiConstants.Definitions,
Components?.Schemas,
(w, key, component) =>
{
if (component.Reference != null &&
component.Reference.Type == ReferenceType.Schema &&
component.Reference.Id == key)
{
component.SerializeAsV2WithoutReference(w);
}
else
{
component.SerializeAsV2(w);
}
});
// parameters
writer.WriteOptionalMap(
OpenApiConstants.Parameters,
Components?.Parameters,
(w, key, component) =>
{
if (component.Reference != null &&
component.Reference.Type == ReferenceType.Parameter &&
component.Reference.Id == key)
{
component.SerializeAsV2WithoutReference(w);
}
else
{
component.SerializeAsV2(w);
}
});
// responses
writer.WriteOptionalMap(
OpenApiConstants.Responses,
Components?.Responses,
(w, key, component) =>
{
if (component.Reference != null &&
component.Reference.Type == ReferenceType.Response &&
component.Reference.Id == key)
{
component.SerializeAsV2WithoutReference(w);
}
else
{
component.SerializeAsV2(w);
}
});
// securityDefinitions
writer.WriteOptionalMap(
OpenApiConstants.SecurityDefinitions,
Components?.SecuritySchemes,
(w, key, component) =>
{
if (component.Reference != null &&
component.Reference.Type == ReferenceType.SecurityScheme &&
component.Reference.Id == key)
{
component.SerializeAsV2WithoutReference(w);
}
else
{
component.SerializeAsV2(w);
}
});
// security
writer.WriteOptionalCollection(
OpenApiConstants.Security,
SecurityRequirements,
(w, s) => s.SerializeAsV2(w));
// tags
writer.WriteOptionalCollection(OpenApiConstants.Tags, Tags, (w, t) => t.SerializeAsV2WithoutReference(w));
// externalDocs
writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, e) => e.SerializeAsV2(w));
// extensions
writer.WriteExtensions(Extensions);
writer.WriteEndObject();
}
private static void WriteHostInfoV2(IOpenApiWriter writer, IList<OpenApiServer> servers)
{
if (servers == null || !servers.Any())
{
return;
}
// Arbitrarily choose the first server given that V2 only allows
// one host, port, and base path.
var firstServer = servers.First();
// Divide the URL in the Url property into host and basePath required in OpenAPI V2
// The Url property cannotcontain path templating to be valid for V2 serialization.
var firstServerUrl = new Uri(firstServer.Url);
// host
writer.WriteProperty(
OpenApiConstants.Host,
firstServerUrl.GetComponents(UriComponents.Host | UriComponents.Port, UriFormat.SafeUnescaped));
// basePath
if (firstServerUrl.AbsolutePath != "/")
{
writer.WriteProperty(OpenApiConstants.BasePath, firstServerUrl.AbsolutePath);
}
// Consider all schemes of the URLs in the server list that have the same
// host, port, and base path as the first server.
var schemes = servers.Select(
s =>
{
Uri.TryCreate(s.Url, UriKind.RelativeOrAbsolute, out var url);
return url;
})
.Where(
u => Uri.Compare(
u,
firstServerUrl,
UriComponents.Host | UriComponents.Port | UriComponents.Path,
UriFormat.SafeUnescaped,
StringComparison.OrdinalIgnoreCase) ==
0)
.Select(u => u.Scheme)
.Distinct()
.ToList();
// schemes
writer.WriteOptionalCollection(OpenApiConstants.Schemes, schemes, (w, s) => w.WriteValue(s));
}
/// <summary>
/// Load the referenced <see cref="IOpenApiReferenceable"/> object from a <see cref="OpenApiReference"/> object
/// </summary>
public IOpenApiReferenceable ResolveReference(OpenApiReference reference)
{
if (reference == null)
{
return null;
}
if (reference.IsExternal)
{
// Should not attempt to resolve external references against a single document.
throw new ArgumentException(Properties.SRResource.RemoteReferenceNotSupported);
}
if (!reference.Type.HasValue)
{
throw new ArgumentException(Properties.SRResource.LocalReferenceRequiresType);
}
// Special case for Tag
if (reference.Type == ReferenceType.Tag)
{
foreach (var tag in this.Tags)
{
if (tag.Name == reference.Id)
{
tag.Reference = reference;
return tag;
}
}
return null;
}
try
{
switch (reference.Type)
{
case ReferenceType.Schema:
return this.Components.Schemas[reference.Id];
case ReferenceType.Response:
return this.Components.Responses[reference.Id];
case ReferenceType.Parameter:
return this.Components.Parameters[reference.Id];
case ReferenceType.Example:
return this.Components.Examples[reference.Id];
case ReferenceType.RequestBody:
return this.Components.RequestBodies[reference.Id];
case ReferenceType.Header:
return this.Components.Headers[reference.Id];
case ReferenceType.SecurityScheme:
return this.Components.SecuritySchemes[reference.Id];
case ReferenceType.Link:
return this.Components.Links[reference.Id];
case ReferenceType.Callback:
return this.Components.Callbacks[reference.Id];
default:
throw new OpenApiException(Properties.SRResource.InvalidReferenceType);
}
} catch(KeyNotFoundException)
{
throw new OpenApiException(string.Format(Properties.SRResource.InvalidReferenceId,reference.Id));
}
}
}
}