Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
# openapi-aggregator

Aggregate and merge OpenAPI 3.x specifications from multiple sources into a single spec.
Aggregate and merge OpenAPI 3.x (and Swagger 2.0) specifications from multiple sources into a single spec.

Available as both a **Rust library** and a **CLI tool**.

**Try it in your browser:** the [playground](https://includeamin.github.io/openapi-aggregator/) runs the same merge engine compiled to WebAssembly. Add specs, edit the config, and share the result as a link.

## Features

- **Swagger 2.0 support** – Swagger 2.0 sources are converted to OpenAPI 3.0.3 automatically; anything that had to be approximated is reported as a warning
- **Multiple source types** – local YAML files, local JSON files, and HTTP endpoints (with custom headers)
- **Config-file driven** – define sources and merge options in a single YAML config
- **Conflict resolution** – choose between `error`, `overwrite`, or `rename` strategies for duplicate paths and component names
Expand Down Expand Up @@ -197,6 +198,7 @@ Other top-level fields:

- `webhooks` (OpenAPI 3.1) are merged like paths.
- Top-level `security` stays top-level only when every source declares the same requirements. Otherwise each source's requirements are copied onto its own operations, so no operation gains or loses authentication. Renamed security schemes and `discriminator.mapping` entries are updated along with `$ref`s.
- Swagger 2.0 sources are converted to OpenAPI 3.0.3 before merging (`host`/`basePath`/`schemes` become `servers`, `in: body` and `in: formData` parameters become `requestBody`, `definitions` move to `components`, and so on). Conversion is lenient and each approximation or dropped field is reported as a warning prefixed with the source name. Swagger 1.x is not supported.
- The merged `openapi` version comes from the first source. The CLI prints a warning when sources use different `major.minor` versions (also available via `aggregate_with_report`).
- Component types are always emitted in the same order, so the output is stable across runs.

Expand Down
3 changes: 2 additions & 1 deletion crates/openapi-aggregator-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,12 @@ pub mod config;
pub mod error;
pub mod merge;
pub mod prepare;
pub mod swagger2;

pub use config::{
Config, ConflictStrategy, InfoOverride, MergeConfig, OutputConfig, OutputFormat, ServerEntry,
Source, TagEntry, TagPrefixStrategy,
};
pub use error::Error;
pub use merge::{merge_specs, merge_specs_with_report, MergeReport};
pub use prepare::{parse_content, prepare_source};
pub use prepare::{parse_content, prepare_source, prepare_source_with_notes, PreparedSource};
122 changes: 104 additions & 18 deletions crates/openapi-aggregator-core/src/prepare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,42 @@ use serde_json::Value;
use crate::config::Source;
use crate::error::Error;
use crate::merge::deep_merge;
use crate::swagger2;

/// Parse spec text, apply the source's `additional_blocks` and validate it.
/// Returns `(display_name, spec)`.
/// A source after parsing, Swagger 2.0 conversion, `additional_blocks` and validation.
#[derive(Debug, Clone)]
pub struct PreparedSource {
pub name: String,
pub spec: Value,
/// Warnings about anything approximated while converting from Swagger 2.0,
/// each prefixed with `source '<name>': `. Empty for OpenAPI 3.x sources.
pub notes: Vec<String>,
}

/// Parse spec text, convert Swagger 2.0 to OpenAPI 3.0, apply the source's
/// `additional_blocks` and validate it. Returns `(display_name, spec)`.
pub fn prepare_source(content: &str, source: &Source) -> Result<(String, Value), Error> {
prepare_source_with_notes(content, source).map(|p| (p.name, p.spec))
}

/// Like [`prepare_source`], but also returns the conversion notes.
pub fn prepare_source_with_notes(content: &str, source: &Source) -> Result<PreparedSource, Error> {
let name = source.display_name();
let value = parse_and_prepare(content, source)?;
validate_openapi(&value, &name)?;
Ok((name, value))
let (spec, notes) = parse_and_prepare(content, source)?;
validate_openapi(&spec, &name)?;
let notes = notes
.into_iter()
.map(|n| format!("source '{name}': {n}"))
.collect();
Ok(PreparedSource { name, spec, notes })
}

fn parse_and_prepare(content: &str, source: &Source) -> Result<Value, Error> {
fn parse_and_prepare(content: &str, source: &Source) -> Result<(Value, Vec<String>), Error> {
let mut value = parse_content(content)?;
let mut notes = Vec::new();
if is_swagger2(&value) {
(value, notes) = swagger2::convert(value);
}
if let Some(blocks) = source_additional_blocks(source) {
if !blocks.is_object() {
return Err(Error::InvalidSpec {
Expand All @@ -24,7 +48,19 @@ fn parse_and_prepare(content: &str, source: &Source) -> Result<Value, Error> {
}
deep_merge(&mut value, blocks);
}
Ok(value)
Ok((value, notes))
}

/// A Swagger 2.0 document: has `swagger: 2.x` (string or bare YAML number) and no `openapi`.
fn is_swagger2(value: &Value) -> bool {
if value.get("openapi").is_some() {
return false;
}
match value.get("swagger") {
Some(Value::String(v)) => v == "2" || v.starts_with("2."),
Some(Value::Number(n)) => n.as_f64() == Some(2.0),
_ => false,
}
}

fn source_additional_blocks(source: &Source) -> Option<&Value> {
Expand Down Expand Up @@ -56,7 +92,7 @@ fn validate_openapi(value: &Value, source_name: &str) -> Result<(), Error> {
}),
None if value.get("swagger").is_some() => Err(Error::InvalidSpec {
name: source_name.into(),
reason: "Swagger 2.0 specs are not supported (only OpenAPI 3.x is supported)".into(),
reason: "Swagger 1.x is not supported (only Swagger 2.0 and OpenAPI 3.x are)".into(),
}),
None => Err(Error::InvalidSpec {
name: source_name.into(),
Expand Down Expand Up @@ -125,7 +161,7 @@ mod tests {
}
}"#;

let merged = parse_and_prepare(base, &source).unwrap();
let merged = parse_and_prepare(base, &source).unwrap().0;
assert_eq!(merged["x-vendor-root"]["enabled"], true);
assert_eq!(merged["paths"]["/pets"]["get"]["summary"], "list pets");
assert_eq!(
Expand All @@ -152,18 +188,68 @@ mod tests {
}

#[test]
fn prepare_source_rejects_non_openapi_with_source_name() {
let source = Source::File {
name: Some("legacy".into()),
path: PathBuf::from("ignored.yaml"),
tag_prefix: None,
additional_blocks: None,
};
let err = prepare_source("swagger: '2.0'\ninfo: {title: T, version: '1'}\n", &source)
fn prepare_source_rejects_swagger_1_x_with_source_name() {
let source = file_source("legacy", None);
let err = prepare_source("swagger: '1.2'\ninfo: {title: T, version: '1'}\n", &source)
.unwrap_err()
.to_string();
assert!(err.contains("legacy"), "{err}");
assert!(err.contains("Swagger 2.0") && err.contains("3.x"), "{err}");
assert!(err.contains("Swagger 1.x"), "{err}");
}

fn file_source(name: &str, blocks: Option<Value>) -> Source {
Source::File {
name: Some(name.into()),
path: PathBuf::from("ignored.yaml"),
tag_prefix: None,
additional_blocks: blocks,
}
}

const SWAGGER2: &str =
"swagger: '2.0'\ninfo: {title: T, version: '1'}\nhost: api.test\npaths: {}\n";

#[test]
fn prepare_converts_swagger2_and_prefixes_notes() {
let prepared = prepare_source_with_notes(SWAGGER2, &file_source("legacy", None)).unwrap();
assert_eq!(prepared.name, "legacy");
assert_eq!(prepared.spec["openapi"], "3.0.3");
assert!(!prepared.notes.is_empty());
assert!(prepared
.notes
.iter()
.all(|n| n.starts_with("source 'legacy': ")));
assert!(prepared.notes[0].contains("converted from Swagger 2.0"));

let (name, spec) = prepare_source(SWAGGER2, &file_source("legacy", None)).unwrap();
assert_eq!(
(name.as_str(), &spec["openapi"]),
("legacy", &json!("3.0.3"))
);
}

#[test]
fn plain_openapi_has_no_notes() {
let prepared = prepare_source_with_notes(
r#"{"openapi":"3.0.3","info":{"title":"T","version":"1"},"paths":{}}"#,
&file_source("x", None),
)
.unwrap();
assert!(prepared.notes.is_empty());
}

#[test]
fn additional_blocks_apply_after_conversion() {
let blocks =
json!({"info": {"x-a": 1}, "components": {"schemas": {"Extra": {"type": "object"}}}});
let prepared =
prepare_source_with_notes(SWAGGER2, &file_source("legacy", Some(blocks))).unwrap();
assert_eq!(prepared.spec["info"]["x-a"], 1);
assert_eq!(
prepared.spec["components"]["schemas"]["Extra"]["type"],
"object"
);
assert_eq!(prepared.spec["servers"][0]["url"], "https://api.test");
}

#[test]
Expand Down
Loading
Loading