Skip to content

Commit 2b159ad

Browse files
RachitMalik12Rachit Malikmartincostellobaywet
authored
[DRAFT] 2.0 upgrade guide working doc (#2298)
* added wip upgrade guide * made changes requested by vincent * modified folder structure * Fix typo Co-authored-by: Martin Costello <[email protected]> * fix incorrect spacing Co-authored-by: Martin Costello <[email protected]> * fix typo Co-authored-by: Martin Costello <[email protected]> * fix typo Co-authored-by: Martin Costello <[email protected]> * Update docs/upgrade-guide-2.md Co-authored-by: Martin Costello <[email protected]> * fix typo Co-authored-by: Martin Costello <[email protected]> * Update docs/upgrade-guide-2.md Co-authored-by: Martin Costello <[email protected]> * Update docs/upgrade-guide-2.md Co-authored-by: Martin Costello <[email protected]> * Update docs/upgrade-guide-2.md Co-authored-by: Martin Costello <[email protected]> * Update docs/upgrade-guide-2.md Co-authored-by: Martin Costello <[email protected]> * Update docs/upgrade-guide-2.md Co-authored-by: Martin Costello <[email protected]> * Update docs/upgrade-guide-2.md Co-authored-by: Martin Costello <[email protected]> * Apply suggestions from code review Co-authored-by: Martin Costello <[email protected]> * chore: removes extraneous virtual keywords Signed-off-by: Vincent Biret <[email protected]> * chore: fixes max/min types Signed-off-by: Vincent Biret <[email protected]> * chore: updates comment on type change Signed-off-by: Vincent Biret <[email protected]> * chore: updates annotation to metadata Signed-off-by: Vincent Biret <[email protected]> * chore: linting Signed-off-by: Vincent Biret <[email protected]> * docs: adds a snippet to document yaml reading Signed-off-by: Vincent Biret <[email protected]> --------- Signed-off-by: Vincent Biret <[email protected]> Co-authored-by: Rachit Malik <[email protected]> Co-authored-by: Martin Costello <[email protected]> Co-authored-by: Vincent Biret <[email protected]>
1 parent 63a8a34 commit 2b159ad

File tree

1 file changed

+390
-0
lines changed

1 file changed

+390
-0
lines changed

docs/upgrade-guide-2.md

+390
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,390 @@
1+
---
2+
title: Upgrade guide to OpenAPI.NET 2.1
3+
description: Learn how to upgrade your OpenAPI.NET version from 1.6 to 2.0
4+
author: rachit.malik
5+
ms.author: malikrachit
6+
ms.topic: conceptual
7+
---
8+
9+
# Introduction
10+
11+
We are excited to announce the preview of a new version of the OpenAPI.NET library!
12+
OpenAPI.NET v2 is a major update to the OpenAPI.NET library. This release includes a number of performance improvements, API enhancements, and support for OpenAPI v3.1.
13+
14+
## The biggest update ever
15+
16+
Since the release of the first version of the OpenAPI.NET library in 2018, there has not been a major version update to the library. With the addition of support for OpenAPI v3.1 it was necessary to make some breaking changes. With this opportunity, we have taken the time to make some other improvements to the library, based on the experience we have gained supporting a large community of users for the last six years .
17+
18+
## Performance Improvements
19+
20+
One of the key features of OpenAPI.NET is its performance. This version makes it possible to parse JSON based OpenAPI descriptions even faster. OpenAPI.NET v1 relied on the excellent YamlSharp library for parsing both JSON and YAML files. With OpenAPI.NET v2 we are relying on System.Text.Json for parsing JSON files. For YAML files, we continue to use YamlSharp to parse YAML but then convert to JsonNodes for processing. This allows us to take advantage of the performance improvements in System.Text.Json while still supporting YAML files.
21+
22+
In v1, instances of `$ref` were resolved in a second pass of the document to ensure the target of the reference has been parsed before attempting to resolve it. In v2, reference targets are lazily resolved when reference objects are accessed. This improves load time performance for documents that make heavy use of references.
23+
24+
[How does this change the behaviour of external references?]
25+
26+
## Reduced Dependencies
27+
28+
In OpenAPI v1, it was necessary to include the Microsoft.OpenApi.Readers library to be able to read OpenAPI descriptions in either YAML or JSON. In OpenAPI.NET v2, the core Microsoft.OpenAPI library can both read and write JSON. It is only necessary to use the newly renamed [Microsoft.OpenApi.YamlReader](https://www.nuget.org/packages/Microsoft.OpenApi.YamlReader/) library if you need YAML support. This allows teams who are only working in JSON to avoid the additional dependency and therefore eliminate all non-.NET library references.
29+
30+
Once the dependency is added, the reader needs to be added to the reader settings as demonstrated below
31+
32+
```csharp
33+
var settings = new OpenApiReaderSettings();
34+
settings.AddYamlReader();
35+
36+
var result = OpenApiDocument.LoadAsync(openApiString, settings: settings);
37+
```
38+
39+
## API Enhancements
40+
41+
The v1 library attempted to mimic the pattern of `XmlTextReader` and `JsonTextReader` for the purpose of loading OpenAPI documents from strings, streams and text readers.
42+
43+
```csharp
44+
var reader = new OpenApiStringReader();
45+
var openApiDoc = reader.Read(stringOpenApiDoc, out var diagnostic);
46+
```
47+
48+
The same pattern can be used for `OpenApiStreamReader` and `OpenApiTextReader`. When we introduced the `ReadAsync` methods we eliminated the use of the `out` parameter.
49+
50+
```csharp
51+
var reader = new OpenApiStreamReader();
52+
var (document, diagnostics) = await reader.ReadAsync(streamOpenApiDoc);
53+
```
54+
55+
A `ReadResult` object acts as a tuple of `OpenApiDocument` and `OpenApiDiagnostic`.
56+
57+
The challenge with this approach is that the reader classes are not very discoverable and the behaviour is not actually consistent with the `*TextReader` pattern that allows incrementally reading the document. This library does not support incrementally reading the OpenAPI Document. It only reads a complete document and returns an `OpenApiDocument` instance.
58+
59+
In the v2 library we are moving to the pattern used by classes like `XDocument` where a set of static `Load` and `Parse` methods are used as factory methods.
60+
61+
```csharp
62+
public class OpenApiDocument {
63+
public static async Task<ReadResult> LoadAsync(string url, OpenApiReaderSettings settings = null) {}
64+
public static async Task<ReadResult> LoadAsync(Stream stream, string? format = null, OpenApiReaderSettings? settings = null) {}
65+
public static ReadResult Load(MemoryStream stream, string? format = null, OpenApiReaderSettings? settings = null) {}
66+
public static ReadResult Parse(string input, string? format = null, OpenApiReaderSettings? settings = null) {}
67+
}
68+
```
69+
70+
This API design allows a developer to use IDE autocomplete to present all the loading options by simply knowing the name of the `OpenApiDocument` class. Each of these methods are layered on top of the more primitive methods to ensure consistent behaviour.
71+
72+
As the YAML format is only supported when including the `Microsoft.OpenApi.YamlReader` library it was decided not to use an enum for the `format` parameter. We are considering implementing a more [strongly typed solution](https://github.com/microsoft/OpenAPI.NET/issues/1952) similar to the way that `HttpMethod` is implemented so that we have a strongly typed experience that is also extensible.
73+
74+
When the loading methods are used without a format parameter, we will attempt to parse the document using the default JSON reader. If that fails and the YAML reader is registered, then we will attempt to read as YAML. The goal is always to provide the fastest path with JSON but still maintain the convenience of not having to care whether a URL points to YAML or JSON if you need that flexibility.
75+
76+
### Removing the OpenAPI Any classes
77+
78+
In the OpenAPI specification, there are a few properties that are defined as type `any`. This includes:
79+
80+
- the example property in the parameter, media type objects
81+
- the value property in the example object
82+
- the values in the link object's parameters dictionary and `requestBody` property
83+
- all `x-` extension properties
84+
85+
In the v1 library, there are a set of classes that are derived from the `OpenApiAny` base class which is an abstract model which reflects the JSON data model plus some additional primitive types such as `decimal`, `float`, `datetime` etc.
86+
87+
In v2 we are removing this abstraction and relying on the `JsonNode` model to represent these inner types. In v1 we were not able to reliably identify the additional primitive types and it caused a significant amount of false negatives in error reporting as well as incorrectly parsed data values.
88+
89+
Due to `JsonNode` implicit operators, this makes initialization sometimes easier, instead of:
90+
91+
```csharp
92+
new OpenApiParameter
93+
{
94+
In = null,
95+
Name = "username",
96+
Description = "username to fetch",
97+
Example = new OpenApiFloat(5),
98+
};
99+
```
100+
101+
the assignment becomes simply,
102+
103+
```csharp
104+
Example = 0.5f,
105+
```
106+
107+
For a more complex example, where the developer wants to create an extension that is an object they would do this in v1:
108+
109+
```csharp
110+
var openApiObject = new OpenApiObject
111+
{
112+
{"stringProp", new OpenApiString("stringValue1")},
113+
{"objProp", new OpenApiObject()},
114+
{
115+
"arrayProp",
116+
new OpenApiArray
117+
{
118+
new OpenApiBoolean(false)
119+
}
120+
}
121+
};
122+
var parameter = new OpenApiParameter();
123+
parameter.Extensions.Add("x-foo", new OpenApiAny(openApiObject));
124+
125+
```
126+
127+
In v2, the equivalent code would be,
128+
129+
```csharp
130+
var openApiObject = new JsonObject
131+
{
132+
{"stringProp", "stringValue1"},
133+
{"objProp", new JsonObject()},
134+
{
135+
"arrayProp",
136+
new JsonArray
137+
{
138+
false
139+
}
140+
}
141+
};
142+
var parameter = new OpenApiParameter();
143+
parameter.Extensions.Add("x-foo", new OpenApiAny(openApiObject));
144+
145+
```
146+
147+
### Updates to OpenApiSchema
148+
149+
The OpenAPI 3.1 specification changes significantly how it leverages JSON Schema. In 3.0 and earlier, OpenAPI used a "subset, superset" of JSON Schema draft-4. This caused many problems for developers trying to use JSON Schema validation libraries with the JSON Schema in their OpenAPI descriptions. In OpenAPI 3.1, the 2020-12 draft version of JSON Schema was adopted and a new JSON Schema vocabulary was adopted to support OpenAPI specific keywords. All attempts to constrain what JSON Schema keywords could be used in OpenAPI were removed.
150+
151+
#### New keywords introduced in 2020-12
152+
153+
```csharp
154+
/// $schema, a JSON Schema dialect identifier. Value must be a URI
155+
public string Schema { get; set; }
156+
/// $id - Identifies a schema resource with its canonical URI.
157+
public string Id { get; set; }
158+
/// $comment - reserves a location for comments from schema authors to readers or maintainers of the schema.
159+
public string Comment { get; set; }
160+
/// $vocabulary- used in meta-schemas to identify the vocabularies available for use in schemas described by that meta-schema.
161+
public IDictionary<string, bool> Vocabulary { get; set; }
162+
/// $dynamicRef - an applicator that allows for deferring the full resolution until runtime, at which point it is resolved each time it is encountered while evaluating an instance
163+
public string DynamicRef { get; set; }
164+
/// $dynamicAnchor - used to create plain name fragments that are not tied to any particular structural location for referencing purposes, which are taken into consideration for dynamic referencing.
165+
public string DynamicAnchor { get; set; }
166+
/// $defs - reserves a location for schema authors to inline re-usable JSON Schemas into a more general schema.
167+
public IDictionary<string, OpenApiSchema> Definitions { get; set; }
168+
public IDictionary<string, OpenApiSchema> PatternProperties { get; set; } = new Dictionary<string, OpenApiSchema>();
169+
public bool UnevaluatedProperties { get; set;}
170+
171+
```
172+
173+
#### Changes to existing keywords
174+
175+
```csharp
176+
177+
public string? ExclusiveMaximum { get; set; } // type changed to reflect the new version of JSON schema
178+
public string? ExclusiveMinimum { get; set; } // type changed to reflect the new version of JSON schema
179+
public JsonSchemaType? Type { get; set; } // Was string, now flagged enum
180+
public string? Maximum { get; set; } // type changed to overcome double vs decimal issues
181+
public string? Minimum { get; set; } // type changed to overcome double vs decimal issues
182+
183+
public JsonNode Default { get; set; } // Type matching no longer enforced. Was IOpenApiAny
184+
public bool ReadOnly { get; set; } // No longer has defined semantics in OpenAPI 3.1
185+
public bool WriteOnly { get; set; } // No longer has defined semantics in OpenAPI 3.1
186+
187+
public JsonNode Example { get; set; } // No longer IOpenApiAny
188+
public IList<JsonNode> Examples { get; set; }
189+
public IList<JsonNode> Enum { get; set; }
190+
public OpenApiExternalDocs ExternalDocs { get; set; } // OpenApi Vocab
191+
public bool Deprecated { get; set; } // OpenApi Vocab
192+
public OpenApiXml Xml { get; set; } // OpenApi Vocab
193+
194+
public IDictionary<string, object> Metadata { get; set; } // Custom property bag to be used by the application, used to be named annotations
195+
```
196+
197+
#### OpenApiSchema methods
198+
199+
Other than the addition of `SerializeAsV31`, the methods have not changed.
200+
201+
```csharp
202+
public class OpenApiSchema : IOpenApiAnnotatable, IOpenApiExtensible, IOpenApiReferenceable, IOpenApiSerializable
203+
{
204+
public OpenApiSchema() { }
205+
public OpenApiSchema(OpenApiSchema schema) { }
206+
public void SerializeAsV31(IOpenApiWriter writer) { }
207+
public void SerializeAsV3(IOpenApiWriter writer) { }
208+
public void SerializeAsV2(IOpenApiWriter writer) { }
209+
}
210+
211+
```
212+
213+
## OpenAPI v3.1 Support
214+
215+
There are a number of new features in OpenAPI v3.1 that are now supported in OpenAPI.NET.
216+
217+
### Webhooks
218+
219+
```csharp
220+
221+
public class OpenApiDocument : IOpenApiSerializable, IOpenApiExtensible, IOpenApiAnnotatable {
222+
/// <summary>
223+
/// The incoming webhooks that MAY be received as part of this API and that the API consumer MAY choose to implement.
224+
/// A map of requests initiated other than by an API call, for example by an out of band registration.
225+
/// The key name is a unique string to refer to each webhook, while the (optionally referenced) Path Item Object describes a request that may be initiated by the API provider and the expected responses
226+
/// </summary>
227+
public IDictionary<string, OpenApiPathItem>? Webhooks { get; set; } = new Dictionary<string, OpenApiPathItem>();
228+
}
229+
```
230+
231+
### Summary in info object
232+
233+
```csharp
234+
235+
/// <summary>
236+
/// Open API Info Object, it provides the metadata about the Open API.
237+
/// </summary>
238+
public class OpenApiInfo : IOpenApiSerializable, IOpenApiExtensible
239+
{
240+
/// <summary>
241+
/// A short summary of the API.
242+
/// </summary>
243+
public string Summary { get; set; }
244+
}
245+
```
246+
247+
### License SPDX identifiers
248+
249+
```csharp
250+
/// <summary>
251+
/// License Object.
252+
/// </summary>
253+
public class OpenApiLicense : IOpenApiSerializable, IOpenApiExtensible
254+
{
255+
/// <summary>
256+
/// An SPDX license expression for the API. The identifier field is mutually exclusive of the Url property.
257+
/// </summary>
258+
public string Identifier { get; set; }
259+
}
260+
```
261+
262+
### Reusable path items
263+
264+
```csharp
265+
/// <summary>
266+
/// Components Object.
267+
/// </summary>
268+
public class OpenApiComponents : IOpenApiSerializable, IOpenApiExtensible
269+
{
270+
/// <summary>
271+
/// An object to hold reusable <see cref="OpenApiPathItem"/> Object.
272+
/// </summary>
273+
public IDictionary<string, OpenApiPathItem>? PathItems { get; set; } = new Dictionary<string, OpenApiPathItem>();
274+
}
275+
```
276+
277+
#### Summary and Description alongside $ref
278+
279+
Through the use of proxy objects in order to represent references, it is now possible to set the Summary and Description property on an object that is a reference. This was previously not possible.
280+
281+
```csharp
282+
var parameter = new OpenApiParameterReference("id", hostdocument)
283+
{
284+
Description = "Customer Id"
285+
};
286+
```
287+
288+
### Use HTTP Method Object Instead of Enum
289+
290+
HTTP methods are now represented as objects instead of enums. This change enhances flexibility but requires updates to how HTTP methods are handled in your code.
291+
Example:
292+
293+
```csharp
294+
// Before (1.6)
295+
OpenApiOperation operation = new OpenApiOperation
296+
{
297+
HttpMethod = OperationType.Get
298+
};
299+
300+
// After (2.0)
301+
OpenApiOperation operation = new OpenApiOperation
302+
{
303+
HttpMethod = new HttpMethod("GET") // or HttpMethod.Get
304+
};
305+
```
306+
307+
#### 2. Enable Null Reference Type Support
308+
309+
Version 2.0 preview 13 introduces support for null reference types, which improves type safety and reduces the likelihood of null reference exceptions.
310+
311+
**Example:**
312+
313+
```csharp
314+
// Before (1.6)
315+
OpenApiDocument document = new OpenApiDocument
316+
{
317+
Components = new OpenApiComponents()
318+
};
319+
320+
// After (2.0)
321+
OpenApiDocument document = new OpenApiDocument
322+
{
323+
Components = new OpenApiComponents()
324+
{
325+
Schemas = new Dictionary<string, IOpenApiSchema?>()
326+
}
327+
};
328+
329+
```
330+
331+
#### 3. References as Components
332+
333+
References can now be used as components, allowing for more modular and reusable OpenAPI documents.
334+
335+
**Example:**
336+
337+
```csharp
338+
// Before (1.6)
339+
OpenApiSchema schema = new OpenApiSchema
340+
{
341+
Reference = new OpenApiReference
342+
{
343+
Type = ReferenceType.Schema,
344+
Id = "MySchema"
345+
}
346+
};
347+
348+
// After (2.0)
349+
OpenApiComponents components = new OpenApiComponents
350+
{
351+
Schemas = new Dictionary<string, IOpenApiSchema>
352+
{
353+
["MySchema"] = new OpenApiSchema
354+
{
355+
Reference = new OpenApiSchemaReference("MySchema")
356+
}
357+
}
358+
};
359+
```
360+
361+
### OpenApiDocument.SerializeAs()
362+
363+
The `SerializeAs()` method simplifies serialization scenarios, making it easier to convert OpenAPI documents to different formats.
364+
**Example:**
365+
366+
```csharp
367+
OpenApiDocument document = new OpenApiDocument();
368+
string json = document.SerializeAs(OpenApiSpecVersion.OpenApi3_0, OpenApiFormat.Json);
369+
370+
```
371+
372+
### Bug Fixes
373+
374+
## Serialization of References
375+
376+
Fixed a bug where references would not serialize summary or descriptions in OpenAPI 3.1.
377+
**Example:**
378+
379+
```csharp
380+
OpenApiSchemaReference schemaRef = new OpenApiSchemaReference("MySchema")
381+
{
382+
Summary = "This is a summary",
383+
Description = "This is a description"
384+
};
385+
```
386+
387+
## Feedback
388+
389+
If you have any feedback please file a GitHub issue [here](https://github.com/microsoft/OpenAPI.NET/issues)
390+
The team is looking forward to hear your experience trying the new version and we hope you have fun busting out your OpenAPI 3.1 descriptions.

0 commit comments

Comments
 (0)