Skip to content

Commit dc25f9e

Browse files
committed
Inspect string input's format if not explicitly provided
1 parent 7acdf9b commit dc25f9e

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ public static ReadResult Parse(string input,
169169
string format = null,
170170
OpenApiReaderSettings settings = null)
171171
{
172-
format ??= OpenApiConstants.Json;
172+
format ??= InspectInputFormat(input);
173173
settings ??= new OpenApiReaderSettings();
174174

175175
// Copy string into MemoryStream
@@ -193,15 +193,14 @@ public static T Parse<T>(string input,
193193
string format = null,
194194
OpenApiReaderSettings settings = null) where T : IOpenApiElement
195195
{
196-
format ??= OpenApiConstants.Json;
196+
format ??= InspectInputFormat(input);
197197
settings ??= new OpenApiReaderSettings();
198198
var stream = new MemoryStream(Encoding.UTF8.GetBytes(input));
199199
return Load<T>(stream, version, format, out diagnostic, settings);
200200
}
201201

202202
private static async Task<ReadResult> InternalLoadAsync(Stream input, string format, OpenApiReaderSettings settings, CancellationToken cancellationToken = default)
203203
{
204-
Utils.CheckArgumentNull(format, nameof(format));
205204
var reader = OpenApiReaderRegistry.GetReader(format);
206205
var readResult = await reader.ReadAsync(input, settings, cancellationToken);
207206

@@ -289,5 +288,10 @@ SecurityException or
289288
}
290289
return (null, null);
291290
}
291+
292+
private static string InspectInputFormat(string input)
293+
{
294+
return input.StartsWith("{", StringComparison.OrdinalIgnoreCase) || input.StartsWith("[", StringComparison.OrdinalIgnoreCase) ? OpenApiConstants.Json : OpenApiConstants.Yaml;
295+
}
292296
}
293297
}

test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,21 @@ public void ParseDocumentFromInlineStringShouldSucceed()
106106
});
107107
}
108108

109+
[Fact]
110+
public void ParseInlineStringWithoutProvidingFormatSucceeds()
111+
{
112+
var stringOpenApiDoc = """
113+
openapi: 3.1.0
114+
info:
115+
title: Sample API
116+
version: 1.0.0
117+
paths: {}
118+
""";
119+
120+
var readResult = OpenApiDocument.Parse(stringOpenApiDoc);
121+
readResult.OpenApiDocument.Info.Title.Should().Be("Sample API");
122+
}
123+
109124
[Fact]
110125
public async Task ParseBasicDocumentWithMultipleServersShouldSucceed()
111126
{

0 commit comments

Comments
 (0)