AnCH OAS library parses OpenAPI 3.0 documents and generates C++ code from them: anch-oas-gen generates C++ structures and enumerations from the document schemas ( components.schemas ) with their anch-json mappers, so that API payloads can be deserialized (and serialized) with anch::json::deserialize and anch::json::serialize . With --server and --client options, it also generates anch-rest endpoints from the document paths: a service interface registered in anch::rest::Api and a typed client (see Endpoints ).
AnCH OAS depends on anch-json (document parsing) and anch-cli ( anch-oas-gen arguments). Generated code depends on anch-json, on anch-uuid when uuid format is used, and on anch-date when date-time or date formats are used (linked by anch-json when ANCH_DATE is ON ).
Documents have to be in JSON format (YAML is not supported). Swagger 2.0 and OpenAPI 3.1 documents are refused.
anch-oas is built with ANCH_BUILD_OAS option (ON by default) ; cmake --install installs anch-oas-gen with the libraries.
Options:
-i / --input : OpenAPI document (default to standard input) ;-o / --output : output directory, created when needed (default to current directory) ;-n / --namespace : models namespace (default to model ) ;-f / --file : generated files base name (default to models ) ;--no-uuid : uuid format is mapped to std::string instead of anch::UUID ;--no-date : date-time and date formats are mapped to std::string instead of anch::date::DateTime and anch::date::Date ;--server : generates the service interface and its endpoints registration ( NAME-server.hpp and NAME-server.cpp ) ;--client : generates the typed client ( NAME-client.hpp and NAME-client.cpp ) ;--api-name : service and client names prefix (default to the document title in PascalCase) ;--no-constraints : value constraints are not generated ;--strict : unsupported schemas and operations raise an error instead of a warning.Unchanged files are not rewritten. With CMake, a stamp file tracks the generation:
The models header holds the types and their descriptions ( anch::Mapping specializations, shared by formats, with their constraints) ; the source holds the anch-json mappers of enumerations.
Generated models are used with anch-json:
| OpenAPI schema | C++ type |
|---|---|
string ( uuid format) | std::string ( anch::UUID ) |
string ( date-time format) | anch::date::DateTime (RFC 3339, written in UTC) |
string ( date format) | anch::date::Date (RFC 3339 full-date ) |
integer ( int32 format) | int64_t ( int32_t ) |
number ( float format) | double ( float ) |
boolean | bool |
string enum | enum class (unknown values are refused) |
object with properties , allOf | struct |
array | std::vector |
object with additionalProperties schema only | std::map<std::string,T> |
| other component schema | alias ( using ) |
nullable properties are std::optional ; arrays and maps are empty when absent.anch::val::required : deserialization fails when they are absent ( MISSING_FIELD ) or null while they are not nullable ( CONSTRAINT_VIOLATION ).<Model><Property> , <Model><Property>Item for array items and <Model><Property>Value for map values.allOf merges the properties of every schema: inherited properties keep the types of the model which declares them.std::shared_ptr ; recursion through arrays and maps does not need pointers._ ; C++ keywords and macros get a _ suffix ( class → class_ ). Enumeration values are upper case words ( in-stock and inStock → IN_STOCK ).operator== (every member is compared).Schema constraints are generated as anch-json constraints given to registerField , and checked on deserialization, and on serialization when serialize_check_constraints option is enabled ( CONSTRAINT_VIOLATION error with the path of the value, see anch-json for client and server recommended options). They are listed in the generated documentation of each member. --no-constraints disables them (required properties are still checked). Generated models can be checked without serialization with anch::val::validate (every violation is returned, see anch-json).
| OpenAPI keyword | Generated constraint |
|---|---|
minLength , maxLength (strings) | anch::val::minLength , anch::val::maxLength (Unicode code points) |
minimum , maximum , exclusiveMinimum , exclusiveMaximum (numbers) | anch::val::minimum , anch::val::maximum , anch::val::exclusiveMinimum , anch::val::exclusiveMaximum |
multipleOf (numbers) | anch::val::multipleOf |
minItems , maxItems , uniqueItems (arrays) | anch::val::minItems , anch::val::maxItems , anch::val::uniqueItems |
minProperties , maxProperties (maps) | anch::val::minProperties , anch::val::maxProperties |
non string enum (numbers, booleans) | anch::val::allowed<T>({...}) |
pattern (strings) | anch::val::pattern ( std::regex ECMAScript by default, see anch::val::setPatternCompiler ) |
format (strings which are not mapped to a C++ type) | anch::val::format : registered formats ( email , hostname , ipv4 , ipv6 , uri , byte , ...) are checked, other formats are not |
array items and map additionalProperties constraints | anch::val::items(...) |
Code a string with minLength gets the minLength constraint.--strict ): minLength on an integer, multipleOf which is not strictly positive, enum value which is not a value of the type, invalid pattern , ... String constraints of uuid , date-time and date formats are ignored without warning: values are checked by their parser.The following schemas are not generated (warning, or error with --strict ):
oneOf / anyOf compositions (anch-json does not support polymorphism) ;#/components/schemas/ .Properties which have not been generated are unknown fields for anch-json: use deserialize_ignore_unknown_field to accept them. Formats without registered validator ( password , ...) are not checked: validators can be added with anch::val::registerFormat . Constraints of component schemas which are deserialized directly (alias of array deserialized as root value) are not checked: only properties constraints are.
With --server and --client , each operation of the document paths ( get , put , post , delete and patch ) is a method of the <API>Service interface (server side) and of the <API>Client class (client side). Both are in the models namespace and depend on anch-rest ( anch::rest-server and anch::rest-client CMake targets).
Generation rules:
operationId in camelCase ( get-pet → getPet ), derived from the method and the path when it is missing ( DELETE /pets/{id} → deletePetsById , with a warning) ;const T& body ), required query parameters, optional query parameters ( std::optional ). Path item and operation parameters are merged, references to #/components/parameters/ are followed. Path and query parameters are strings, numbers, booleans or UUID (converted by anch::rest::ParamConverter : invalid or missing value is a 400 response) ;application/json ( anch::codec::Json ), text/plain ( anch::codec::Text , strings only), multipart/form-data ( anch::rest::Multipart ) and application/x-www-form-urlencoded ( anch::rest::FormUrlEncoded ) ; references to #/components/requestBodies/ are followed (see form bodies). Other media types ( *\/* , application/octet-stream , image/png , ...), JSON and text without schema and request bodies without media type are raw streams: std::istream& body,
std::string_view contentType server side (request Content-Type , empty when absent), anch::rest::RawBody client side (stream, content type and size: the declared media type is sent when content type is empty if it is the only one and concrete, application/octet-stream otherwise) ;2xx ) with content → its type, with a 404 response → std::optional (empty result is a 404 response server side, 404 response is an empty result client side), without content → void , several success responses or other media types → anch::rest::Response . Status other than 200 (or 204 for void ) is set with Endpoint::status ( 201 , 202 , ...). Error responses are not generated: client raises anch::rest::HttpError ;<Operation>Request and <Operation>Response , with their constraints (checked as described in anch-rest).Not generated (warning, or error with --strict ): head , options and trace operations (anch-rest serves HEAD with GET routes), path segments which are not whole parameters ( /files/{name}.json ), undeclared path parameters, parameters of other types (enumerations, arrays, objects). Header and cookie parameters are not generated (warning). Constraints of path and query parameters are not checked.
Form request bodies ( multipart/form-data and application/x-www-form-urlencoded ) need an object schema (a model) or no schema ( anch::rest::Form body). A model used by several media types of a body (JSON and form) gets every codec, a form media type with another schema is ignored (warning). Each form body model gets an anch::rest::FormMapper in NAME-forms.hpp and NAME-forms.cpp (generated with --server and --client , without mapper when the document has no form body):
string with binary format (or array of them) of a multipart/form-data model → anch::rest::Part (file name, media type and content), not mapped in JSON: models header then includes rest/form.hpp (anch-rest-common) ;anch::rest::ParamConverter : invalid or missing required value is a 400 response), arrays of them → repeated fields ;multipart/form-data models → application/json parts ;anch::rest::checkFormConstraints ). Not generated (warning, or error with --strict ): enumerations and dates fields, objects of application/x-www-form-urlencoded models, recursive models, form bodies which are not objects. Encoding objects ( encoding ) are not read.