How do I generate "$ref" for schema?
I've added a schemas to my components:
var testSchema = new OpenApiSchema { Type = "object" };
doc.Components.Schemas.Add("test", testSchema );
How do I reference this schema elsewhere?
myPath.Operations[OperationType.Get].Responses["200"].Content["application/json"].Schema = ??
I have tried just referencing the object but that isn't working correctly, I'd like to see in the output it to generate something like:
"$ref": "#/components/schemas/test"
Thanks
Hi Leah,
Sorry for the pain. You have run into one of the more ugly aspects of the document model. There are a couple of ways of doing this. You can build the DOM as it would be when first being read from a document, or you can build it after the references have been resolved.
To build it the way it gets read from an input file, you would create two objects. e.g.
The reference,
var testSchemaReference = new OpenApiSchema {
UnresolvedReference = true,
Reference = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = "test"
}
};
and the component,
var testSchema = new OpenApiSchema {
Type = "object",
UnresolvedReference = false
};
doc.Components.Schemas.Add("test", testSchema);
The you build the OpenAPI document with these two objects. However, then you should use the OpenAPIReferenceResolver to walk the document and replace the reference with a single combined object.
The easier way is to create the object as the combined reference and target from the start. This would make your schema object look like this,
var testSchema = new OpenApiSchema {
Type = "object",
UnresolvedReference = false,
Reference = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = "test"
}
};
It is a little weird, but you effectively create a component that points to itself. You can use this object in both the components section and then anywhere where you want to put the reference. The design was done this way so that for documents, there only needs to be a single object for the component and all the references to it. This helps with performance and consistency when editing documents.
Here's a fully working sample,
var doc = new OpenApiDocument();
var testSchema = new OpenApiSchema {
Type = "object",
UnresolvedReference = false,
Reference = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = "test"
}
};
doc.Components = new OpenApiComponents();
doc.Components.Schemas.Add("test", testSchema);
var pathItem = new OpenApiPathItem()
{
Operations = new Dictionary<OperationType, OpenApiOperation> {
[OperationType.Get] = new OpenApiOperation
{
Responses = new OpenApiResponses {
["200"] = new OpenApiResponse {
Content = new Dictionary<string,OpenApiMediaType>() {
["application/json"] = new OpenApiMediaType {
Schema = testSchema
}
}
}
}
}
}
};
doc.Paths = new OpenApiPaths
{
{ "/test", pathItem }
};
Console.Write(doc.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0));