Rust

OpenAPI

OpenAPI 2.0, 3.0 and 3.1 documents read into one version-independent, immutable model.
Rust 4,177 lines (2,772 code)split
PartCodeCommentsBlankTotalFiles
Rust source2,7721,1582474,17711

Comments include doc comments. Rust tests are tests/ and #[cfg(test)] modules.

Install#

The crate lives in the Appwrite repository; depend on it from Git.

Cargo.toml
[dependencies]
utopia-openapi = { git = "https://github.com/appwrite/appwrite" }

Getting started#

Common tasks with OpenAPI, each a complete program you can copy and run.

An OpenAPI document describes an HTTP API: its servers, paths, operations, parameters, request and response bodies, schemas and security. This library reads documents written in OpenAPI 2.0 (Swagger), 3.0 or 3.1 into one model, so code that generates SDKs, documentation or routes from a document works the same whichever version it was written in. Errors name the JSON Pointer location of the problem, so they can be traced back into the source.

Read a document

Pass the JSON text. The version is detected from swagger or openapi; pass one to insist on it.

Rust
use utopia_openapi::{HttpMethod, Version, parse};

let spec = parse(br#"{
    "openapi": "3.0.3",
    "info": {"title": "Pets", "version": "1.0.0"},
    "paths": {"/pets": {"get": {
        "operationId": "listPets",
        "tags": ["pets"],
        "parameters": [{"name": "limit", "in": "query", "schema": {"type": "integer", "minimum": 1}}],
        "responses": {"200": {"description": "The pets"}}
    }}}
}"#, Some(Version::V3_0))?;

let list = spec.paths["/pets"].operation(HttpMethod::Get).unwrap();
assert_eq!(list.id, "listPets");
assert_eq!(list.parameters[0].name, "limit");
assert_eq!(spec.operations_by_tag("pets").count(), 1);

One model for every version

A 2.0 document reads into the same shape as a 3.x one: host, basePath and schemes become servers, a body parameter becomes a request body with one media type per consumes, and a response schema gets one media type per produces.

Rust
use utopia_openapi::{HttpMethod, parse};

let spec = parse(br##"{
    "swagger": "2.0",
    "info": {"title": "Legacy", "version": "2"},
    "host": "api.example.com",
    "basePath": "/v1",
    "schemes": ["https"],
    "consumes": ["application/json"],
    "definitions": {"Pet": {"type": "object", "properties": {"name": {"type": "string"}}}},
    "paths": {"/pets": {"post": {
        "parameters": [{"name": "pet", "in": "body", "required": true, "schema": {"$ref": "#/definitions/Pet"}}],
        "responses": {"200": {"description": "OK"}}
    }}}
}"##, None)?;

assert_eq!(spec.servers[0].url, "https://api.example.com/v1");
let body = spec.paths["/pets"].operation(HttpMethod::Post).unwrap().request_body.as_ref().unwrap();
assert!(body.required);
assert_eq!(body.content["application/json"].schema.as_ref().unwrap().reference(), Some("#/definitions/Pet"));

Follow schema references

Schema references stay references, since recursive schemas are legal. Resolve one when you need the schema it names: chains of references are followed, and a cycle or an unknown name stops at the last schema reached.

Rust
use utopia_openapi::{SchemaKind, parse};

let spec = parse(br##"{"openapi": "3.1.0", "info": {"title": "Refs", "version": "1"}, "components": {"schemas": {
    "Id": {"type": "string", "format": "uuid"},
    "UserId": {"$ref": "#/components/schemas/Id"},
    "User": {"type": "object", "properties": {"id": {"$ref": "#/components/schemas/UserId"}}}
}}}"##, None)?;

let id = &spec.schemas["User"].as_object().unwrap().properties["id"];
let resolved = spec.resolve_schema(id);
assert!(matches!(resolved.kind, SchemaKind::String(_)));
assert_eq!(resolved.format.as_deref(), Some("uuid"));

Handle errors

Every failure is an Error whose message names where it happened.

Rust
use utopia_openapi::{Error, parse};

