AnCH Framework 0.2
Another C++ Hack: C++23 utility libraries
Loading...
Searching...
No Matches
AnCH OAS library documentation

Introduction

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 ).

Prerequisites

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.

Installation

anch-oas is built with ANCH_BUILD_OAS option (ON by default) ; cmake --install installs anch-oas-gen with the libraries.

Usage

anch-oas-gen -i petstore.json -o gen -n petstore::model -f petstore # generates gen/petstore.hpp and gen/petstore.cpp
cat petstore.json | anch-oas-gen -o gen # document on standard input: gen/models.hpp and gen/models.cpp

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:

set(models_dir ${CMAKE_CURRENT_BINARY_DIR}/gen)
add_custom_command(
OUTPUT ${models_dir}/petstore.stamp
BYPRODUCTS ${models_dir}/petstore.hpp ${models_dir}/petstore.cpp
COMMAND anch-oas-gen -i ${CMAKE_CURRENT_SOURCE_DIR}/petstore.json -o ${models_dir} -n petstore::model -f petstore
COMMAND ${CMAKE_COMMAND} -E touch ${models_dir}/petstore.stamp
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/petstore.json)
add_custom_target(petstore-models DEPENDS ${models_dir}/petstore.stamp)
add_executable(petstore main.cpp ${models_dir}/petstore.cpp)
add_dependencies(petstore petstore-models)
target_include_directories(petstore PRIVATE ${models_dir})
target_link_libraries(petstore PRIVATE anch::json anch::uuid)

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:

#include "petstore.hpp"
#include "json/json.hpp"
void
readPet(std::istream& input) {
petstore::model::Pet pet = anch::json::deserialize<petstore::model::Pet>(input);
std::cout << pet.id << " " << pet.name << std::endl;
}

Mapping

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 )
  • Optional and nullable properties are std::optional ; arrays and maps are empty when absent.
  • Required properties are registered with anch::val::required : deserialization fails when they are absent ( MISSING_FIELD ) or null while they are not nullable ( CONSTRAINT_VIOLATION ).
  • Inline objects and enumerations are named after their path: <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.
  • Recursive references (a model which contains itself directly or through other models) are std::shared_ptr ; recursion through arrays and maps does not need pointers.
  • Member names are property names where invalid characters are replaced by _ ; C++ keywords and macros get a _ suffix ( class → class_ ). Enumeration values are upper case words ( in-stock and inStock → IN_STOCK ).
  • Properties are declared in alphabetical order (anch-json maps are ordered).
  • Models have a default operator== (every member is compared).

Constraints

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(...)
  • Numbers are written as in the document (no conversion: integers bounds can be greater than 2^53). A bound outside the range of the C++ integer type is reported with a warning.
  • Constraints of alias components are applied where they are used: "$ref": "#/components/schemas/Code" with Code a string with minLength gets the minLength constraint.
  • Constraints which can not be applied are ignored with a warning (error with --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.

Limitations

The following schemas are not generated (warning, or error with --strict ):

  • oneOf / anyOf compositions (anch-json does not support polymorphism) ;
  • free-form objects and schemas without type (anch-json has no generic JSON value type) ;
  • nested containers: array of arrays, map of arrays, ... ;
  • references outside #/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.

Endpoints

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).

// Server: implement the service and register its endpoints
class Store: public petstore::model::PetStoreService {
public:
std::optional<petstore::model::Pet> getPet(int64_t id) override; // GET /pets/{id} (404 when empty)
petstore::model::Tag createTag(const petstore::model::Tag& body) override; // POST /pets (201)
std::vector<petstore::model::Tag> listPets(const std::string& status, const std::optional<int32_t>& limit) override; // GET /pets
};
Store store;
petstore::model::registerEndpoints(api, store);
api.validate();
// Client: typed calls over an anch-rest client (transport, base URL and filters are configured by the caller)
anch::rest::Client rest(std::make_unique<anch::rest::CurlTransport>(), "https://api.example.com");
petstore::model::PetStoreClient client(rest);
std::optional<petstore::model::Pet> pet = client.getPet(1);
std::vector<petstore::model::Tag> tags = client.listPets("AB"); // optional query parameters default to std::nullopt

Generation rules:

  • method name: operationId in camelCase ( get-pet → getPet ), derived from the method and the path when it is missing ( DELETE /pets/{id} → deletePetsById , with a warning) ;
  • arguments: path parameters in path order, request body ( 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) ;
  • request body: 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) ;
  • result: success response ( 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 ;
  • inline schemas of bodies and responses are models named <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 bodies

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) ;
  • strings, numbers, booleans and UUID → fields ( anch::rest::ParamConverter : invalid or missing required value is a 400 response), arrays of them → repeated fields ;
  • objects, arrays of objects and maps of multipart/form-data models → application/json parts ;
  • anch-json constraints are checked on server side ( 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.