OpenApi.fromJson constructor
Create an OpenApi object from a JSON representation of an OpenAPI
Implementation
factory OpenApi.fromJson(Map<String, dynamic> json) {
return fromJsonWithLogging(json, (json) {
// Initialize the schemas, will be formatted in place below
Map<String, dynamic> schemas = json['components']?['schemas'] ?? {};
// Before starting, look for multipart requests and handle separately
// Multipart requests are built directly, not as a schema
if (json.containsKey('paths')) {
final paths = json['paths'] as Map<String, dynamic>;
for (final path in paths.entries) {
final pathItem = PathItem.fromJson(path.value);
final requestBody = pathItem.post?.requestBody;
final mediaType = requestBody?.content?['multipart/form-data'];
if (requestBody != null && mediaType != null) {
final ref = mediaType.schema?.ref;
if (ref != null && schemas.containsKey(ref)) {
// Remove from schemas and copy to the request body
final schema = schemas[ref];
schemas.remove(ref);
paths[path
.key]['post']['requestBody']['content']['multipart/form-data']['schema'] =
schema;
}
}
}
}
final d = _formatSpecFromJson(json: json, schemas: schemas);
// Search for any extra schemas created by this generator
// Used to improve the generated schema library
schemas = d['components']?['schemas'] ?? {};
final Map<String, dynamic> schemaExtra = {};
final Map<String, List<String>> extraSchemaMapping = {};
for (final s in schemas.keys) {
final (schemaOut, extraOut) = _extraComponentSchemas(
schemaKey: s,
schemaMap: schemas[s],
allSchemaNames: (schemas.keys.toList() + schemaExtra.keys.toList()),
);
schemas[s] = schemaOut;
if (extraOut.isNotEmpty) {
schemaExtra.addAll(extraOut);
extraSchemaMapping[s] = extraOut.keys.toList();
}
}
// Add any extra schemas to the spec
schemas.addAll(schemaExtra);
if (schemas.isNotEmpty) {
d['components']?['schemas'] = schemas;
}
final out = OpenApi(
version: d.containsKey('openapi') ? d['openapi'] : null,
info: Info.fromJson(d['info']),
jsonSchemaDialect: d['jsonSchemaDialect'],
externalDocs: d.containsKey('externalDocs')
? ExternalDocs.fromJson(d['externalDocs'])
: null,
servers: (d['servers'] as List<dynamic>?)
?.map((e) => Server.fromJson(e))
.toList(),
tags: (d['tags'] as List<dynamic>?)
?.map((e) => Tag.fromJson(e))
.toList(),
paths: (d['paths'] as Map<String, dynamic>?)?.map(
(k, e) => MapEntry(k, PathItem.fromJson(e)),
),
webhooks: (d['webhooks'] as Map<String, dynamic>?)?.map(
(k, e) => MapEntry(k, PathItem.fromJson(e)),
),
components: d.containsKey('components')
? Components.fromJson(d['components'])
: null,
security: (d['security'] as List<dynamic>?)
?.map((e) => Security.fromJson(e))
.toList(),
extraSchemaMapping: extraSchemaMapping,
);
return out;
});
}