let error = parse(br#"{"openapi": "3.1.0", "info": {"version": "1"}}"#, None).unwrap_err();
assert!(matches!(error, Error::InvalidSpecification(_)));
assert_eq!(error.to_string(), "Expected string #/info/title");

let error = parse(br#"{"swagger": "1.2"}"#, None).unwrap_err();
assert_eq!(error.to_string(), "Unsupported OpenAPI version: 1.2");

Reference#

OpenAPI 2.0, 3.0 and 3.1 documents read into one version-independent, immutable model.

parse decodes a JSON document, detects its version from swagger or openapi, and reads it into a [Specification]: servers, tags, paths and their Operations, named Schemas, security schemes. A 2.0 document and a 3.1 document describing the same service read into the same shape: 2.0's host and basePath become servers, body and formData parameters a request body, definitions the schemas.

Object references ($ref to parameters, responses, examples, security schemes, path items) are followed while reading, inside the document only (LocalResolver); schema references are kept as SchemaKind::Reference, since recursive schemas are legal, and Specification::resolve_schema follows them on request.

Rust
use utopia_openapi::{HttpMethod, SchemaKind, Version, parse};

let spec = parse(br##"{
    "openapi": "3.1.0",
    "info": {"title": "Pets", "version": "1.0.0"},
    "paths": {"/pets/{id}": {"get": {
        "operationId": "getPet",
        "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}],
        "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Pet"}}}}}
    }}},
    "components": {"schemas": {"Pet": {"type": "object", "properties": {"name": {"type": ["string", "null"]}}}}}
}"##, None)?;

assert_eq!(spec.version, Version::V3_1);
let get = spec.paths["/pets/{id}"].operation(HttpMethod::Get).unwrap();
assert_eq!(get.id, "getPet");
let schema = get.responses["200"].content["application/json"].schema.as_ref().unwrap();
assert_eq!(schema.reference(), Some("#/components/schemas/Pet"));
let pet = spec.resolve_schema(schema).as_object().unwrap();
assert!(pet.properties["name"].nullable);
assert!(matches!(pet.properties["name"].kind, SchemaKind::String(_)));

Modules#

Each module groups one concept of the library. Internal ones hold items the crate re-exports at its root.

API#

What utopia_openapi exports at its root.

Structs

AnnotationsThe annotations every schema kind shares, for building a schema (`CompositeSchema::compose`); a `Schema` carries them as its own fields.ArraySchemaThe keywords of an array schema.CompositeSchema`oneOf`, `anyOf` or `allOf` over member schemas, and/or `not`.ConditionA property that must hold one literal value.ConditionalReferenceOne member of a union, recognised by required literal properties.ContactThe `info.contact` object.DialectThe JSON Schema rules an OpenAPI version permits.DiscriminatorThe `discriminator` of a composite schema.EncodingHow one property of a multipart or form body is encoded.ExampleA named example.ExternalDocumentationAn `externalDocs` object.HeaderA response or encoding header.InfoThe `info` object.LicenseThe `info.license` object.LocalResolverResolves local references (`#/...` JSON Pointers) against one document; any other reference is `Error::ReferenceNotFound`.MediaTypeA body in one media type.NumericSchemaThe keywords of an integer or number schema.OAuthFlowOne OAuth flow.ObjectSchemaThe keywords of an object schema.OpenApi2Reads an OpenAPI 2.0 document: `host`, `basePath` and `schemes` become servers, `definitions` the schemas, `body` and `formData` parameters a request body (one media type per `consumes`), and response schemas one media type per `produces`.OpenApi3Reads an OpenAPI 3.0 or 3.1 document. The minor version only changes the schema `Dialect`(super::Dialect) and whether `mutualTLS` security schemes are accepted (3.1).OperationOne operation: a method on a path.ParameterA parameter of an operation.PathItemThe operations available on one path.ReferenceA `$ref` value.RequestBodyThe body of a request.ResolutionContextWhat a resolution already went through: the references followed so far (to detect cycles) and the base URI of the document, for resolvers that fetch other documents.ResponseOne response of an operation.SchemaOne node of the schema tree.SchemaReaderReads raw schema values into the canonical tree.SecurityRequirementOne security alternative: every scheme it names applies together, each with its OAuth scopes.SecuritySchemeA security scheme.ServerA server the API is served from. OpenAPI 2.0's `host`, `basePath` and `schemes` become one server per scheme.ServerVariableA placeholder of a server URL.SpecificationWhat a document describes, the same shape whichever OpenAPI version it was written in: a 2.0 and a 3.1 document describing the same service read into equal specifications.StringSchemaThe keywords of a string schema.TagA tag, with its documentation.