Add standalone C++ server using cpp-httplib for OpenAPI-based APIs (#21724)

Supports:
All OpenAPI 3.x data types: primitives, arrays, enums, nullable/optional fields, nested objects
All parameter types: path, query, header, cookie, and combinations
Schema composition: allOf (inheritance), oneOf (discriminated unions), anyOf (flexible unions)
Security schemes: API key and bearer token authentication
Discriminator-based polymorphic deserialization and error handling

Provides:
Error handling for invalid JSON, type mismatches, missing/unknown discriminator, and parameter validation
Build system integration (CMake) for easy compilation and linking with required dependencies
Clear build and run instructions for local development and testing
Enables comprehensive, real-world validation of generated C++ server code against OpenAPI specifications
This commit is contained in:
vasireddyrajesh
2026-02-12 17:11:05 +05:30
committed by GitHub
parent d47ab0f545
commit b96334ffad
132 changed files with 18350 additions and 1 deletions

View File

@@ -0,0 +1,59 @@
name: Samples cpp httplib server
on:
push:
paths:
- "samples/server/petstore/cpp-httplib-server/**"
- ".github/workflows/samples-cpp-httplib-server.yaml"
pull_request:
paths:
- "samples/server/petstore/cpp-httplib-server/**"
- ".github/workflows/samples-cpp-httplib-server.yaml"
env:
GRADLE_VERSION: 6.9
jobs:
build:
name: Build cpp httplib server
strategy:
matrix:
sample:
- samples/server/petstore/cpp-httplib-server/petstore
- samples/server/petstore/cpp-httplib-server/feature-test
os:
- ubuntu-latest
- macOS-latest
- windows-latest
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Install dependencies (Linux)
if: matrix.os == 'ubuntu-latest'
run: |
sudo apt-get update
sudo apt-get install -y build-essential libssl-dev zlib1g-dev cmake
- name: Install dependencies (macOS)
if: matrix.os == 'macOS-latest'
run: |
brew install openssl zlib cmake
- name: Install dependencies (Windows)
if: matrix.os == 'windows-latest'
run: |
vcpkg install openssl:x64-windows zlib:x64-windows
shell: cmd
timeout-minutes: 20
- name: Build
working-directory: ${{ matrix.sample }}
run: |
if [ "${{ matrix.os }}" = "windows-latest" ]; then
cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE="C:/vcpkg/scripts/buildsystems/vcpkg.cmake"
else
cmake -S . -B build
fi
cmake --build build --verbose
shell: bash

View File

@@ -91,7 +91,7 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se
| | Languages/Frameworks |
| -------------------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.1, .NET Core 3.1, .NET 5.0. Libraries: RestSharp, GenericHost, HttpClient), **C++** (Arduino, cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Apache HttpClient 4.x, Apache HttpClient 5.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, Spring 6 RestClient, MicroProfile Rest Client, Helidon), **Jetbrains HTTP Client**, **Julia**, **k6**, **Kotlin**, **Lua**, **N4JS**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (hyper, reqwest, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient, pekko), **Swift** (2.x, 3.x, 4.x, 5.x, 6.x), **Typescript** (AngularJS, Angular (9.x - 19.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, redux-query, Rxjs), **XoJo**, **Zapier** |
| **Server stubs** | **Ada**, **C#** (ASP.NET Core, Azure Functions), **C++** (Oat++, Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant, Yesod), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/), [Apache Camel](https://camel.apache.org/), [Helidon](https://helidon.io/)), **Julia**, **Kotlin** (Spring Boot, [Ktor](https://github.com/ktorio/ktor), [Vert.x](https://vertx.io/)), **PHP** ([Flight](https://docs.flightphp.com/), Laravel, Lumen, [Mezzio (fka Zend Expressive)](https://github.com/mezzio/mezzio), Slim, Silex, [Symfony](https://symfony.com/)), **Python** (FastAPI, Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** ([rust-server](https://openapi-generator.tech/docs/generators/rust-server/)), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), [Cask](https://github.com/com-lihaoyi/cask), Scalatra) |
| **Server stubs** | **Ada**, **C#** (ASP.NET Core, Azure Functions), **C++** (Httplib, Oat++, Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant, Yesod), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/), [Apache Camel](https://camel.apache.org/), [Helidon](https://helidon.io/)), **Julia**, **Kotlin** (Spring Boot, [Ktor](https://github.com/ktorio/ktor), [Vert.x](https://vertx.io/)), **PHP** ([Flight](https://docs.flightphp.com/), Laravel, Lumen, [Mezzio (fka Zend Expressive)](https://github.com/mezzio/mezzio), Slim, Silex, [Symfony](https://symfony.com/)), **Python** (FastAPI, Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** ([rust-server](https://openapi-generator.tech/docs/generators/rust-server/)), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), [Cask](https://github.com/com-lihaoyi/cask), Scalatra) |
| **API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc**, **Markdown**, **PlantUML** |
| **Configuration files** | [**Apache2**](https://httpd.apache.org/) |
| **Others** | **GraphQL**, **JMeter**, **Ktorm**, **MySQL Schema**, **Postman Collection**, **Protocol Buffer**, **WSDL** |
@@ -1025,6 +1025,7 @@ Here is a list of template creators:
* Apex: @asnelling
* Bash: @bkryza
* C: @PowerOfCreation @zhemant [:heart:](https://www.patreon.com/zhemant)
* C++ Httplib: @rajvesh
* C++ Oat++: @Kraust
* C++ REST: @Danielku15
* C++ Tiny: @AndersSpringborg @kaareHH @michelealbano @mkakbas

View File

@@ -0,0 +1,8 @@
generatorName: cpp-httplib-server
outputDir: samples/server/petstore/cpp-httplib-server/feature-test
inputSpec: modules/openapi-generator/src/test/resources/3_0/cpp-httplib-server/feature-test.json
templateDir: modules/openapi-generator/src/main/resources/cpp-httplib-server
additionalProperties:
apiNamespace: "api"
modelNamespace: "models"
projectName: "cpp-httplib-server-feature-test"

View File

@@ -0,0 +1,8 @@
generatorName: cpp-httplib-server
outputDir: samples/server/petstore/cpp-httplib-server/petstore
inputSpec: modules/openapi-generator/src/test/resources/3_0/cpp-httplib-server/petstore.json
templateDir: modules/openapi-generator/src/main/resources/cpp-httplib-server
additionalProperties:
apiNamespace: "api"
modelNamespace: "models"
projectName: "cpp-httplib-server-petstore"

View File

@@ -89,6 +89,7 @@ The following generators are available:
* [ada-server](generators/ada-server.md)
* [aspnet-fastendpoints](generators/aspnet-fastendpoints.md)
* [aspnetcore](generators/aspnetcore.md)
* [cpp-httplib-server](generators/cpp-httplib-server.md)
* [cpp-oatpp-server](generators/cpp-oatpp-server.md)
* [cpp-pistache-server](generators/cpp-pistache-server.md)
* [cpp-qt-qhttpengine-server](generators/cpp-qt-qhttpengine-server.md)

View File

@@ -65,6 +65,7 @@ The following generators are available:
## SERVER generators
* [ada-server](ada-server.md)
* [aspnetcore](aspnetcore.md)
* [cpp-httplib-server](cpp-httplib-server.md)
* [cpp-oatpp-server](cpp-oatpp-server.md)
* [cpp-pistache-server](cpp-pistache-server.md)
* [cpp-qt5-qhttpengine-server](cpp-qt5-qhttpengine-server.md)

View File

@@ -0,0 +1,286 @@
---
title: Documentation for the cpp-httplib-server Generator
---
## METADATA
| Property | Value | Notes |
| -------- | ----- | ----- |
| generator name | cpp-httplib-server | pass this to the generate command after -g |
| generator stability | STABLE | |
| generator type | SERVER | |
| generator language | C++ | |
| generator default templating engine | mustache | |
| helpTxt | Generates a C++ server using the httplib library. | |
## CONFIG OPTIONS
These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details.
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|addApiImplStubs|Generate API implementation stubs and a sample main.cpp for quick start| |false|
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|<dl><dt>**false**</dt><dd>The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.</dd><dt>**true**</dt><dd>Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.</dd></dl>|true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|enumUnknownDefaultCase|If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response.With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.|<dl><dt>**false**</dt><dd>No changes to the enum's are made, this is the default option.</dd><dt>**true**</dt><dd>With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case.</dd></dl>|false|
|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C# have this enabled by default).|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|reservedWordPrefix|Prefix to prepend to reserved words in order to avoid conflicts| |r_|
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|variableNameFirstCharacterUppercase|Make first character of variable name uppercase (eg. value -&gt; Value)| |true|
## IMPORT MAPPING
| Type/Alias | Imports |
| ---------- | ------- |
## INSTANTIATION TYPES
| Type/Alias | Instantiated By |
| ---------- | --------------- |
## LANGUAGE PRIMITIVES
<ul class="column-ul">
<li>bool</li>
<li>char</li>
<li>double</li>
<li>float</li>
<li>int</li>
<li>long</li>
<li>size_t</li>
<li>std::any</li>
<li>std::deque</li>
<li>std::list</li>
<li>std::map</li>
<li>std::optional</li>
<li>std::pair</li>
<li>std::queue</li>
<li>std::set</li>
<li>std::stack</li>
<li>std::string</li>
<li>std::tuple</li>
<li>std::unordered_map</li>
<li>std::unordered_set</li>
<li>std::variant</li>
<li>std::vector</li>
<li>unsigned char</li>
<li>unsigned int</li>
<li>unsigned long</li>
<li>void</li>
</ul>
## RESERVED WORDS
<ul class="column-ul">
<li>NULL</li>
<li>alignas</li>
<li>alignof</li>
<li>and</li>
<li>and_eq</li>
<li>asm</li>
<li>auto</li>
<li>bitand</li>
<li>bitor</li>
<li>bool</li>
<li>break</li>
<li>case</li>
<li>catch</li>
<li>char</li>
<li>char16_t</li>
<li>char32_t</li>
<li>class</li>
<li>compl</li>
<li>concept</li>
<li>const</li>
<li>const_cast</li>
<li>constexpr</li>
<li>continue</li>
<li>decltype</li>
<li>default</li>
<li>delete</li>
<li>do</li>
<li>double</li>
<li>dynamic_cast</li>
<li>else</li>
<li>enum</li>
<li>explicit</li>
<li>export</li>
<li>extern</li>
<li>false</li>
<li>float</li>
<li>for</li>
<li>friend</li>
<li>goto</li>
<li>if</li>
<li>inline</li>
<li>int</li>
<li>linux</li>
<li>long</li>
<li>mutable</li>
<li>namespace</li>
<li>new</li>
<li>noexcept</li>
<li>not</li>
<li>not_eq</li>
<li>nullptr</li>
<li>operator</li>
<li>or</li>
<li>or_eq</li>
<li>private</li>
<li>protected</li>
<li>public</li>
<li>register</li>
<li>reinterpret_cast</li>
<li>requires</li>
<li>return</li>
<li>short</li>
<li>signed</li>
<li>sizeof</li>
<li>static</li>
<li>static_assert</li>
<li>static_cast</li>
<li>struct</li>
<li>switch</li>
<li>template</li>
<li>this</li>
<li>thread_local</li>
<li>throw</li>
<li>true</li>
<li>try</li>
<li>typedef</li>
<li>typeid</li>
<li>typename</li>
<li>union</li>
<li>unsigned</li>
<li>using</li>
<li>virtual</li>
<li>void</li>
<li>volatile</li>
<li>wchar_t</li>
<li>while</li>
<li>xor</li>
<li>xor_eq</li>
</ul>
## FEATURE SET
### Client Modification Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|BasePath|✗|ToolingExtension
|Authorizations|✗|ToolingExtension
|UserAgent|✗|ToolingExtension
|MockServer|✗|ToolingExtension
### Data Type Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Custom|✗|OAS2,OAS3
|Int32|✓|OAS2,OAS3
|Int64|✓|OAS2,OAS3
|Float|✓|OAS2,OAS3
|Double|✓|OAS2,OAS3
|Decimal|✓|ToolingExtension
|String|✓|OAS2,OAS3
|Byte|✓|OAS2,OAS3
|Binary|✓|OAS2,OAS3
|Boolean|✓|OAS2,OAS3
|Date|✓|OAS2,OAS3
|DateTime|✓|OAS2,OAS3
|Password|✓|OAS2,OAS3
|File|✓|OAS2
|Uuid|✗|
|Array|✓|OAS2,OAS3
|Null|✗|OAS3
|AnyType|✗|OAS2,OAS3
|Object|✓|OAS2,OAS3
|Maps|✓|ToolingExtension
|CollectionFormat|✓|OAS2
|CollectionFormatMulti|✓|OAS2
|Enum|✓|OAS2,OAS3
|ArrayOfEnum|✓|ToolingExtension
|ArrayOfModel|✓|ToolingExtension
|ArrayOfCollectionOfPrimitives|✓|ToolingExtension
|ArrayOfCollectionOfModel|✓|ToolingExtension
|ArrayOfCollectionOfEnum|✓|ToolingExtension
|MapOfEnum|✓|ToolingExtension
|MapOfModel|✓|ToolingExtension
|MapOfCollectionOfPrimitives|✓|ToolingExtension
|MapOfCollectionOfModel|✓|ToolingExtension
|MapOfCollectionOfEnum|✓|ToolingExtension
### Documentation Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Readme|✓|ToolingExtension
|Model|✓|ToolingExtension
|Api|✓|ToolingExtension
### Global Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Host|✓|OAS2,OAS3
|BasePath|✓|OAS2,OAS3
|Info|✓|OAS2,OAS3
|Schemes|✗|OAS2,OAS3
|PartialSchemes|✓|OAS2,OAS3
|Consumes|✓|OAS2
|Produces|✓|OAS2
|ExternalDocumentation|✓|OAS2,OAS3
|Examples|✓|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer|✗|OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3
### Parameter Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Path|✓|OAS2,OAS3
|Query|✓|OAS2,OAS3
|Header|✓|OAS2,OAS3
|Body|✓|OAS2
|FormUnencoded|✓|OAS2
|FormMultipart|✓|OAS2
|Cookie|✓|OAS3
### Schema Support Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Simple|✓|OAS2,OAS3
|Composite|✓|OAS2,OAS3
|Polymorphism|✓|OAS2,OAS3
|Union|✗|OAS3
|allOf|✗|OAS2,OAS3
|anyOf|✗|OAS3
|oneOf|✗|OAS3
|not|✗|OAS3
### Security Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|BasicAuth|✓|OAS2,OAS3
|ApiKey|✓|OAS2,OAS3
|OpenIDConnect|✗|OAS3
|BearerToken|✓|OAS3
|OAuth2_Implicit|✗|OAS2,OAS3
|OAuth2_Password|✗|OAS2,OAS3
|OAuth2_ClientCredentials|✗|OAS2,OAS3
|OAuth2_AuthorizationCode|✗|OAS2,OAS3
|SignatureAuth|✗|OAS3
|AWSV4Signature|✗|ToolingExtension
### Wire Format Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|JSON|✓|OAS2,OAS3
|XML|✗|OAS2,OAS3
|PROTOBUF|✗|ToolingExtension
|Custom|✗|OAS2,OAS3

View File

@@ -12,6 +12,7 @@ org.openapitools.codegen.languages.CrystalClientCodegen
org.openapitools.codegen.languages.CLibcurlClientCodegen
org.openapitools.codegen.languages.ClojureClientCodegen
org.openapitools.codegen.languages.ConfluenceWikiCodegen
org.openapitools.codegen.languages.CppHttplibServerCodegen
org.openapitools.codegen.languages.CppOatppClientCodegen
org.openapitools.codegen.languages.CppQtClientCodegen
org.openapitools.codegen.languages.CppQtQHttpEngineServerCodegen

View File

@@ -0,0 +1,75 @@
{{>License}}
#pragma once
#include <string>
#include <vector>
#include <memory>
namespace {{apiNamespace}} {
/**
* @brief Authentication Manager Interface
*
* This interface defines the contract for authentication validation.
* Users must implement this interface to provide their own authentication logic.
*
* Example implementation:
* @code
* class MyAuthManager : public AuthenticationManager {
* public:
* bool validateApiKey(const std::string& key) override {
* return database.checkApiKey(key);
* }
*
* bool validateBearerToken(const std::string& token) override {
* return jwt::verify(token, secret);
* }
*
* bool validateBasicAuth(const std::string& username, const std::string& password) override {
* return bcrypt::verify(password, database.getPasswordHash(username));
* }
*
* bool validateOAuth2(const std::string& token, const std::vector<std::string>& scopes) override {
* auto introspection = oauthProvider.introspect(token);
* return introspection.active && hasRequiredScopes(introspection, scopes);
* }
* };
* @endcode
*/
class AuthenticationManager {
public:
virtual ~AuthenticationManager() = default;
/**
* @brief Validate an API key
* @param key The API key to validate
* @return true if the API key is valid, false otherwise
*/
virtual bool validateApiKey(const std::string& key) = 0;
/**
* @brief Validate a Bearer token (e.g., JWT)
* @param token The bearer token to validate
* @return true if the token is valid, false otherwise
*/
virtual bool validateBearerToken(const std::string& token) = 0;
/**
* @brief Validate Basic authentication credentials
* @param username The username
* @param password The password
* @return true if the credentials are valid, false otherwise
*/
virtual bool validateBasicAuth(const std::string& username, const std::string& password) = 0;
/**
* @brief Validate an OAuth2 token with required scopes
* @param token The OAuth2 access token
* @param scopes The required scopes for this operation
* @return true if the token is valid and has required scopes, false otherwise
*/
virtual bool validateOAuth2(const std::string& token, const std::vector<std::string>& scopes) = 0;
};
} // namespace {{apiNamespace}}

View File

@@ -0,0 +1,62 @@
cmake_minimum_required(VERSION 3.14)
project({{cmakeProjectName}} LANGUAGES CXX)
include(FetchContent)
# Fetch nlohmann_json
FetchContent_Declare(
nlohmann_json
GIT_REPOSITORY https://github.com/nlohmann/json.git
GIT_TAG v3.11.3
)
FetchContent_MakeAvailable(nlohmann_json)
# Fetch cpp-httplib
FetchContent_Declare(
httplib
GIT_REPOSITORY https://github.com/yhirose/cpp-httplib.git
GIT_TAG v0.15.3
)
FetchContent_MakeAvailable(httplib)
# System libraries - install with: sudo apt-get install libssl-dev zlib1g-dev
find_package(OpenSSL REQUIRED)
find_package(ZLIB REQUIRED)
set(TARGET_NAME {{cmakeProjectName}}_openapi_lib)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
file(GLOB API_SRCS
${CMAKE_CURRENT_SOURCE_DIR}/api/*.h
${CMAKE_CURRENT_SOURCE_DIR}/api/*.cpp
)
file(GLOB MODEL_SRCS
${CMAKE_CURRENT_SOURCE_DIR}/models/*.h
${CMAKE_CURRENT_SOURCE_DIR}/models/*.cpp
)
add_library(${TARGET_NAME} ${API_SRCS} ${MODEL_SRCS})
target_include_directories (${TARGET_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
# Make sure these libraries/headers are available in the build environment before linking
# Required libraries/headers are httplib,ssl,nlohmann::json,zlib
target_link_libraries(${TARGET_NAME}
PRIVATE
httplib::httplib
OpenSSL::SSL
OpenSSL::Crypto
nlohmann_json::nlohmann_json
ZLIB::ZLIB)
{{#addApiImplStubs}}
# Build executable server with stub implementation
add_executable({{cmakeProjectName}}_server main.cpp)
target_link_libraries({{cmakeProjectName}}_server
PRIVATE
${TARGET_NAME}
httplib::httplib
OpenSSL::SSL
OpenSSL::Crypto
nlohmann_json::nlohmann_json
ZLIB::ZLIB)
target_include_directories({{cmakeProjectName}}_server PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
{{/addApiImplStubs}}

View File

@@ -0,0 +1,5 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/

View File

@@ -0,0 +1,437 @@
# {{projectName}} - C++ Server
## Overview
This server was generated using the [OpenAPI Generator](https://openapi-generator.tech) project.
It uses the [cpp-httplib](https://github.com/yhirose/cpp-httplib) library to implement a lightweight HTTP server
with JSON request/response handling via [nlohmann/json](https://github.com/nlohmann/json).
## Requirements
- C++17 compatible compiler
- CMake (3.14 or higher)
- OpenSSL (for HTTPS support)
- ZLIB (for compression support)
**Note:** The following libraries are automatically downloaded via CMake FetchContent:
- [cpp-httplib](https://github.com/yhirose/cpp-httplib) v0.15.3
- [nlohmann/json](https://github.com/nlohmann/json) v3.11.3
### Platform-Specific Installation
**Linux (Ubuntu/Debian):**
```bash
sudo apt-get update
sudo apt-get install -y libssl-dev zlib1g-dev cmake build-essential
```
**macOS:**
```bash
brew install openssl zlib cmake
```
**Windows:**
```powershell
# Using vcpkg
vcpkg install openssl:x64-windows zlib:x64-windows
# Then configure CMake with vcpkg toolchain:
cmake -B build -DCMAKE_TOOLCHAIN_FILE=[vcpkg_root]/scripts/buildsystems/vcpkg.cmake
```
## Project Structure
```
├── CMakeLists.txt # Project build configuration
├── README.md # This file
├── models/ # Generated model classes
└── api/ # Generated API handler classes
```
## Building the Project
```bash
mkdir build
cd build
cmake ..
make
```
{{#addApiImplStubs}}
### Quick Start with Generated Stubs
This project was generated with implementation stubs enabled. You can build and run the server immediately:
```bash
mkdir build && cd build
cmake ..
make
./{{cmakeProjectName}}_server
```
The server will start on `http://0.0.0.0:8080` with:
- All API endpoints registered with stub implementations
- Health check endpoint at `/health`
{{#hasAuthMethods}}
- Example authentication manager (remember to implement real authentication logic!)
{{/hasAuthMethods}}
**Implementation files to customize:**
{{#apiInfo}}
{{#apis}}
{{#operations}}
- `api/{{classFilename}}{{apiSuffix}}Impl.h` - API interface implementation
- `api/{{classFilename}}{{apiSuffix}}Impl.cpp` - Business logic stubs
{{/operations}}
{{/apis}}
{{/apiInfo}}
- `main.cpp` - Server configuration and startup
{{/addApiImplStubs}}
## Working with Models
### Model Classes
{{#models}}
{{#model}}
#### {{vendorExtensions.modelNamespace}}::{{vendorExtensions.modelClassName}}
```cpp
// Create a model
auto model = {{vendorExtensions.modelNamespace}}::{{vendorExtensions.modelClassName}}();
{{#vars}}
model.{{vendorExtensions.setter}}(/* value */); // Set {{baseName}}
{{/vars}}
// Serialize to JSON
nlohmann::json json = {{vendorExtensions.modelNamespace}}::{{vendorExtensions.modelClassName}}::toJson(model);
std::string jsonString = json.dump();
// Deserialize from JSON
auto parsedModel = {{vendorExtensions.modelNamespace}}::{{vendorExtensions.modelClassName}}::fromJson(nlohmann::json::parse(jsonString));
```
{{/model}}
{{/models}}
## Implementing API Handlers
### API Classes
Each API is generated as an abstract base class with pure virtual methods that you must implement.
{{#apiInfo}}
{{#apis}}
{{#operations}}
#### {{classname}}
Create a class that inherits from the generated base class:
```cpp
#include "api/{{classFilename}}{{apiSuffix}}.h"
class {{classname}}Impl : public {{apiNamespace}}::{{classname}} {
public:
{{#operation}}
{{#vendorExtensions}}
{{#hasAnyResponseSchema}}
{{responseType}} {{handlerFunctionName}}({{#hasAnyRequestSchema}}const {{requestType}}& params{{/hasAnyRequestSchema}}) override {
{{#hasAnyRequestSchema}}
// Access request parameters:
{{#pathParams}}
// Path: params.m_{{paramName}}
{{/pathParams}}
{{#queryParams}}
// Query: params.m_{{paramName}}{{^vendorExtensions.isRequired}} (optional){{/vendorExtensions.isRequired}}
{{/queryParams}}
{{#headerParams}}
// Header: params.m_{{paramName}}{{^vendorExtensions.isRequired}} (optional){{/vendorExtensions.isRequired}}
{{/headerParams}}
{{#requestModel}}
// Body: params.m_request (std::optional<{{requestModelNamespace}}::{{requestModel}}>)
{{/requestModel}}
{{/hasAnyRequestSchema}}
// Implement your business logic here
{{#successCodeToTypes}}
// Return success response (HTTP {{successConstName}}):
{{successType}} successResponse;
// ... populate response ...
return successResponse;
{{/successCodeToTypes}}
{{#errorCodeToTypes}}
// Or return error response (HTTP {{errorConstName}}):
// {{errorType}} errorResponse;
// return errorResponse;
{{/errorCodeToTypes}}
}
{{/hasAnyResponseSchema}}
{{^hasAnyResponseSchema}}
void {{handlerFunctionName}}({{#hasAnyRequestSchema}}const {{requestType}}& params{{/hasAnyRequestSchema}}) override {
{{#hasAnyRequestSchema}}
// Access request parameters from params struct
{{/hasAnyRequestSchema}}
// Implement your logic here
}
{{/hasAnyResponseSchema}}
{{/vendorExtensions}}
{{/operation}}
};
```
{{/operations}}
{{/apis}}
{{/apiInfo}}
## Running the Server
Here's a complete example of setting up and running the server:
```cpp
#include <httplib.h>
#include <memory>
{{#apiInfo}}{{#apis}}{{#operations}}
#include "api/{{classFilename}}{{apiSuffix}}.h"
{{/operations}}{{/apis}}{{/apiInfo}}
{{#hasAuthMethods}}
#include "api/AuthenticationManager.h"
{{/hasAuthMethods}}
int main() {
httplib::Server server;
{{#hasAuthMethods}}
// Create authentication manager (required for this API)
auto authMgr = std::make_shared<MyAuthManager>();
{{/hasAuthMethods}}
// Create API implementations
{{#apiInfo}}{{#apis}}{{#operations}}
{{classname}}Impl {{classVarName}};
{{/operations}}{{/apis}}{{/apiInfo}}
// Register routes
{{#apiInfo}}{{#apis}}{{#operations}}
{{classVarName}}.registerRoutes(server{{#hasAuthMethods}}, authMgr{{/hasAuthMethods}});
{{/operations}}{{/apis}}{{/apiInfo}}
// Start server
std::cout << "Server starting on http://localhost:8080" << std::endl;
server.listen("localhost", 8080);
return 0;
}
```
{{#hasAuthMethods}}
### With Authentication
When authentication is required, you must:
1. Implement the `AuthenticationManager` interface (see Authentication section below)
2. Pass the authentication manager to `registerRoutes()`
{{/hasAuthMethods}}
{{^hasAuthMethods}}
### Without Authentication
This API does not require authentication. Simply create your API implementations and register them with the server.
{{/hasAuthMethods}}
## Authentication
{{#hasAuthMethods}}
This API requires authentication. Implement the `AuthenticationManager` interface to provide your authentication logic:
```cpp
#include "api/AuthenticationManager.h"
class MyAuthManager : public {{apiNamespace}}::AuthenticationManager {
public:
bool validateApiKey(const std::string& key) override {
// Validate API key from header, query, or cookie
// Example: check against database or cache
return checkApiKeyInDatabase(key);
}
bool validateBearerToken(const std::string& token) override {
// Validate JWT or other bearer tokens
// Example: verify signature and expiration
return jwt::verify(token, secret_key);
}
bool validateBasicAuth(const std::string& username, const std::string& password) override {
// Validate username/password credentials
// Example: check against user database with hashed passwords
auto user = findUser(username);
return user && bcrypt::verify(password, user->passwordHash);
}
bool validateOAuth2(const std::string& token, const std::vector<std::string>& scopes) override {
// Validate OAuth2 token and check required scopes
// Example: introspect token and verify scopes
auto introspection = oauthProvider.introspect(token);
return introspection.active && hasAllScopes(introspection.scopes, scopes);
}
};
```
### Authentication Flow
1. The server automatically extracts credentials from requests (headers, query params, cookies)
2. Before calling your handler, it validates credentials using your `AuthenticationManager`
3. If validation fails, the server returns HTTP 401 Unauthorized automatically
4. If validation succeeds, your handler is called
### Security Schemes
The generated code supports:
- **API Key**: Header, query parameter, or cookie-based authentication
- **Bearer Token**: Authorization header with "Bearer" scheme (e.g., JWT)
- **Basic Auth**: HTTP Basic authentication (username:password)
- **OAuth2**: OAuth 2.0 token-based authentication with scope validation
{{/hasAuthMethods}}
{{^hasAuthMethods}}
This API does not require authentication.
{{/hasAuthMethods}}
## Error Handling
### Response Variants
Each API endpoint that returns data uses `std::variant` to represent multiple possible response types (success and errors):
```cpp
// Example: endpoint returns success (User) or errors (NotFound, ServerError)
using GetUserResponse = std::variant<User, NotFound, ServerError>;
GetUserResponse handleGetUser(const GetUserRequest& params) override {
if (userExists(params.m_userId)) {
User user = fetchUser(params.m_userId);
return user; // Automatically sets HTTP 200
} else {
NotFound error;
error.setMessage("User not found");
return error; // Automatically sets HTTP 404
}
}
```
The server automatically:
- Detects which type is returned from the variant
- Sets the appropriate HTTP status code
- Serializes the response to JSON
### HTTP Status Codes
Status codes are automatically set based on the response type you return. Each model type is associated with a specific HTTP status code defined in your OpenAPI specification.
**Optimized Status Code Constants:**
The generator only creates HTTP status code constants (e.g., `HTTP_RESPONSE_CODE_200`, `HTTP_RESPONSE_CODE_404`) for codes actually used by your API operations. This reduces code bloat and compilation time compared to generating all possible HTTP status codes.
### Parameter Validation
The generated code automatically validates:
- **Required parameters**: Returns HTTP 400 if missing
- **Type conversion**: Returns HTTP 400 if parameter cannot be converted to expected type
- **JSON parsing**: Returns HTTP 400 if request body is invalid JSON
Custom validation logic should be implemented in your handler methods.
### Working with Optional Parameters
Optional parameters and model fields use `std::optional`:
```cpp
void handleRequest(const RequestParams& params) override {
// Check if optional query parameter is present
if (params.m_optionalParam) {
auto value = *params.m_optionalParam; // Dereference to get value
// Use value...
}
// Check if optional request body is present
if (params.m_request) {
auto body = *params.m_request; // Dereference to get body
// Use body...
}
}
```
## Advanced Features
### Parameter Serialization Styles
The generator supports various parameter serialization styles as defined in OpenAPI:
- **simple**: Comma-separated values (default for path/header)
- **form**: Ampersand-separated values (default for query)
- **spaceDelimited**: Space-separated values
- **pipeDelimited**: Pipe-separated values
- **deepObject**: Nested object notation for query parameters
These are automatically handled during parameter parsing.
### Enum Handling
All generated enums automatically include an `UNSPECIFIED` value as the first enum entry for safe initialization:
```cpp
enum class Status {
UNSPECIFIED = 0, // Added automatically for safety
PENDING,
APPROVED,
REJECTED
};
// Safe default initialization
Status status; // Defaults to UNSPECIFIED (0)
// Explicit initialization
Status activeStatus = Status::APPROVED;
// Enum serialization/deserialization
// UNSPECIFIED is not a valid API value and indicates uninitialized state
```
**Why UNSPECIFIED?**
- Provides a safe default value for uninitialized enums
- Prevents undefined behavior from using uninitialized enum values
- Makes it clear when an enum hasn't been set vs. having a valid API value
- Does not appear in OpenAPI spec - internal C++ implementation detail
### Union Types (anyOf/oneOf)
When your OpenAPI spec uses `anyOf` or `oneOf`, the generated code uses `std::variant`:
```cpp
// OpenAPI: { "anyOf": [{"type": "string"}, {"type": "number"}] }
using MyUnionType = std::variant<std::string, double>;
// In your model:
MyUnionType value;
// Use std::visit to handle different types:
std::visit([](const auto& v) {
using T = std::decay_t<decltype(v)>;
if constexpr (std::is_same_v<T, std::string>) {
std::cout << "String: " << v << std::endl;
} else if constexpr (std::is_same_v<T, double>) {
std::cout << "Number: " << v << std::endl;
}
}, value);
```
## Additional Resources
- [cpp-httplib Documentation](https://github.com/yhirose/cpp-httplib)
- [nlohmann/json Documentation](https://github.com/nlohmann/json)
- [OpenAPI Generator Documentation](https://openapi-generator.tech/docs/generators/cpp-httplib-server)
- [OpenAPI Specification](https://swagger.io/specification/)
- [cpp-httplib Documentation](https://github.com/yhirose/cpp-httplib)
- [nlohmann/json Documentation](https://github.com/nlohmann/json)
- [OpenAPI Generator Documentation](https://openapi-generator.tech/docs/generators/)

View File

@@ -0,0 +1,128 @@
{{>License}}
#pragma once
// System headers
#include <httplib.h>{{#hasAuthMethods}}
#include <memory>{{/hasAuthMethods}}{{#includeVariantHeader}}
{{{includeVariantHeader}}}{{/includeVariantHeader}}{{#includeOptionalHeader}}
{{{includeOptionalHeader}}}{{/includeOptionalHeader}}
// Project headers
{{#modelsUsed}}
#include "models/{{{.}}}.h"
{{/modelsUsed}}
namespace {{apiNamespace}} {
{{#hasAuthMethods}}
class AuthenticationManager;
{{/hasAuthMethods}}
class {{apiClassnameInPascalCase}} {
public:
{{apiClassnameInPascalCase}}() = default;
virtual ~{{apiClassnameInPascalCase}}() = default;
/**
* @brief Register all routes for this API
* @param svr The httplib::Server instance to register routes on
{{#hasAnyAuth}}
* @param auth The AuthenticationManager for authentication (optional, defaults to nullptr)
{{/hasAnyAuth}}
*/
void registerRoutes(httplib::Server& svr{{#hasAnyAuth}}, std::shared_ptr<AuthenticationManager> auth = nullptr{{/hasAnyAuth}});
{{#operations}}
{{#operation}}
{{#vendorExtensions}}
{{#hasAnyRequestSchema}}
{{#-first}}
// =========================
// ===== Request types =====
// =========================
{{/-first}}
/**
* @brief Request type for {{handlerFunctionName}}.
*/
struct {{requestType}}
{
{{#requestModel}}
{{{bodyParam.dataType}}} m_request; //Request Body{{#bodyParam.vendorExtensions.isRequired}} (required){{/bodyParam.vendorExtensions.isRequired}}{{^bodyParam.vendorExtensions.isRequired}} (optional){{/bodyParam.vendorExtensions.isRequired}}{{/requestModel}}{{#queryParams}}
{{{dataType}}} m_{{paramName}}; //Query Params{{#vendorExtensions.isRequired}} (required){{/vendorExtensions.isRequired}}{{^vendorExtensions.isRequired}} (optional){{/vendorExtensions.isRequired}}{{/queryParams}}{{#headerParams}}
{{{dataType}}} m_{{paramName}}; //HeaderParams{{#vendorExtensions.isRequired}} (required){{/vendorExtensions.isRequired}}{{^vendorExtensions.isRequired}} (optional){{/vendorExtensions.isRequired}}{{/headerParams}}{{#pathParams}}
{{{dataType}}} m_{{paramName}}; //PathParams (always required){{/pathParams}}{{#cookieParams}}
{{{dataType}}} m_{{paramName}}; //Cookies{{#vendorExtensions.isRequired}} (required){{/vendorExtensions.isRequired}}{{^vendorExtensions.isRequired}} (optional){{/vendorExtensions.isRequired}}{{/cookieParams}}
};
{{/hasAnyRequestSchema}}
{{/vendorExtensions}}
{{/operation}}
{{/operations}}
{{#operations}}
{{#operation}}
{{#vendorExtensions}}
{{#hasAnyResponseSchema}}
{{#-first}}
// ==========================
// ===== Response types =====
// ==========================
{{/-first}}
/**
* @brief Response type for {{handlerFunctionName}}.
*/
{{#hasSingleResponseType}}
using {{responseType}} = {{singleResponseType}};
{{/hasSingleResponseType}}
{{^hasSingleResponseType}}
using {{responseType}} = std::variant<{{#successCodeToTypes}}{{#successType}}
{{successType}}{{/successType}}{{#errorCodeToTypes}}{{#-first}} ,{{/-first}}{{/errorCodeToTypes}}{{/successCodeToTypes}}{{^errorCodeToTypes}}>;{{/errorCodeToTypes}}{{#errorCodeToTypes}}
{{#errorType}}{{errorType}}{{/errorType}}{{^-last}} ,{{/-last}}{{#-last}} >;{{/-last}}{{/errorCodeToTypes}}
{{/hasSingleResponseType}}
{{/hasAnyResponseSchema}}
{{/vendorExtensions}}
{{/operation}}
{{/operations}}
// ============================================================
// ===== Pure virtual functions to be handled by the user =====
// ============================================================
{{#operations}}
{{#operation}}
{{#vendorExtensions}}
/**
{{#hasAnyRequestSchema}}
* {{requestType}} - struct containing all the query parameters and headers and schemas as available.
{{/hasAnyRequestSchema}}
{{#hasAnyResponseSchema}}
* @return {{responseType}} The response type returned by the handler.
{{/hasAnyResponseSchema}}
*/
virtual {{#hasAnyResponseSchema}}{{responseType}}{{/hasAnyResponseSchema}}{{^hasAnyResponseSchema}}void{{/hasAnyResponseSchema}} {{handlerFunctionName}}({{#hasAnyRequestSchema}}const {{requestType}}& params{{/hasAnyRequestSchema}})=0;
{{/vendorExtensions}}
{{/operation}}
{{/operations}}
private:
// ========================================
// ===== Helper function declarations =====
// ========================================
{{#operations}}
{{#operation}}
{{#vendorExtensions}}
{{#hasAnyRequestSchema}}
static bool parse{{operationIdPascalCase}}Params(const httplib::Request& req, {{requestType}}& params, std::vector<std::string>& paramErrors);
{{/hasAnyRequestSchema}}
void handle{{operationIdPascalCase}}Request(const httplib::Request& req, httplib::Response& res{{#hasAuth}}, std::shared_ptr<AuthenticationManager> auth{{/hasAuth}});
{{#hasAnyResponseSchema}}
static void handle{{responseType}}(const {{responseType}}& result, httplib::Response& res);
{{/hasAnyResponseSchema}}
{{/vendorExtensions}}
{{/operation}}
{{/operations}}
{{#hasAnyAuth}}
static bool performAuthentication(
const httplib::Request& req,
std::shared_ptr<AuthenticationManager> auth,
httplib::Response& res);
{{/hasAnyAuth}}
};
} // namespace {{apiNamespace}}

View File

@@ -0,0 +1,33 @@
{{>License}}
#pragma once
#include "{{{apiHeaderFileName}}}"
namespace {{apiNamespace}} {
/**
* @brief Implementation class for {{apiClassnameInPascalCase}}
*
* This is a stub implementation that you can use as a starting point.
* Override the methods to implement your business logic.
*/
class {{apiClassnameInPascalCase}}Impl : public {{apiClassnameInPascalCase}} {
public:
{{apiClassnameInPascalCase}}Impl() = default;
virtual ~{{apiClassnameInPascalCase}}Impl() = default;
{{#operations}}
{{#operation}}
{{#vendorExtensions}}
/**
* @brief Implementation stub for {{handlerFunctionName}}
*/
{{#hasAnyResponseSchema}}{{responseType}}{{/hasAnyResponseSchema}}{{^hasAnyResponseSchema}}void{{/hasAnyResponseSchema}} {{handlerFunctionName}}({{#hasAnyRequestSchema}}const {{requestType}}& params{{/hasAnyRequestSchema}}) override;
{{/vendorExtensions}}
{{/operation}}
{{/operations}}
};
} // namespace {{apiNamespace}}

View File

@@ -0,0 +1,40 @@
{{>License}}
#include "{{{apiClassnameInPascalCase}}}ApiImpl.h"
#include <stdexcept>
namespace {{apiNamespace}} {
{{#operations}}
{{#operation}}
{{#vendorExtensions}}
/**
* Implementation stub for {{handlerFunctionName}}
* TODO: Implement your business logic here
*/
{{#hasAnyResponseSchema}}{{classname}}::{{responseType}}{{/hasAnyResponseSchema}}{{^hasAnyResponseSchema}}void{{/hasAnyResponseSchema}} {{classname}}::{{handlerFunctionName}}({{#hasAnyRequestSchema}}const {{classname}}::{{requestType}}& params{{/hasAnyRequestSchema}})
{
// TODO: Implement your business logic here
{{#hasAnyResponseSchema}}
{{#hasSingleResponseType}}
// Return a default/stub response
{{responseType}} response;
// Initialize response fields as needed
return response;
{{/hasSingleResponseType}}
{{^hasSingleResponseType}}
// Return first success type as default
{{#successCodeToTypes}}{{#-first}}
{{successType}} response;
// Initialize response fields as needed
return response;
{{/-first}}{{/successCodeToTypes}}
{{/hasSingleResponseType}}
{{/hasAnyResponseSchema}}
}
{{/vendorExtensions}}
{{/operation}}
{{/operations}}
} // namespace {{apiNamespace}}

View File

@@ -0,0 +1,756 @@
{{>License}}
// System headers
#include <algorithm>
#include <cctype>
#include <locale>{{#operations}}{{#operation}}{{#vendorExtensions}}{{#hasAnyRequestSchema}}{{#hasArrayParams}}{{#-first}}
#include <sstream>{{/-first}}{{/hasArrayParams}}{{/hasAnyRequestSchema}}{{/vendorExtensions}}{{/operation}}{{/operations}}
// Project headers
#include "{{{apiHeaderFileName}}}"{{#hasAnyAuth}}
#include "AuthenticationManager.h"{{/hasAnyAuth}}
{{#statusCodeConsts}}
constexpr int {{constName}} = {{statusCode}};
{{/statusCodeConsts}}
namespace {{apiNamespace}} {
using namespace {{modelNamespace}};
{{#operations}}
{{#operation}}
{{#vendorExtensions}}
{{#hasAnyRequestSchema}}
bool {{apiClassnameInPascalCase}}::parse{{operationIdPascalCase}}Params(const httplib::Request& req, {{apiClassnameInPascalCase}}::{{requestType}}& params, std::vector<std::string>& paramErrors)
{
std::vector<std::string> errors;
{{#requestModel}}
if (!req.body.empty())
{
try
{
nlohmann::json json = nlohmann::json::parse(req.body);
{{#bodyParam.vendorExtensions.isOptional}}
{{{bodyParam.baseType}}} temp;
from_json(json, temp);
params.m_request = temp;
{{/bodyParam.vendorExtensions.isOptional}}
{{^bodyParam.vendorExtensions.isOptional}}
from_json(json, params.m_request);
{{/bodyParam.vendorExtensions.isOptional}}
}
catch (const std::exception& e)
{
errors.push_back("Invalid request body: " + std::string(e.what()));
}
}{{#bodyParam.vendorExtensions.isRequired}}
else
{
errors.push_back("Missing required request body");
}{{/bodyParam.vendorExtensions.isRequired}}
{{/requestModel}}
{{#queryParams}}
{{#-first}}
{{/-first}}
// Query Parameters - {{baseName}}
if (req.has_param("{{baseName}}"))
{
{{#vendorExtensions.isObject}}try
{
{{#vendorExtensions.isDeepObject}}// deepObject: parse as JSON object from multiple keys
nlohmann::json obj;
for (const auto& [k, v] : req.params)
{
if (k.find("{{baseName}}[") == 0)
{
std::string field = k.substr(std::string("{{baseName}}[").size(), k.size() - std::string("{{baseName}}[").size() - 1);
obj[field] = v;
}
}
params.m_{{paramName}} = obj.get<{{{vendorExtensions.unwrappedDataType}}}>();{{/vendorExtensions.isDeepObject}}{{^vendorExtensions.isDeepObject}}// Parse JSON object from query
auto val = req.get_param_value("{{baseName}}", 0);
params.m_{{paramName}} = nlohmann::json::parse(val).get<{{{vendorExtensions.unwrappedDataType}}}>();{{/vendorExtensions.isDeepObject}}
}
catch (const std::exception& e)
{
errors.push_back("Invalid query parameter '{{baseName}}': " + std::string(e.what()));
}{{/vendorExtensions.isObject}}{{#vendorExtensions.isArray}}try
{
{{#vendorExtensions.isSpaceDelimited}}// spaceDelimited: split by space
auto val = req.get_param_value("{{baseName}}", 0);
std::stringstream ss(val);
std::string item;{{#vendorExtensions.isOptional}}
if (!params.m_{{paramName}}.has_value())
{
params.m_{{paramName}} = std::vector<{{{items.dataType}}}>{};
}{{/vendorExtensions.isOptional}}
while (std::getline(ss, item, ' '))
{
if (!item.empty())
{
{{#vendorExtensions.isOptional}}
params.m_{{paramName}}->emplace_back(item);
{{/vendorExtensions.isOptional}}
{{^vendorExtensions.isOptional}}
params.m_{{paramName}}.emplace_back(item);
{{/vendorExtensions.isOptional}}
}
}{{/vendorExtensions.isSpaceDelimited}}{{#vendorExtensions.isPipeDelimited}}// pipeDelimited: split by |
auto val = req.get_param_value("{{baseName}}", 0);
std::stringstream ss(val);
std::string item;{{#vendorExtensions.isOptional}}
if (!params.m_{{paramName}}.has_value())
{
params.m_{{paramName}} = std::vector<{{{items.dataType}}}>{};
}{{/vendorExtensions.isOptional}}
while (std::getline(ss, item, '|'))
{
if (!item.empty())
{
{{#vendorExtensions.isOptional}}
params.m_{{paramName}}->emplace_back(item);
{{/vendorExtensions.isOptional}}
{{^vendorExtensions.isOptional}}
params.m_{{paramName}}.emplace_back(item);
{{/vendorExtensions.isOptional}}
}
}{{/vendorExtensions.isPipeDelimited}}{{^vendorExtensions.isSpaceDelimited}}{{^vendorExtensions.isPipeDelimited}}// form/simple: multi-param or comma-separated
size_t count = req.get_param_value_count("{{baseName}}");{{#vendorExtensions.isOptional}}
if (!params.m_{{paramName}}.has_value())
{
params.m_{{paramName}} = std::vector<{{{items.dataType}}}>{};
}{{/vendorExtensions.isOptional}}
if (count > 1)
{
for (size_t i = 0; i < count; ++i)
{
auto val = req.get_param_value("{{baseName}}", i);
{{#items.vendorExtensions.isInt}}
{{#vendorExtensions.isOptional}}
params.m_{{paramName}}->emplace_back(std::stoi(val));
{{/vendorExtensions.isOptional}}
{{^vendorExtensions.isOptional}}
params.m_{{paramName}}.emplace_back(std::stoi(val));
{{/vendorExtensions.isOptional}}
{{/items.vendorExtensions.isInt}}
{{#items.vendorExtensions.isLong}}
{{#vendorExtensions.isOptional}}
params.m_{{paramName}}->emplace_back(std::stol(val));
{{/vendorExtensions.isOptional}}
{{^vendorExtensions.isOptional}}
params.m_{{paramName}}.emplace_back(std::stol(val));
{{/vendorExtensions.isOptional}}
{{/items.vendorExtensions.isLong}}
{{#items.vendorExtensions.isDouble}}
{{#vendorExtensions.isOptional}}
params.m_{{paramName}}->emplace_back(std::stod(val));
{{/vendorExtensions.isOptional}}
{{^vendorExtensions.isOptional}}
params.m_{{paramName}}.emplace_back(std::stod(val));
{{/vendorExtensions.isOptional}}
{{/items.vendorExtensions.isDouble}}
{{#items.vendorExtensions.isFloat}}
{{#vendorExtensions.isOptional}}
params.m_{{paramName}}->emplace_back(std::stof(val));
{{/vendorExtensions.isOptional}}
{{^vendorExtensions.isOptional}}
params.m_{{paramName}}.emplace_back(std::stof(val));
{{/vendorExtensions.isOptional}}
{{/items.vendorExtensions.isFloat}}
{{^items.vendorExtensions.isInt}}{{^items.vendorExtensions.isLong}}{{^items.vendorExtensions.isDouble}}{{^items.vendorExtensions.isFloat}}
{{#vendorExtensions.isOptional}}
params.m_{{paramName}}->emplace_back(val);
{{/vendorExtensions.isOptional}}
{{^vendorExtensions.isOptional}}
params.m_{{paramName}}.emplace_back(val);
{{/vendorExtensions.isOptional}}
{{/items.vendorExtensions.isFloat}}{{/items.vendorExtensions.isDouble}}{{/items.vendorExtensions.isLong}}{{/items.vendorExtensions.isInt}}
}
}
else if (count == 1)
{
auto val = req.get_param_value("{{baseName}}", 0);
std::stringstream ss(val);
std::string item;
while (std::getline(ss, item, ','))
{
if (!item.empty())
{
{{#items.vendorExtensions.isInt}}
{{#vendorExtensions.isOptional}}
params.m_{{paramName}}->emplace_back(std::stoi(item));
{{/vendorExtensions.isOptional}}
{{^vendorExtensions.isOptional}}
params.m_{{paramName}}.emplace_back(std::stoi(item));
{{/vendorExtensions.isOptional}}
{{/items.vendorExtensions.isInt}}
{{#items.vendorExtensions.isLong}}
{{#vendorExtensions.isOptional}}
params.m_{{paramName}}->emplace_back(std::stol(item));
{{/vendorExtensions.isOptional}}
{{^vendorExtensions.isOptional}}
params.m_{{paramName}}.emplace_back(std::stol(item));
{{/vendorExtensions.isOptional}}
{{/items.vendorExtensions.isLong}}
{{#items.vendorExtensions.isDouble}}
{{#vendorExtensions.isOptional}}
params.m_{{paramName}}->emplace_back(std::stod(item));
{{/vendorExtensions.isOptional}}
{{^vendorExtensions.isOptional}}
params.m_{{paramName}}.emplace_back(std::stod(item));
{{/vendorExtensions.isOptional}}
{{/items.vendorExtensions.isDouble}}
{{#items.vendorExtensions.isFloat}}
{{#vendorExtensions.isOptional}}
params.m_{{paramName}}->emplace_back(std::stof(item));
{{/vendorExtensions.isOptional}}
{{^vendorExtensions.isOptional}}
params.m_{{paramName}}.emplace_back(std::stof(item));
{{/vendorExtensions.isOptional}}
{{/items.vendorExtensions.isFloat}}
{{^items.vendorExtensions.isInt}}{{^items.vendorExtensions.isLong}}{{^items.vendorExtensions.isDouble}}{{^items.vendorExtensions.isFloat}}
{{#vendorExtensions.isOptional}}
params.m_{{paramName}}->emplace_back(item);
{{/vendorExtensions.isOptional}}
{{^vendorExtensions.isOptional}}
params.m_{{paramName}}.emplace_back(item);
{{/vendorExtensions.isOptional}}
{{/items.vendorExtensions.isFloat}}{{/items.vendorExtensions.isDouble}}{{/items.vendorExtensions.isLong}}{{/items.vendorExtensions.isInt}}
}
}
}{{/vendorExtensions.isPipeDelimited}}{{/vendorExtensions.isSpaceDelimited}}
}
catch (const std::exception& e)
{
errors.push_back("Invalid query parameter '{{baseName}}': " + std::string(e.what()));
}{{/vendorExtensions.isArray}}{{#vendorExtensions.isEnum}}try
{
params.m_{{paramName}} = {{enumFromStringHelper}}(req.get_param_value("{{baseName}}"));
}
catch (const std::exception& e)
{
errors.push_back("Invalid query parameter '{{baseName}}': " + std::string(e.what()));
}{{/vendorExtensions.isEnum}}{{#vendorExtensions.isString}}params.m_{{paramName}} = req.get_param_value("{{baseName}}"){{#vendorExtensions.isMatrix}}.substr(1){{/vendorExtensions.isMatrix}}{{#vendorExtensions.isLabel}}.substr(1){{/vendorExtensions.isLabel}};{{/vendorExtensions.isString}}{{#vendorExtensions.isInt}}try
{
params.m_{{paramName}} = std::stoi(req.get_param_value("{{baseName}}"));
}
catch (const std::exception& e)
{
errors.push_back("Invalid query parameter '{{baseName}}': " + std::string(e.what()));
}{{/vendorExtensions.isInt}}{{#vendorExtensions.isLong}}try
{
params.m_{{paramName}} = std::stoll(req.get_param_value("{{baseName}}"));
}
catch (const std::exception& e)
{
errors.push_back("Invalid query parameter '{{baseName}}': " + std::string(e.what()));
}{{/vendorExtensions.isLong}}{{#vendorExtensions.isBool}}try
{
params.m_{{paramName}} = (req.get_param_value("{{baseName}}") == "true");
}
catch (const std::exception& e)
{
errors.push_back("Invalid query parameter '{{baseName}}': " + std::string(e.what()));
}{{/vendorExtensions.isBool}}{{#vendorExtensions.isDouble}}try
{
params.m_{{paramName}} = std::stod(req.get_param_value("{{baseName}}"));
}
catch (const std::exception& e)
{
errors.push_back("Invalid query parameter '{{baseName}}': " + std::string(e.what()));
}{{/vendorExtensions.isDouble}}{{#vendorExtensions.isFloat}}try
{
params.m_{{paramName}} = std::stof(req.get_param_value("{{baseName}}"));
}
catch (const std::exception& e)
{
errors.push_back("Invalid query parameter '{{baseName}}': " + std::string(e.what()));
}{{/vendorExtensions.isFloat}}{{^vendorExtensions.isObject}}{{^vendorExtensions.isArray}}{{^vendorExtensions.isEnum}}{{^vendorExtensions.isString}}{{^vendorExtensions.isInt}}{{^vendorExtensions.isLong}}{{^vendorExtensions.isBool}}{{^vendorExtensions.isDouble}}{{^vendorExtensions.isFloat}}// Fallback: direct assignment
params.m_{{paramName}} = req.get_param_value("{{baseName}}");{{/vendorExtensions.isFloat}}{{/vendorExtensions.isDouble}}{{/vendorExtensions.isBool}}{{/vendorExtensions.isLong}}{{/vendorExtensions.isInt}}{{/vendorExtensions.isString}}{{/vendorExtensions.isEnum}}{{/vendorExtensions.isArray}}{{/vendorExtensions.isObject}}
}{{^vendorExtensions.isRequired}}{{#vendorExtensions.hasDefaultValue}}
else
{
// Use default value for optional parameter
params.m_{{paramName}} = {{{vendorExtensions.defaultValue}}};
}{{/vendorExtensions.hasDefaultValue}}{{/vendorExtensions.isRequired}}
{{/queryParams}}
{{#headerParams}}
{{#-first}}
{{/-first}}
// Header Parameters - {{baseName}}
if (!req.get_header_value("{{baseName}}").empty())
{
{{#vendorExtensions.isObject}}try
{
// Parse JSON object from header
auto val = req.get_header_value("{{baseName}}");
params.m_{{paramName}} = nlohmann::json::parse(val);
}
catch (const std::exception& e)
{
errors.push_back("Invalid header parameter '{{baseName}}': " + std::string(e.what()));
}{{/vendorExtensions.isObject}}{{#vendorExtensions.isArray}}try
{
// Header arrays may be comma-separated
auto val = req.get_header_value("{{baseName}}");
std::stringstream ss(val);
std::string item;{{#vendorExtensions.isOptional}}
if (!params.m_{{paramName}}.has_value())
{
params.m_{{paramName}} = std::vector<{{{items.dataType}}}>{};
}{{/vendorExtensions.isOptional}}
while (std::getline(ss, item, ','))
{
if (!item.empty())
{
{{#vendorExtensions.isOptional}}
params.m_{{paramName}}->emplace_back(item);
{{/vendorExtensions.isOptional}}
{{^vendorExtensions.isOptional}}
params.m_{{paramName}}.emplace_back(item);
{{/vendorExtensions.isOptional}}
}
}
}
catch (const std::exception& e)
{
errors.push_back("Invalid header parameter '{{baseName}}': " + std::string(e.what()));
}{{/vendorExtensions.isArray}}{{#vendorExtensions.isEnum}}try
{
params.m_{{paramName}} = {{enumFromStringHelper}}(req.get_header_value("{{baseName}}"));
}
catch (const std::exception& e)
{
errors.push_back("Invalid header parameter '{{baseName}}': " + std::string(e.what()));
}{{/vendorExtensions.isEnum}}{{#vendorExtensions.isString}}params.m_{{paramName}} = req.get_header_value("{{baseName}}");{{/vendorExtensions.isString}}{{#vendorExtensions.isInt}}try
{
params.m_{{paramName}} = std::stoi(req.get_header_value("{{baseName}}"));
}
catch (const std::exception& e)
{
errors.push_back("Invalid header parameter '{{baseName}}': " + std::string(e.what()));
}{{/vendorExtensions.isInt}}{{#vendorExtensions.isLong}}try
{
params.m_{{paramName}} = std::stoll(req.get_header_value("{{baseName}}"));
}
catch (const std::exception& e)
{
errors.push_back("Invalid header parameter '{{baseName}}': " + std::string(e.what()));
}{{/vendorExtensions.isLong}}{{#vendorExtensions.isBool}}try
{
params.m_{{paramName}} = (req.get_header_value("{{baseName}}") == "true");
}
catch (const std::exception& e)
{
errors.push_back("Invalid header parameter '{{baseName}}': " + std::string(e.what()));
}{{/vendorExtensions.isBool}}{{#vendorExtensions.isDouble}}try
{
params.m_{{paramName}} = std::stod(req.get_header_value("{{baseName}}"));
}
catch (const std::exception& e)
{
errors.push_back("Invalid header parameter '{{baseName}}': " + std::string(e.what()));
}{{/vendorExtensions.isDouble}}{{#vendorExtensions.isFloat}}try
{
params.m_{{paramName}} = std::stof(req.get_header_value("{{baseName}}"));
}
catch (const std::exception& e)
{
errors.push_back("Invalid header parameter '{{baseName}}': " + std::string(e.what()));
}{{/vendorExtensions.isFloat}}{{^vendorExtensions.isObject}}{{^vendorExtensions.isArray}}{{^vendorExtensions.isEnum}}{{^vendorExtensions.isString}}{{^vendorExtensions.isInt}}{{^vendorExtensions.isLong}}{{^vendorExtensions.isBool}}{{^vendorExtensions.isDouble}}{{^vendorExtensions.isFloat}}// Fallback: direct assignment
params.m_{{paramName}} = req.get_header_value("{{baseName}}");{{/vendorExtensions.isFloat}}{{/vendorExtensions.isDouble}}{{/vendorExtensions.isBool}}{{/vendorExtensions.isLong}}{{/vendorExtensions.isInt}}{{/vendorExtensions.isString}}{{/vendorExtensions.isEnum}}{{/vendorExtensions.isArray}}{{/vendorExtensions.isObject}}
}{{^vendorExtensions.isRequired}}{{#vendorExtensions.hasDefaultValue}}
else
{
// Use default value for optional parameter
params.m_{{paramName}} = {{{vendorExtensions.defaultValue}}};
}{{/vendorExtensions.hasDefaultValue}}{{/vendorExtensions.isRequired}}
{{/headerParams}}
{{#pathParams}}
{{#-first}}
{{/-first}}
// Path Parameters - {{baseName}} (index: {{vendorExtensions.pathIndex}})
if (req.matches.size() < {{vendorExtensions.pathIndex}} + 1)
{
errors.push_back("Missing path parameter '{{baseName}}'");
}
else
{
try
{
{{#vendorExtensions.isObject}}
// Parse JSON object from path param (rare)
auto val = req.matches[{{vendorExtensions.pathIndex}}];
params.m_{{paramName}} = nlohmann::json::parse(val);
{{/vendorExtensions.isObject}}
{{#vendorExtensions.isArray}}
// Path arrays may be delimited (e.g., comma, pipe, etc.)
auto val = req.matches[{{vendorExtensions.pathIndex}}];
std::stringstream ss(val);
std::string item;{{#vendorExtensions.isOptional}}
if (!params.m_{{paramName}}.has_value())
{
params.m_{{paramName}} = std::vector<{{{items.dataType}}}>{};
}{{/vendorExtensions.isOptional}}
while (std::getline(ss, item, ','))
{
if (!item.empty())
{
{{#vendorExtensions.isOptional}}
params.m_{{paramName}}->emplace_back(item);
{{/vendorExtensions.isOptional}}
{{^vendorExtensions.isOptional}}
params.m_{{paramName}}.emplace_back(item);
{{/vendorExtensions.isOptional}}
}
}
{{/vendorExtensions.isArray}}
{{#vendorExtensions.isEnum}}
params.m_{{paramName}} = {{enumFromStringHelper}}(req.matches[{{vendorExtensions.pathIndex}}]);
{{/vendorExtensions.isEnum}}
{{#vendorExtensions.isString}}
params.m_{{paramName}} = req.matches[{{vendorExtensions.pathIndex}}];
{{/vendorExtensions.isString}}
{{#vendorExtensions.isInt}}
params.m_{{paramName}} = std::stoi(req.matches[{{vendorExtensions.pathIndex}}]);
{{/vendorExtensions.isInt}}
{{#vendorExtensions.isLong}}
params.m_{{paramName}} = std::stoll(req.matches[{{vendorExtensions.pathIndex}}]);
{{/vendorExtensions.isLong}}
{{#vendorExtensions.isBool}}
params.m_{{paramName}} = (req.matches[{{vendorExtensions.pathIndex}}] == "true");
{{/vendorExtensions.isBool}}
{{#vendorExtensions.isDouble}}
params.m_{{paramName}} = std::stod(req.matches[{{vendorExtensions.pathIndex}}]);
{{/vendorExtensions.isDouble}}
{{#vendorExtensions.isFloat}}
params.m_{{paramName}} = std::stof(req.matches[{{vendorExtensions.pathIndex}}]);
{{/vendorExtensions.isFloat}}
}
catch (const std::exception& e)
{
errors.push_back("Invalid path parameter '{{baseName}}': " + std::string(e.what()));
}
}
{{/pathParams}}
{{#cookieParams}}
{{#-first}}
{{/-first}}
// Cookie Parameters - {{baseName}}
try
{
auto cookieHeader = req.get_header_value("Cookie");
if (!cookieHeader.empty())
{
std::string cookieValue;
std::string key = "{{baseName}}=";
size_t start = cookieHeader.find(key);
if (start != std::string::npos)
{
start += key.length();
size_t end = cookieHeader.find(";", start);
if (end == std::string::npos) end = cookieHeader.length();
cookieValue = cookieHeader.substr(start, end - start);
{{#vendorExtensions.isObject}}params.m_{{paramName}} = nlohmann::json::parse(cookieValue);{{/vendorExtensions.isObject}}{{#vendorExtensions.isArray}}{{#vendorExtensions.isOptional}}
if (!params.m_{{paramName}}.has_value())
{
params.m_{{paramName}} = std::vector<{{{items.dataType}}}>{};
}{{/vendorExtensions.isOptional}}
std::stringstream ss(cookieValue);
std::string item;
while (std::getline(ss, item, ','))
{
if (!item.empty())
{
{{#vendorExtensions.isOptional}}
params.m_{{paramName}}->emplace_back(item);
{{/vendorExtensions.isOptional}}
{{^vendorExtensions.isOptional}}
params.m_{{paramName}}.emplace_back(item);
{{/vendorExtensions.isOptional}}
}
}{{/vendorExtensions.isArray}}{{#vendorExtensions.isEnum}}params.m_{{paramName}} = {{enumFromStringHelper}}(cookieValue);{{/vendorExtensions.isEnum}}{{#vendorExtensions.isString}}params.m_{{paramName}} = cookieValue;{{/vendorExtensions.isString}}{{#vendorExtensions.isInt}}params.m_{{paramName}} = std::stoi(cookieValue);{{/vendorExtensions.isInt}}{{#vendorExtensions.isLong}}params.m_{{paramName}} = std::stoll(cookieValue);{{/vendorExtensions.isLong}}{{#vendorExtensions.isBool}}params.m_{{paramName}} = (cookieValue == "true");{{/vendorExtensions.isBool}}{{#vendorExtensions.isDouble}}params.m_{{paramName}} = std::stod(cookieValue);{{/vendorExtensions.isDouble}}{{#vendorExtensions.isFloat}}params.m_{{paramName}} = std::stof(cookieValue);{{/vendorExtensions.isFloat}}{{^vendorExtensions.isObject}}{{^vendorExtensions.isArray}}{{^vendorExtensions.isEnum}}{{^vendorExtensions.isString}}{{^vendorExtensions.isInt}}{{^vendorExtensions.isLong}}{{^vendorExtensions.isBool}}{{^vendorExtensions.isDouble}}{{^vendorExtensions.isFloat}}params.m_{{paramName}} = cookieValue;{{/vendorExtensions.isFloat}}{{/vendorExtensions.isDouble}}{{/vendorExtensions.isBool}}{{/vendorExtensions.isLong}}{{/vendorExtensions.isInt}}{{/vendorExtensions.isString}}{{/vendorExtensions.isEnum}}{{/vendorExtensions.isArray}}{{/vendorExtensions.isObject}}
}{{^vendorExtensions.isRequired}}{{#vendorExtensions.hasDefaultValue}}
else
{
// Use default value for optional parameter
params.m_{{paramName}} = {{{vendorExtensions.defaultValue}}};
}{{/vendorExtensions.hasDefaultValue}}{{/vendorExtensions.isRequired}}
}{{^vendorExtensions.isRequired}}{{#vendorExtensions.hasDefaultValue}}
else
{
// Use default value for optional parameter
params.m_{{paramName}} = {{{vendorExtensions.defaultValue}}};
}{{/vendorExtensions.hasDefaultValue}}{{/vendorExtensions.isRequired}}
}
catch (const std::exception& e)
{
errors.push_back("Invalid cookie parameter '{{baseName}}': " + std::string(e.what()));
}
{{/cookieParams}}
// Return errors via out-parameter, return false if any errors
if (!errors.empty())
{
paramErrors = std::move(errors);
return false;
}
return true;
}
{{/hasAnyRequestSchema}}
{{#hasAnyResponseSchema}}
void {{apiClassnameInPascalCase}}::handle{{responseType}}(const {{responseType}}& result, httplib::Response& res)
{
{{#hasSingleResponseType}}
// Single response type
res.status = {{#successCodeToTypes}}{{successConstName}}{{/successCodeToTypes}}{{#errorCodeToTypes}}{{errorConstName}}{{/errorCodeToTypes}};
nlohmann::json responseJson;
to_json(responseJson, result);
res.set_content(responseJson.dump(), "application/json");
{{/hasSingleResponseType}}
{{^hasSingleResponseType}}
std::visit([&](const auto& value)
{
using T = std::decay_t<decltype(value)>;
{{#successCodeToTypes}}{{#-first}}
// Success types
{{/-first}}{{^-first}}else {{/-first}}if constexpr (std::is_same_v<T, {{successType}}>)
{
res.status = {{successConstName}};
nlohmann::json responseJson;
to_json(responseJson, value);
res.set_content(responseJson.dump(), "application/json");
}{{/successCodeToTypes}}{{#errorCodeToTypes}}{{#-first}}
// Error types{{/-first}}
else if constexpr (std::is_same_v<T, {{errorType}}>)
{
res.status = {{errorConstName}};
nlohmann::json errorJson = value;
res.set_content(errorJson.dump(), "application/json");
}{{/errorCodeToTypes}}{{^successCodeToTypes}}{{^errorCodeToTypes}}
// No response types defined
res.status = {{statusCodeToConst.500}};
res.set_content("{\"error\": \"No response handler defined\"}", "application/json");
{{/errorCodeToTypes}}{{/successCodeToTypes}}
}, result);
{{/hasSingleResponseType}}
}
{{/hasAnyResponseSchema}}
{{/vendorExtensions}}
{{/operation}}
{{/operations}}
{{#hasAnyAuth}}
bool {{apiClassnameInPascalCase}}::performAuthentication(
const httplib::Request& req,
std::shared_ptr<AuthenticationManager> auth,
httplib::Response& res)
{
if (!auth)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "AuthenticationManager not configured";
res.status = {{statusCodeToConst.500}};
res.set_content(errorJson.dump(), "application/json");
return false;
}
{{#hasApiKeyAuth}}
{{#apiKeyAuth}}
{{#isKeyInHeader}}
if (req.has_header("{{keyParamName}}"))
{
if (auth->validateApiKey(req.get_header_value("{{keyParamName}}"))) return true;
}
{{/isKeyInHeader}}
{{#isKeyInQuery}}
if (req.has_param("{{keyParamName}}"))
{
if (auth->validateApiKey(req.get_param_value("{{keyParamName}}"))) return true;
}
{{/isKeyInQuery}}
{{#isKeyInCookie}}
{
auto cookieHeader = req.get_header_value("Cookie");
std::string key = "{{keyParamName}}=";
size_t start = cookieHeader.find(key);
if (start != std::string::npos)
{
start += key.length();
size_t end = cookieHeader.find(";", start);
if (end == std::string::npos) end = cookieHeader.length();
std::string cookieValue = cookieHeader.substr(start, end - start);
if (auth->validateApiKey(cookieValue)) return true;
}
}
{{/isKeyInCookie}}
{{/apiKeyAuth}}
{{/hasApiKeyAuth}}
{{#hasBasicAuth}}
if (req.has_header("Authorization"))
{
auto authHeader = req.get_header_value("Authorization");
if (authHeader.find("Basic ") == 0)
{
std::string credentials = authHeader.substr(6);
if (auth->validateBasicAuth(credentials, "")) return true;
}
}
{{/hasBasicAuth}}
{{#hasBearerAuth}}
if (req.has_header("Authorization"))
{
auto authHeader = req.get_header_value("Authorization");
if (authHeader.find("Bearer ") == 0)
{
std::string token = authHeader.substr(7);
if (auth->validateBearerToken(token)) return true;
}
}
{{/hasBearerAuth}}
{{#hasOAuth2}}
if (req.has_header("Authorization"))
{
auto authHeader = req.get_header_value("Authorization");
if (authHeader.find("Bearer ") == 0)
{
std::string token = authHeader.substr(7);
{{#oauth2Auth}}
std::vector<std::string> requiredScopes = { {{#scopes}}"{{scope}}"{{^-last}}, {{/-last}}{{/scopes}} };
if (auth->validateOAuth2(token, requiredScopes)) return true;
{{/oauth2Auth}}
}
}
{{/hasOAuth2}}
return false;
}
{{/hasAnyAuth}}
{{#operations}}
{{#operation}}
{{#vendorExtensions}}
void {{apiClassnameInPascalCase}}::handle{{operationIdPascalCase}}Request([[maybe_unused]] const httplib::Request& req, httplib::Response& res{{#hasAuth}}, std::shared_ptr<AuthenticationManager> auth{{/hasAuth}})
{
try
{
{{#hasAuth}}
if (!performAuthentication(req, auth, res))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Authentication required";
res.status = {{statusCodeToConst.401}};
res.set_content(errorJson.dump(), "application/json");
return;
}
{{/hasAuth}}{{#hasAnyRequestSchema}}
{{requestType}} params;
std::vector<std::string> paramErrors;
if (!parse{{operationIdPascalCase}}Params(req, params, paramErrors))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid parameters";
errorJson["errors"] = paramErrors;
res.status = {{statusCodeToConst.400}};
res.set_content(errorJson.dump(), "application/json");
return;
}
{{#hasAnyResponseSchema}}
auto result = {{handlerFunctionName}}(params);
handle{{responseType}}(result, res);
{{/hasAnyResponseSchema}}{{^hasAnyResponseSchema}}
{{handlerFunctionName}}(params);
res.status = {{statusCodeToConst.204}};
{{/hasAnyResponseSchema}}{{/hasAnyRequestSchema}}{{^hasAnyRequestSchema}}{{#hasAnyResponseSchema}}
auto result = {{handlerFunctionName}}();
handle{{responseType}}(result, res);
{{/hasAnyResponseSchema}}{{^hasAnyResponseSchema}}
{{handlerFunctionName}}();
res.status = {{statusCodeToConst.204}};
{{/hasAnyResponseSchema}}{{/hasAnyRequestSchema}}
}{{#requestModel}}
catch (const nlohmann::json::parse_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = {{statusCodeToConst.400}};
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::invalid_iterator& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = {{statusCodeToConst.400}};
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::type_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = {{statusCodeToConst.400}};
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::out_of_range& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = {{statusCodeToConst.400}};
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::other_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = {{statusCodeToConst.400}};
res.set_content(errorJson.dump(), "application/json");
}{{/requestModel}}{{#vendorExtensions.hasPrimitiveParams}}
catch (const std::invalid_argument& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid parameter: " + std::string(e.what());
res.status = {{statusCodeToConst.400}};
res.set_content(errorJson.dump(), "application/json");
}
catch (const std::out_of_range& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid parameter: " + std::string(e.what());
res.status = {{statusCodeToConst.400}};
res.set_content(errorJson.dump(), "application/json");
}{{/vendorExtensions.hasPrimitiveParams}}{{^requestModel}}{{^vendorExtensions.hasPrimitiveParams}}
catch (const std::exception& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Internal error: " + std::string(e.what());
res.status = {{statusCodeToConst.500}};
res.set_content(errorJson.dump(), "application/json");
}{{/vendorExtensions.hasPrimitiveParams}}{{/requestModel}}
}
{{/vendorExtensions}}
{{/operation}}
{{/operations}}
void {{apiClassnameInPascalCase}}::registerRoutes(httplib::Server& svr{{#hasAnyAuth}}, std::shared_ptr<AuthenticationManager> auth{{/hasAnyAuth}})
{
{{#operations}}
{{#operation}}
{{#vendorExtensions}}
svr.{{httpMethod}}("{{path}}", [this{{#hasAuth}}, auth{{/hasAuth}}]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handle{{operationIdPascalCase}}Request(req, res{{#hasAuth}}, auth{{/hasAuth}});
});
{{/vendorExtensions}}
{{/operation}}
{{/operations}}
}
} // namespace {{apiNamespace}}

View File

@@ -0,0 +1,94 @@
{{>License}}
#include <httplib.h>
#include <iostream>
#include <memory>
{{#apiInfo}}
{{#apis}}
{{#operations}}
#include "api/{{apiClassnameInPascalCase}}Impl.h"
{{/operations}}
{{/apis}}
{{/apiInfo}}
{{#hasAuthMethods}}
#include "api/AuthenticationManager.h"
// Example AuthenticationManager implementation
class SimpleAuthManager : public {{#apiInfo}}{{#apis}}{{#-first}}{{apiNamespace}}{{/-first}}{{/apis}}{{/apiInfo}}::AuthenticationManager {
public:
bool validateApiKey(const std::string& key) override {
// TODO: Implement your API key validation logic
return key == "your-api-key"; // Replace with actual validation
}
bool validateBearerToken(const std::string& token) override {
// TODO: Implement your Bearer token validation logic
return !token.empty(); // Replace with actual validation
}
bool validateBasicAuth(const std::string& username, const std::string& password) override {
// TODO: Implement your Basic auth validation logic
return username == "admin" && password == "admin"; // Replace with actual validation
}
bool validateOAuth2(const std::string& token, const std::vector<std::string>& scopes) override {
// TODO: Implement your OAuth2 validation logic
return !token.empty(); // Replace with actual validation
}
};
{{/hasAuthMethods}}
int main() {
httplib::Server svr;
std::cout << "Starting {{projectName}} server..." << std::endl;
{{#hasAuthMethods}}
// Create authentication manager
auto authManager = std::make_shared<SimpleAuthManager>();
{{/hasAuthMethods}}
{{#apiInfo}}
{{#apis}}
{{#operations}}
// Register {{apiClassnameInPascalCase}} routes
auto {{#lambda.camelcase}}{{apiClassnameInPascalCase}}{{/lambda.camelcase}}Impl = std::make_shared<{{apiNamespace}}::{{apiClassnameInPascalCase}}Impl>();
{{#lambda.camelcase}}{{apiClassnameInPascalCase}}{{/lambda.camelcase}}Impl->registerRoutes(svr{{#hasAnyAuth}}, authManager{{/hasAnyAuth}});
{{/operations}}
{{/apis}}
{{/apiInfo}}
// Health check endpoint
svr.Get("/health", [](const httplib::Request&, httplib::Response& res) {
res.set_content("{\"status\": \"ok\"}", "application/json");
});
// Configure server
const char* host = "0.0.0.0";
int port = 8080;
// Get port from environment variable if available
const char* portEnv = std::getenv("PORT");
if (portEnv != nullptr)
{
try
{
port = std::stoi(portEnv);
}
catch (...)
{
std::cerr << "Invalid PORT environment variable, using default: " << port << std::endl;
}
}
std::cout << "Server listening on " << host << ":" << port << std::endl;
std::cout << "Health check available at: http://" << host << ":" << port << "/health" << std::endl;
// Start server
if (!svr.listen(host, port)) {
std::cerr << "Failed to start server on " << host << ":" << port << std::endl;
return 1;
}
return 0;
}

View File

@@ -0,0 +1,249 @@
{{>License}}
#pragma once
{{#models}}
{{#model}}
// System headers
#include <nlohmann/json.hpp>
{{#vendorExtensions.filteredImports}}
{{{.}}}
{{/vendorExtensions.filteredImports}}
{{#parent}}{{#-first}}// Project headers{{/-first}}
#include "{{parent}}.h"
{{/parent}}
namespace {{vendorExtensions.modelNamespace}} {
{{#vendorExtensions.isOneOfSchema}}
// oneOf schema - type alias for std::variant
using {{vendorExtensions.modelClassName}} = std::variant<
{{#vendorExtensions.oneOfTypes}}{{.}}{{^-last}},
{{/-last}}{{/vendorExtensions.oneOfTypes}}>;
// JSON serialization functions (inline for header-only)
{{#vendorExtensions.discriminatorProperty}}
inline void from_json(const nlohmann::json& j, {{vendorExtensions.modelClassName}}& obj) {
if (!j.contains("{{vendorExtensions.discriminatorProperty}}")) {
throw nlohmann::json::type_error::create(302, "Discriminator property '{{vendorExtensions.discriminatorProperty}}' not found in JSON", &j);
}
std::string discriminatorValue = j["{{vendorExtensions.discriminatorProperty}}"].get<std::string>();
{{#vendorExtensions.discriminatorMapping}}
if (discriminatorValue == "{{value}}") {
obj = j.get<{{key}}>();
return;
}
{{/vendorExtensions.discriminatorMapping}}
throw nlohmann::json::type_error::create(302, "Unknown discriminator value: " + discriminatorValue, &j);
}
{{/vendorExtensions.discriminatorProperty}}
{{^vendorExtensions.discriminatorProperty}}
inline void from_json(const nlohmann::json& j, {{vendorExtensions.modelClassName}}& obj)
{
{{#vendorExtensions.oneOfTypes}}
try
{
obj = j.get<{{.}}>();
return;
}
catch (const nlohmann::json::exception&)
{
// Type mismatch, try next variant alternative
}
{{/vendorExtensions.oneOfTypes}}
throw nlohmann::json::type_error::create(302, "Could not deserialize into any variant type of {{vendorExtensions.modelClassName}}", &j);
}
{{/vendorExtensions.discriminatorProperty}}
inline void to_json(nlohmann::json& j, const {{vendorExtensions.modelClassName}}& obj)
{
std::visit([&j](const auto& val) { j = nlohmann::json(val); }, obj);
}
{{/vendorExtensions.isOneOfSchema}}
{{#vendorExtensions.isAnyOfSchema}}
// anyOf schema - type alias for std::variant
using {{vendorExtensions.modelClassName}} = std::variant<
{{#vendorExtensions.anyOfTypes}} {{.}}{{^-last}},
{{/-last}}{{/vendorExtensions.anyOfTypes}} >;
// JSON serialization functions (inline for header-only)
{{#vendorExtensions.discriminatorProperty}}
inline void from_json(const nlohmann::json& j, {{vendorExtensions.modelClassName}}& obj) {
if (!j.contains("{{vendorExtensions.discriminatorProperty}}")) {
throw nlohmann::json::type_error::create(302, "Discriminator property '{{vendorExtensions.discriminatorProperty}}' not found in JSON", &j);
}
std::string discriminatorValue = j["{{vendorExtensions.discriminatorProperty}}"].get<std::string>();
{{#vendorExtensions.discriminatorMapping}}
if (discriminatorValue == "{{value}}") {
obj = j.get<{{key}}>();
return;
}
{{/vendorExtensions.discriminatorMapping}}
throw nlohmann::json::type_error::create(302, "Unknown discriminator value: " + discriminatorValue, &j);
}
{{/vendorExtensions.discriminatorProperty}}
{{^vendorExtensions.discriminatorProperty}}
inline void from_json(const nlohmann::json& j, {{vendorExtensions.modelClassName}}& obj)
{
{{#vendorExtensions.anyOfTypes}}
try
{
obj = j.get<{{.}}>();
return;
}
catch (const nlohmann::json::exception&)
{
// Type mismatch, try next variant alternative
}
{{/vendorExtensions.anyOfTypes}}
throw nlohmann::json::type_error::create(302, "Could not deserialize into any variant type of {{vendorExtensions.modelClassName}}", &j);
}
{{/vendorExtensions.discriminatorProperty}}
inline void to_json(nlohmann::json& j, const {{vendorExtensions.modelClassName}}& obj)
{
std::visit([&j](const auto& val) { j = nlohmann::json(val); }, obj);
}
{{/vendorExtensions.isAnyOfSchema}}
{{^vendorExtensions.isOneOfSchema}}
{{^vendorExtensions.isAnyOfSchema}}
{{#vars}}
{{#isUnionType}}
// Union type for anyOf/oneOf property
using {{unionTypeName}} = std::variant<
{{#unionTypes}} {{.}}{{^-last}},{{/-last}}
{{/unionTypes}}>;
// Inline serialization for union type
inline void to_json(nlohmann::json& j, const {{unionTypeName}}& v)
{
std::visit([&j](const auto& val) { j = nlohmann::json(val); }, v);
}
inline void from_json(const nlohmann::json& j, {{unionTypeName}}& v)
{
{{#unionTypes}}
try
{
v = j.get<{{.}}>();
return;
}
catch (...)
{
// Try next type
}
{{/unionTypes}}
throw nlohmann::json::type_error::create(302, "Could not deserialize into any variant type of {{unionTypeName}}", &j);
}
{{/isUnionType}}
{{/vars}}
class {{vendorExtensions.modelClassName}}{{#parent}} : public {{parent}}{{/parent}}
{
public:
{{#vars}}
{{#isEnum}}
{{#-first}}
// ===================
// ===== Enums =======
// ===================
{{/-first}}
enum class {{enumName}} {
{{#allowableValues.values}}
{{.}}{{^-last}},{{/-last}}
{{/allowableValues.values}}
};
// Enum conversion functions (definitions in .cpp)
static std::string {{enumName}}ToString({{enumName}} value);
static {{enumName}} {{enumName}}FromString(const std::string& str);
{{/isEnum}}
{{/vars}}
{{vendorExtensions.modelClassName}}();
virtual ~{{vendorExtensions.modelClassName}}() = default;
// Getters and setters
{{#vars}}
[[nodiscard]] {{#isUnionType}}{{unionTypeName}}{{/isUnionType}}{{^isUnionType}}{{{datatypeWithEnum}}}{{/isUnionType}} {{getter}}() const;
void {{setter}}(const {{#isUnionType}}{{unionTypeName}}{{/isUnionType}}{{^isUnionType}}{{{datatypeWithEnum}}}{{/isUnionType}}& {{nameInCamelCase}});
{{/vars}}
{{#vars}}{{#isEnum}}{{^isArray}}{{#-first}}
// =============================================================================
// Friend Enum Serialization Helpers (Required for NLOHMANN JSON serialization)
// =============================================================================
// These friend functions must be declared inside the class because:
// 1. The enum types are nested and don't exist before the class is defined
// 2. NLOHMANN macros need custom serialization for enum types (uses ToString/FromString)
// 3. The 'friend' keyword makes them free functions in the namespace (not member functions)
// so ADL (Argument-Dependent Lookup) can find them during JSON serialization
// =============================================================================
{{/-first}}{{^vendorExtensions.isOptionalEnum}}
// Serialization helpers for {{enumName}}
friend inline void to_json(nlohmann::json& j, const {{enumName}}& e)
{
j = {{enumName}}ToString(e);
}
friend inline void from_json(const nlohmann::json& j, {{enumName}}& e)
{
e = {{enumName}}FromString(j.get<std::string>());
}
{{/vendorExtensions.isOptionalEnum}}
{{#vendorExtensions.isOptionalEnum}}
// Serialization helpers for std::optional<{{enumName}}>
friend inline void to_json(nlohmann::json& j, const std::optional<{{enumName}}>& opt)
{
if (opt.has_value())
{
j = {{enumName}}ToString(opt.value());
}
else
{
j = nullptr;
}
}
friend inline void from_json(const nlohmann::json& j, std::optional<{{enumName}}>& opt)
{
if (j.is_null())
{
opt = std::nullopt;
}
else
{
opt = {{enumName}}FromString(j.get<std::string>());
}
}
{{/vendorExtensions.isOptionalEnum}}
{{/isArray}}{{/isEnum}}{{/vars}}
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE({{vendorExtensions.modelClassName}},
{{#vars}} {{nameInCamelCase}}{{^-last}},{{/-last}}{{/vars}})
private:
{{#vars}}
{{#isUnionType}}
{{unionTypeName}} {{nameInCamelCase}};
{{/isUnionType}}
{{^isUnionType}}
{{{datatypeWithEnum}}} {{nameInCamelCase}};
{{/isUnionType}}
{{/vars}}
};
{{/vendorExtensions.isAnyOfSchema}}
{{/vendorExtensions.isOneOfSchema}}
} // namespace {{vendorExtensions.modelNamespace}}
{{/model}}
{{/models}}

View File

@@ -0,0 +1,83 @@
{{>License}}
{{#models}}
{{#model}}
{{^vendorExtensions.isOneOfSchema}}
{{^vendorExtensions.isAnyOfSchema}}
#include "{{vendorExtensions.modelClassName}}.h"
namespace {{vendorExtensions.modelNamespace}} {
{{vendorExtensions.modelClassName}}::{{vendorExtensions.modelClassName}}()
{{#vars}}
{{#defaultValue}}
{{#-first}}:{{/-first}}{{^-first}},{{/-first}} {{nameInCamelCase}}({{{defaultValue}}})
{{/defaultValue}}
{{/vars}}
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
{{#vars}}
{{#-first}}
// ===================
// ===== Getters =====
// ===================
{{/-first}}
{{! For enums, construct return type with proper class qualification }}
{{#isEnum}}{{#isContainer}}std::vector<{{model.vendorExtensions.modelClassName}}::{{enumName}}>{{/isContainer}}{{^isContainer}}{{#vendorExtensions.isOptionalEnum}}std::optional<{{model.vendorExtensions.modelClassName}}::{{enumName}}>{{/vendorExtensions.isOptionalEnum}}{{^vendorExtensions.isOptionalEnum}}{{model.vendorExtensions.modelClassName}}::{{enumName}}{{/vendorExtensions.isOptionalEnum}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{datatypeWithEnum}}}{{/isEnum}} {{model.vendorExtensions.modelClassName}}::{{getter}}() const
{
return {{nameInCamelCase}};
}
{{/vars}}
{{#vars}}
{{#-first}}
// ===================
// ===== Setters =====
// ===================
{{/-first}}
void {{model.vendorExtensions.modelClassName}}::{{setter}}(const {{{datatypeWithEnum}}}& {{nameInCamelCase}}Obj)
{
{{nameInCamelCase}} = {{nameInCamelCase}}Obj;
}
{{/vars}}
{{#vars}}{{#isEnum}}{{^isArray}}
// =========================================
// ===== Enum {{enumName}} Conversions =====
// =========================================
std::string {{classname}}::{{enumName}}ToString({{classname}}::{{enumName}} value)
{
switch (value)
{
{{#vendorExtensions.enumCases}}
case {{enumName}}::{{name}}: return "{{value}}";
{{/vendorExtensions.enumCases}}
default: return {};
}
}
{{classname}}::{{enumName}} {{classname}}::{{enumName}}FromString(const std::string& str)
{
{{#vendorExtensions.enumCases}}
if (str == "{{value}}")
{
return {{enumName}}::{{name}};
}
{{/vendorExtensions.enumCases}}
throw std::invalid_argument("Invalid enum value");
}
{{/isArray}}{{/isEnum}}{{/vars}}
{{/vendorExtensions.isAnyOfSchema}}
{{/vendorExtensions.isOneOfSchema}}
{{^vendorExtensions.isOneOfSchema}}{{^vendorExtensions.isAnyOfSchema}}
} // namespace {{vendorExtensions.modelNamespace}}
{{/vendorExtensions.isAnyOfSchema}}{{/vendorExtensions.isOneOfSchema}}
{{/model}}
{{/models}}

View File

@@ -0,0 +1,301 @@
/*
* Copyright 2026 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.cpphttplib;
import org.openapitools.codegen.*;
import org.openapitools.codegen.languages.CppHttplibServerCodegen;
import io.swagger.v3.oas.models.media.*;
import org.testng.Assert;
import org.testng.annotations.Test;
@SuppressWarnings("static-method")
public class CppHttplibServerCodegenModelTest {
@Test(description = "convert model with enum property")
public void enumPropertyTest() {
final CppHttplibServerCodegen codegen = new CppHttplibServerCodegen();
codegen.processOpts();
ObjectSchema schema = new ObjectSchema();
StringSchema statusSchema = new StringSchema();
statusSchema.setEnum(java.util.Arrays.asList("available", "pending", "sold"));
schema.addProperty("status", statusSchema);
final CodegenModel model = codegen.fromModel("PetStatus", schema);
Assert.assertEquals(model.name, "PetStatus");
Assert.assertNotNull(model.vars);
Assert.assertEquals(model.vars.size(), 1);
CodegenProperty statusProp = model.vars.get(0);
// Check that isEnum flag is set
Assert.assertTrue(statusProp.isEnum, "isEnum flag should be true for enum properties");
// Check vendor extensions for enum handling
Assert.assertNotNull(statusProp.vendorExtensions, "vendorExtensions should not be null");
Assert.assertTrue((boolean) statusProp.vendorExtensions.getOrDefault("isEnum", false),
"isEnum vendor extension should be true");
// Check enum values
java.util.List<?> enumValues = (java.util.List<?>) statusProp.vendorExtensions.getOrDefault("values", statusProp._enum);
Assert.assertNotNull(enumValues, "enum values should be present");
Assert.assertEquals(enumValues.size(), 3);
}
@Test(description = "convert a simple model with properties")
public void simpleModelTest() {
final CppHttplibServerCodegen codegen = new CppHttplibServerCodegen();
codegen.processOpts();
// Create a simple schema with properties
ObjectSchema schema = new ObjectSchema();
schema.description("a sample model");
schema.addProperty("id", new IntegerSchema().format("int64"));
schema.addProperty("name", new StringSchema());
schema.addProperty("isActive", new BooleanSchema());
schema.setRequired(java.util.Arrays.asList("id", "name"));
final CodegenModel model = codegen.fromModel("User", schema);
Assert.assertEquals(model.name, "User");
Assert.assertEquals(model.classname, "User");
Assert.assertNotNull(model.vars);
Assert.assertEquals(model.vars.size(), 3);
// Check id property
CodegenProperty idProp = model.vars.get(0);
Assert.assertEquals(idProp.name, "Id");
Assert.assertEquals(idProp.baseName, "id");
Assert.assertEquals(idProp.dataType, "long");
Assert.assertTrue(idProp.required);
// Check name property
CodegenProperty nameProp = model.vars.get(1);
Assert.assertEquals(nameProp.name, "Name");
Assert.assertEquals(nameProp.baseName, "name");
Assert.assertEquals(nameProp.dataType, "std::string");
Assert.assertTrue(nameProp.required);
// Check isActive property
CodegenProperty activeProp = model.vars.get(2);
Assert.assertEquals(activeProp.name, "IsActive");
Assert.assertEquals(activeProp.baseName, "isActive");
Assert.assertEquals(activeProp.dataType, "bool");
Assert.assertFalse(activeProp.required);
}
@Test(description = "convert model with array property")
public void arrayPropertyTest() {
final CppHttplibServerCodegen codegen = new CppHttplibServerCodegen();
codegen.processOpts();
ObjectSchema schema = new ObjectSchema();
schema.addProperty("tags", new ArraySchema().items(new StringSchema()));
final CodegenModel model = codegen.fromModel("ModelWithArray", schema);
Assert.assertEquals(model.vars.size(), 1);
CodegenProperty arrayProp = model.vars.get(0);
Assert.assertEquals(arrayProp.baseName, "tags");
Assert.assertEquals(arrayProp.dataType, "std::vector<std::string>");
Assert.assertTrue(arrayProp.isArray);
// Verify array vendor extensions are set
Assert.assertTrue((boolean) arrayProp.vendorExtensions.getOrDefault("isArray", false),
"isArray vendor extension should be true");
}
@Test(description = "convert model with array of enums")
public void arrayOfEnumsPropertyTest() {
final CppHttplibServerCodegen codegen = new CppHttplibServerCodegen();
codegen.processOpts();
ObjectSchema schema = new ObjectSchema();
StringSchema enumItemSchema = new StringSchema();
enumItemSchema.setEnum(java.util.Arrays.asList("ACTIVE", "INACTIVE", "PENDING"));
schema.addProperty("statuses", new ArraySchema().items(enumItemSchema));
final CodegenModel model = codegen.fromModel("ModelWithEnumArray", schema);
Assert.assertEquals(model.vars.size(), 1);
CodegenProperty arrayProp = model.vars.get(0);
Assert.assertTrue(arrayProp.isArray);
Assert.assertTrue((boolean) arrayProp.vendorExtensions.getOrDefault("isArray", false));
// Verify it detects array of enums
Assert.assertTrue((boolean) arrayProp.vendorExtensions.getOrDefault("isArrayOfEnum", false),
"isArrayOfEnum vendor extension should be true");
}
@Test(description = "convert model with map property")
public void mapPropertyTest() {
final CppHttplibServerCodegen codegen = new CppHttplibServerCodegen();
codegen.processOpts();
ObjectSchema schema = new ObjectSchema();
schema.addProperty("metadata", new MapSchema().additionalProperties(new StringSchema()));
final CodegenModel model = codegen.fromModel("ModelWithMap", schema);
Assert.assertEquals(model.vars.size(), 1);
CodegenProperty mapProp = model.vars.get(0);
Assert.assertEquals(mapProp.name, "Metadata");
Assert.assertEquals(mapProp.dataType, "std::map<std::string, std::string>");
Assert.assertTrue(mapProp.isMap);
// Verify map container flag
Assert.assertTrue((boolean) mapProp.vendorExtensions.getOrDefault("isContainer", false),
"isContainer vendor extension should be true for maps");
}
@Test(description = "convert model with numeric enum property")
public void numericEnumPropertyTest() {
final CppHttplibServerCodegen codegen = new CppHttplibServerCodegen();
codegen.processOpts();
ObjectSchema schema = new ObjectSchema();
IntegerSchema statusSchema = new IntegerSchema();
statusSchema.setEnum(java.util.Arrays.asList(0, 1, 2));
schema.addProperty("userStatus", statusSchema);
final CodegenModel model = codegen.fromModel("UserStatusModel", schema);
Assert.assertEquals(model.vars.size(), 1);
CodegenProperty statusProp = model.vars.get(0);
Assert.assertTrue(statusProp.isEnum);
Assert.assertTrue((boolean) statusProp.vendorExtensions.getOrDefault("isEnum", false));
// Numeric enum values should be converted to valid C++ names (prefixed with underscore)
java.util.List<?> enumValues = (java.util.List<?>) statusProp.vendorExtensions.getOrDefault("values", statusProp._enum);
Assert.assertNotNull(enumValues);
// Check that numeric values are properly converted
Assert.assertTrue(enumValues.stream().anyMatch(v -> v.toString().startsWith("_")),
"Numeric enum values should be prefixed with underscore");
}
@Test(description = "convert enum model")
public void enumModelTest() {
final CppHttplibServerCodegen codegen = new CppHttplibServerCodegen();
codegen.processOpts();
StringSchema enumSchema = new StringSchema();
enumSchema.setEnum(java.util.Arrays.asList("ACTIVE", "INACTIVE", "PENDING"));
final CodegenModel model = codegen.fromModel("Status", enumSchema);
// Note: The C++ httplib server generator may not process enum-only models
// in the same way as regular object models. The model might be null or empty.
if (model != null) {
Assert.assertEquals(model.name, "Status");
// Check if it's marked as an enum in vendor extensions
if (model.vendorExtensions.containsKey("x-is-enum")) {
Assert.assertEquals(model.vendorExtensions.get("x-is-enum"), true);
}
}
}
@Test(description = "convert model with nullable property")
public void nullablePropertyTest() {
final CppHttplibServerCodegen codegen = new CppHttplibServerCodegen();
codegen.processOpts();
StringSchema nullableStringSchema = new StringSchema();
nullableStringSchema.setNullable(true);
ObjectSchema schema = new ObjectSchema();
schema.addProperty("optionalField", nullableStringSchema);
final CodegenModel model = codegen.fromModel("ModelWithNullable", schema);
Assert.assertEquals(model.vars.size(), 1);
CodegenProperty nullableProp = model.vars.get(0);
Assert.assertEquals(nullableProp.name, "OptionalField");
Assert.assertTrue(nullableProp.isNullable);
// Check that isOptional vendor extension is set
Assert.assertTrue((boolean) nullableProp.vendorExtensions.getOrDefault("isOptional", false),
"isOptional vendor extension should be true for nullable fields");
}
@Test(description = "convert model with nested object property")
public void nestedObjectPropertyTest() {
final CppHttplibServerCodegen codegen = new CppHttplibServerCodegen();
codegen.processOpts();
ObjectSchema nestedSchema = new ObjectSchema();
nestedSchema.addProperty("id", new IntegerSchema());
nestedSchema.addProperty("name", new StringSchema());
ObjectSchema schema = new ObjectSchema();
schema.addProperty("user", nestedSchema);
final CodegenModel model = codegen.fromModel("ModelWithNested", schema);
Assert.assertEquals(model.vars.size(), 1);
CodegenProperty nestedProp = model.vars.get(0);
Assert.assertEquals(nestedProp.name, "User");
Assert.assertTrue(nestedProp.isModel);
}
@Test(description = "convert model with composed schema (allOf)")
public void composedSchemaTest() {
final CppHttplibServerCodegen codegen = new CppHttplibServerCodegen();
codegen.processOpts();
// Create base schema
ObjectSchema baseSchema = new ObjectSchema();
baseSchema.addProperty("id", new IntegerSchema());
baseSchema.addProperty("name", new StringSchema());
// Create allOf with additional properties
io.swagger.v3.oas.models.media.ComposedSchema composedSchema = new io.swagger.v3.oas.models.media.ComposedSchema();
composedSchema.addAllOfItem(new Schema<>().$ref("#/components/schemas/Base"));
composedSchema.addProperty("email", new StringSchema());
final CodegenModel model = codegen.fromModel("ExtendedUser", composedSchema);
Assert.assertNotNull(model);
Assert.assertEquals(model.name, "ExtendedUser");
}
@Test(description = "convert model with complex types")
public void complexTypesTest() {
final CppHttplibServerCodegen codegen = new CppHttplibServerCodegen();
codegen.processOpts();
ObjectSchema schema = new ObjectSchema();
// Add various property types
schema.addProperty("intValue", new IntegerSchema());
schema.addProperty("longValue", new IntegerSchema().format("int64"));
schema.addProperty("doubleValue", new NumberSchema());
schema.addProperty("floatValue", new NumberSchema().format("float"));
schema.addProperty("boolValue", new BooleanSchema());
schema.addProperty("dateValue", new DateSchema());
schema.addProperty("dateTimeValue", new DateTimeSchema());
final CodegenModel model = codegen.fromModel("ComplexModel", schema);
Assert.assertEquals(model.vars.size(), 7);
// Verify type mappings
java.util.Map<String, String> dataTypeMap = new java.util.HashMap<>();
for (CodegenProperty var : model.vars) {
dataTypeMap.put(var.baseName, var.dataType);
}
Assert.assertEquals(dataTypeMap.get("intValue"), "int");
Assert.assertEquals(dataTypeMap.get("longValue"), "long");
Assert.assertEquals(dataTypeMap.get("doubleValue"), "double");
Assert.assertEquals(dataTypeMap.get("floatValue"), "float");
Assert.assertEquals(dataTypeMap.get("boolValue"), "bool");
Assert.assertEquals(dataTypeMap.get("dateValue"), "std::string");
Assert.assertEquals(dataTypeMap.get("dateTimeValue"), "std::string");
}
}

View File

@@ -0,0 +1,147 @@
/*
* Copyright 2026 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.cpphttplib;
import static org.openapitools.codegen.utils.StringUtils.underscore;
import org.openapitools.codegen.*;
import org.openapitools.codegen.languages.CppHttplibServerCodegen;
import org.testng.Assert;
import org.testng.annotations.Test;
public class CppHttplibServerCodegenTest {
CppHttplibServerCodegen codegen = new CppHttplibServerCodegen();
@Test
public void testInitialConfigValues() throws Exception {
codegen.processOpts();
Assert.assertEquals(codegen.additionalProperties().get("projectName"), "cpp-httplib-server");
Assert.assertEquals(codegen.modelPackage(), "cpp-httplib-server");
Assert.assertEquals(codegen.additionalProperties().get("cmakeProjectName"), "cpp_httplib_server");
}
@Test
public void testSettersForConfigValues() throws Exception {
codegen.additionalProperties().put("projectName", "TestProject");
codegen.additionalProperties().put("modelNamespace", "test::models");
codegen.additionalProperties().put("apiNamespace", "test::apis");
codegen.processOpts();
Assert.assertEquals(codegen.additionalProperties().get("projectName"), "TestProject");
Assert.assertEquals(codegen.additionalProperties().get("modelNamespace"), "test::models");
Assert.assertEquals(codegen.additionalProperties().get("apiNamespace"), "test::apis");
}
@Test
public void testToModelName() {
Assert.assertEquals(codegen.toModelName("User"), "User");
Assert.assertEquals(codegen.toModelName("user"), "User");
Assert.assertEquals(codegen.toModelName("user_model"), "UserModel");
Assert.assertEquals(codegen.toModelName("object"), "InlineModel");
Assert.assertEquals(codegen.toModelName("object_1"), "InlineModel1");
Assert.assertEquals(codegen.toModelName("inline_object_1"), "InlineModel1");
Assert.assertEquals(codegen.toModelName("_inline_model"), "Model");
}
@Test
public void testToApiName() {
Assert.assertEquals(codegen.toApiName("users"), "Users");
Assert.assertEquals(codegen.toApiName("testproject"), "Testproject");
}
@Test
public void testGetTypeDeclaration() {
Assert.assertEquals(codegen.getTypeDeclaration(new io.swagger.v3.oas.models.media.StringSchema()), "std::string");
Assert.assertEquals(codegen.getTypeDeclaration(new io.swagger.v3.oas.models.media.IntegerSchema()), "int");
Assert.assertEquals(codegen.getTypeDeclaration(new io.swagger.v3.oas.models.media.BooleanSchema()), "bool");
io.swagger.v3.oas.models.media.ArraySchema arraySchema = new io.swagger.v3.oas.models.media.ArraySchema();
arraySchema.setItems(new io.swagger.v3.oas.models.media.StringSchema());
Assert.assertEquals(codegen.getTypeDeclaration(arraySchema), "std::vector<std::string>");
}
@Test
public void testStringUtilityMethods() {
Assert.assertEquals(codegen.toPascalCase("user_name"), "UserName");
Assert.assertEquals(codegen.toPascalCase("userName"), "UserName");
Assert.assertEquals(codegen.toCamelCase("user_name"), "userName");
Assert.assertEquals(codegen.toPascalCase("UserName"), "UserName");
Assert.assertEquals(codegen.toCamelCase("UserName"), "userName");
Assert.assertEquals(underscore("UserName"), "user_name");
}
@Test
public void testInlineObjectNaming() {
// Test the enhanced inline object naming that we implemented
Assert.assertEquals(codegen.toModelName("object"), "InlineModel");
Assert.assertEquals(codegen.toModelName("object_1"), "InlineModel1");
Assert.assertEquals(codegen.toModelName("object_123"), "InlineModel123");
Assert.assertEquals(codegen.toModelName("inline_object"), "InlineModel");
Assert.assertEquals(codegen.toModelName("inline_object_5"), "InlineModel5");
}
@Test
public void testModelFilename() {
Assert.assertEquals(codegen.toModelFilename("User"), "User");
Assert.assertEquals(codegen.toModelFilename("UserModel"), "UserModel");
Assert.assertEquals(codegen.toModelFilename("object"), "Object");
Assert.assertEquals(codegen.toModelFilename("usermodel"), "Usermodel");
}
@Test
public void testApiFilename() {
Assert.assertEquals(codegen.toApiFilename("User"), "UserApi");
Assert.assertEquals(codegen.toApiFilename("Default"), "DefaultApi");
}
@Test
public void testTypeDeclarationWithAnyOf() {
io.swagger.v3.oas.models.media.ComposedSchema anyOfSchema = new io.swagger.v3.oas.models.media.ComposedSchema();
anyOfSchema.addAnyOfItem(new io.swagger.v3.oas.models.media.StringSchema());
anyOfSchema.addAnyOfItem(new io.swagger.v3.oas.models.media.IntegerSchema());
String result = codegen.getTypeDeclaration(anyOfSchema);
Assert.assertTrue(result.contains("std::variant"), "anyOf should generate std::variant");
}
@Test
public void testTypeDeclarationWithOneOf() {
io.swagger.v3.oas.models.media.ComposedSchema oneOfSchema = new io.swagger.v3.oas.models.media.ComposedSchema();
oneOfSchema.addOneOfItem(new io.swagger.v3.oas.models.media.StringSchema());
oneOfSchema.addOneOfItem(new io.swagger.v3.oas.models.media.NumberSchema());
String result = codegen.getTypeDeclaration(oneOfSchema);
Assert.assertTrue(result.contains("std::variant"), "oneOf should generate std::variant");
}
@Test
public void testModelNamespaceHandling() {
codegen.additionalProperties().put("modelNamespace", "myapp::models");
codegen.processOpts();
Assert.assertEquals(codegen.additionalProperties().get("modelNamespace"), "myapp::models");
}
@Test
public void testApiNamespaceHandling() {
codegen.additionalProperties().put("apiNamespace", "myapp::api");
codegen.processOpts();
Assert.assertEquals(codegen.additionalProperties().get("apiNamespace"), "myapp::api");
}
}

View File

@@ -0,0 +1,316 @@
{
"openapi": "3.0.0",
"info": {
"title": "Petstore API",
"version": "1.0.0"
},
"servers": [
{ "url": "http://petstore.swagger.io/v2" }
],
"paths": {
"/pet/{petId}": {
"get": {
"tags": ["pet"],
"summary": "Get pet by ID",
"operationId": "getPetById",
"parameters": [
{ "name": "petId", "in": "path", "required": true, "schema": { "type": "integer", "format": "int64" } },
{ "name": "customHeader", "in": "header", "required": false, "schema": { "type": "string" } },
{ "name": "cookieParam", "in": "cookie", "required": false, "schema": { "type": "string" } }
],
"responses": {
"200": { "description": "OK", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Pet" } } } },
"400": { "description": "Invalid ID", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ApiResponse" } } } },
"404": { "description": "Not found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ApiResponse" } } } }
}
},
"delete": {
"tags": ["pet"],
"summary": "Delete pet by ID",
"operationId": "deletePetById",
"parameters": [
{ "name": "petId", "in": "path", "required": true, "schema": { "type": "integer", "format": "int64" } },
{ "name": "api_key", "in": "query", "required": false, "schema": { "type": "string" } }
],
"responses": {
"200": { "description": "Pet deleted" },
"400": { "description": "Invalid ID" }
}
}
},
"/pet": {
"post": {
"tags": ["pet"],
"summary": "Add a new pet",
"operationId": "addPet",
"requestBody": {
"required": true,
"content": {
"application/json": { "schema": { "$ref": "#/components/schemas/Pet" } }
}
},
"responses": {
"201": { "description": "Pet created", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Pet" } } } },
"400": { "description": "Invalid input", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ApiResponse" } } } }
}
},
"put": {
"tags": ["pet"],
"summary": "Update an existing pet",
"operationId": "updatePet",
"requestBody": {
"required": true,
"content": {
"application/json": { "schema": { "$ref": "#/components/schemas/Pet" } }
}
},
"responses": {
"200": { "description": "Pet updated" },
"400": { "description": "Invalid input" }
}
}
},
"/pet/findByStatus": {
"get": {
"tags": ["pet"],
"summary": "Find pets by status (enum, array)",
"operationId": "findPetsByStatus",
"parameters": [
{ "name": "status", "in": "query", "required": true, "schema": { "type": "string", "enum": ["available", "pending", "sold"] } }
],
"responses": {
"200": { "description": "OK", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Pet" } } } } },
"400": { "description": "Invalid status" }
}
}
},
"/pet/findByTags": {
"get": {
"tags": ["pet"],
"summary": "Find pets by tags",
"operationId": "findPetsByTags",
"parameters": [
{ "name": "tags", "in": "query", "required": true, "style": "form", "explode": false, "schema": { "type": "array", "items": { "type": "string" } } }
],
"responses": {
"200": { "description": "OK", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Pet" } } } } }
}
}
},
"/pet/complex": {
"get": {
"tags": ["pet"],
"summary": "Test nested object, enum, array, header, cookie",
"operationId": "complexParamTest",
"parameters": [
{ "name": "deepObj", "in": "query", "required": false, "style": "deepObject", "explode": true, "schema": { "$ref": "#/components/schemas/DeepObj" } },
{ "name": "enumParam", "in": "query", "required": false, "schema": { "type": "string", "enum": ["A", "B", "C"] } },
{ "name": "pipeArr", "in": "query", "required": false, "style": "pipeDelimited", "explode": false, "schema": { "type": "array", "items": { "type": "string" } } },
{ "name": "spaceArr", "in": "query", "required": false, "style": "spaceDelimited", "explode": false, "schema": { "type": "array", "items": { "type": "integer" } } },
{ "name": "x-enum-header", "in": "header", "required": false, "schema": { "type": "string", "enum": ["X", "Y", "Z"] } },
{ "name": "cookieEnum", "in": "cookie", "required": false, "schema": { "type": "string", "enum": ["cookieA", "cookieB"] } }
],
"responses": {
"200": { "description": "OK", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ComplexParamsResponse" } } } }
}
}
},
"/store/order": {
"post": {
"tags": ["store"],
"summary": "Place an order",
"operationId": "placeOrder",
"requestBody": {
"required": true,
"content": {
"application/json": { "schema": { "$ref": "#/components/schemas/Order" } }
}
},
"responses": {
"200": { "description": "Order placed", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Order" } } } }
}
}
},
"/store/order/{orderId}": {
"get": {
"tags": ["store"],
"summary": "Get order by ID",
"operationId": "getOrderById",
"parameters": [
{ "name": "orderId", "in": "path", "required": true, "schema": { "type": "integer", "format": "int64" } }
],
"responses": {
"200": { "description": "OK", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Order" } } } }
}
},
"delete": {
"tags": ["store"],
"summary": "Delete order",
"operationId": "deleteOrder",
"parameters": [
{ "name": "orderId", "in": "path", "required": true, "schema": { "type": "integer", "format": "int64" } }
],
"responses": {
"200": { "description": "Order deleted" }
}
}
},
"/user": {
"post": {
"tags": ["user"],
"summary": "Create user",
"operationId": "createUser",
"requestBody": {
"required": true,
"content": {
"application/json": { "schema": { "$ref": "#/components/schemas/User" } }
}
},
"responses": {
"200": { "description": "User created", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/User" } } } }
}
}
},
"/user/{username}": {
"get": {
"tags": ["user"],
"summary": "Get user by name",
"operationId": "getUserByName",
"parameters": [
{ "name": "username", "in": "path", "required": true, "schema": { "type": "string" } }
],
"responses": {
"200": { "description": "OK", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/User" } } } }
}
},
"put": {
"tags": ["user"],
"summary": "Update user",
"operationId": "updateUser",
"parameters": [
{ "name": "username", "in": "path", "required": true, "schema": { "type": "string" } }
],
"requestBody": {
"required": true,
"content": {
"application/json": { "schema": { "$ref": "#/components/schemas/User" } }
}
},
"responses": {
"200": { "description": "User updated" }
}
},
"delete": {
"tags": ["user"],
"summary": "Delete user",
"operationId": "deleteUser",
"parameters": [
{ "name": "username", "in": "path", "required": true, "schema": { "type": "string" } }
],
"responses": {
"200": { "description": "User deleted" }
}
}
}
},
"components": {
"schemas": {
"Pet": {
"type": "object",
"required": ["name", "photoUrls"],
"properties": {
"id": { "type": "integer", "format": "int64" },
"name": { "type": "string" },
"photoUrls": { "type": "array", "items": { "type": "string" } },
"status": { "type": "string", "enum": ["available", "pending", "sold"], "description": "Pet status in store" },
"category": { "$ref": "#/components/schemas/Category" },
"tags": { "type": "array", "items": { "$ref": "#/components/schemas/Tag" } }
}
},
"Category": {
"type": "object",
"properties": {
"id": { "type": "integer", "format": "int64" },
"name": { "type": "string" }
}
},
"Tag": {
"type": "object",
"properties": {
"id": { "type": "integer", "format": "int64" },
"name": { "type": "string" }
}
},
"Order": {
"type": "object",
"properties": {
"id": { "type": "integer", "format": "int64" },
"petId": { "type": "integer", "format": "int64" },
"quantity": { "type": "integer", "format": "int32" },
"shipDate": { "type": "string", "format": "date-time" },
"status": { "type": "string", "enum": ["placed", "approved", "delivered"], "description": "Order status" },
"complete": { "type": "boolean" }
}
},
"User": {
"type": "object",
"properties": {
"id": { "type": "integer", "format": "int64" },
"username": { "type": "string" },
"firstName": { "type": "string" },
"lastName": { "type": "string" },
"email": { "type": "string", "format": "email" },
"password": { "type": "string" },
"phone": { "type": "string" },
"userStatus": { "type": "integer", "format": "int32", "enum": [0, 1, 2], "description": "User status (0=inactive, 1=active, 2=admin)" }
}
},
"ApiResponse": {
"type": "object",
"properties": {
"code": { "type": "integer", "format": "int32" },
"type": { "type": "string" },
"message": { "type": "string" }
}
},
"DeepObj": {
"type": "object",
"properties": {
"foo": { "type": "string" },
"bar": { "type": "integer" },
"baz": {
"type": "object",
"properties": {
"x": { "type": "string" },
"y": { "type": "integer" }
}
}
}
},
"ComplexParamsResponse": {
"type": "object",
"properties": {
"deepObj": { "$ref": "#/components/schemas/DeepObj" },
"enumParam": { "type": "string", "enum": ["A", "B", "C"] },
"pipeArr": { "type": "array", "items": { "type": "string" } },
"spaceArr": { "type": "array", "items": { "type": "integer" } },
"x-enum-header": { "type": "string", "enum": ["X", "Y", "Z"] },
"cookieEnum": { "type": "string", "enum": ["cookieA", "cookieB"] }
}
},
"PetOrCategory": {
"oneOf": [
{ "$ref": "#/components/schemas/Pet" },
{ "$ref": "#/components/schemas/Category" }
],
"description": "Polymorphic type: Pet or Category"
},
"NullableExample": {
"type": "object",
"properties": {
"maybeString": { "type": "string", "nullable": true, "description": "A nullable string property" }
}
}
}
}
}

View File

@@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@@ -0,0 +1,70 @@
CMakeLists.txt
LICENSE
README.md
api/AuthenticationManager.h
api/CompositionApi.cpp
api/CompositionApi.h
api/DatatypesApi.cpp
api/DatatypesApi.h
api/ParametersApi.cpp
api/ParametersApi.h
api/SecurityApi.cpp
api/SecurityApi.h
models/Address.cpp
models/Address.h
models/Animal.cpp
models/Animal.h
models/ArrayTypes.cpp
models/ArrayTypes.h
models/BankAccount.cpp
models/BankAccount.h
models/Company.cpp
models/Company.h
models/CreatedResponse.cpp
models/CreatedResponse.h
models/CreditCard.cpp
models/CreditCard.h
models/Department.cpp
models/Department.h
models/Dog.cpp
models/Dog.h
models/Employee.cpp
models/Employee.h
models/EnumTypes.cpp
models/EnumTypes.h
models/ErrorResponse.cpp
models/ErrorResponse.h
models/NotFoundResponse.cpp
models/NotFoundResponse.h
models/NullableOptionalTypes.cpp
models/NullableOptionalTypes.h
models/PaymentMethod.cpp
models/PaymentMethod.h
models/PrimitiveTypes.cpp
models/PrimitiveTypes.h
models/SimpleObject.cpp
models/SimpleObject.h
models/StringOrNumber.cpp
models/StringOrNumber.h
models/SuccessResponse.cpp
models/SuccessResponse.h
models/TestAllParameterTypes200Response.cpp
models/TestAllParameterTypes200Response.h
models/TestApiKeySecurity200Response.cpp
models/TestApiKeySecurity200Response.h
models/TestBasicSecurity200Response.cpp
models/TestBasicSecurity200Response.h
models/TestBearerSecurity200Response.cpp
models/TestBearerSecurity200Response.h
models/TestCookieParameters200Response.cpp
models/TestCookieParameters200Response.h
models/TestHeaderParameters200Response.cpp
models/TestHeaderParameters200Response.h
models/TestHeaderParameters401Response.cpp
models/TestHeaderParameters401Response.h
models/TestOAuth2Security200Response.cpp
models/TestOAuth2Security200Response.h
models/TestQueryParameters200Response.cpp
models/TestQueryParameters200Response.h
models/TestQueryParametersDeepObjectParameter.cpp
models/TestQueryParametersDeepObjectParameter.h

View File

@@ -0,0 +1 @@
7.16.0-SNAPSHOT

View File

@@ -0,0 +1,49 @@
cmake_minimum_required(VERSION 3.14)
project(cpp_httplib_server_feature_test LANGUAGES CXX)
include(FetchContent)
# Fetch nlohmann_json
FetchContent_Declare(
nlohmann_json
GIT_REPOSITORY https://github.com/nlohmann/json.git
GIT_TAG v3.11.3
)
FetchContent_MakeAvailable(nlohmann_json)
# Fetch cpp-httplib
FetchContent_Declare(
httplib
GIT_REPOSITORY https://github.com/yhirose/cpp-httplib.git
GIT_TAG v0.15.3
)
FetchContent_MakeAvailable(httplib)
# System libraries - install with: sudo apt-get install libssl-dev zlib1g-dev
find_package(OpenSSL REQUIRED)
find_package(ZLIB REQUIRED)
set(TARGET_NAME cpp_httplib_server_feature_test_openapi_lib)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
file(GLOB API_SRCS
${CMAKE_CURRENT_SOURCE_DIR}/api/*.h
${CMAKE_CURRENT_SOURCE_DIR}/api/*.cpp
)
file(GLOB MODEL_SRCS
${CMAKE_CURRENT_SOURCE_DIR}/models/*.h
${CMAKE_CURRENT_SOURCE_DIR}/models/*.cpp
)
add_library(${TARGET_NAME} ${API_SRCS} ${MODEL_SRCS})
target_include_directories (${TARGET_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
# Make sure these libraries/headers are available in the build environment before linking
# Required libraries/headers are httplib,ssl,nlohmann::json,zlib
target_link_libraries(${TARGET_NAME}
PRIVATE
httplib::httplib
OpenSSL::SSL
OpenSSL::Crypto
nlohmann_json::nlohmann_json
ZLIB::ZLIB)

View File

@@ -0,0 +1,5 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,79 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
#include <string>
#include <vector>
#include <memory>
namespace api {
/**
* @brief Authentication Manager Interface
*
* This interface defines the contract for authentication validation.
* Users must implement this interface to provide their own authentication logic.
*
* Example implementation:
* @code
* class MyAuthManager : public AuthenticationManager {
* public:
* bool validateApiKey(const std::string& key) override {
* return database.checkApiKey(key);
* }
*
* bool validateBearerToken(const std::string& token) override {
* return jwt::verify(token, secret);
* }
*
* bool validateBasicAuth(const std::string& username, const std::string& password) override {
* return bcrypt::verify(password, database.getPasswordHash(username));
* }
*
* bool validateOAuth2(const std::string& token, const std::vector<std::string>& scopes) override {
* auto introspection = oauthProvider.introspect(token);
* return introspection.active && hasRequiredScopes(introspection, scopes);
* }
* };
* @endcode
*/
class AuthenticationManager {
public:
virtual ~AuthenticationManager() = default;
/**
* @brief Validate an API key
* @param key The API key to validate
* @return true if the API key is valid, false otherwise
*/
virtual bool validateApiKey(const std::string& key) = 0;
/**
* @brief Validate a Bearer token (e.g., JWT)
* @param token The bearer token to validate
* @return true if the token is valid, false otherwise
*/
virtual bool validateBearerToken(const std::string& token) = 0;
/**
* @brief Validate Basic authentication credentials
* @param username The username
* @param password The password
* @return true if the credentials are valid, false otherwise
*/
virtual bool validateBasicAuth(const std::string& username, const std::string& password) = 0;
/**
* @brief Validate an OAuth2 token with required scopes
* @param token The OAuth2 access token
* @param scopes The required scopes for this operation
* @return true if the token is valid and has required scopes, false otherwise
*/
virtual bool validateOAuth2(const std::string& token, const std::vector<std::string>& scopes) = 0;
};
} // namespace api

View File

@@ -0,0 +1,323 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
// System headers
#include <algorithm>
#include <cctype>
#include <locale>
// Project headers
#include "CompositionApi.h"
constexpr int HTTP_RESPONSE_CODE_DOG = 200;
constexpr int HTTP_RESPONSE_CODE_STRING_OR_NUMBER = 200;
constexpr int HTTP_RESPONSE_CODE_PAYMENT_METHOD = 200;
constexpr int HTTP_RESPONSE_CODE_BAD_REQUEST = 400;
constexpr int HTTP_RESPONSE_CODE_INTERNAL_SERVER_ERROR = 500;
namespace api {
using namespace models;
bool Composition::parseCompositionallofPostParams(const httplib::Request& req, Composition::CompositionallofPostRequest& params, std::vector<std::string>& paramErrors)
{
std::vector<std::string> errors;
if (!req.body.empty())
{
try
{
nlohmann::json json = nlohmann::json::parse(req.body);
from_json(json, params.m_request);
}
catch (const std::exception& e)
{
errors.push_back("Invalid request body: " + std::string(e.what()));
}
}
else
{
errors.push_back("Missing required request body");
}
// Return errors via out-parameter, return false if any errors
if (!errors.empty())
{
paramErrors = std::move(errors);
return false;
}
return true;
}
void Composition::handleCompositionallofPostResponse(const CompositionallofPostResponse& result, httplib::Response& res)
{
// Single response type
res.status = HTTP_RESPONSE_CODE_DOG;
nlohmann::json responseJson;
to_json(responseJson, result);
res.set_content(responseJson.dump(), "application/json");
}
bool Composition::parseCompositionanyofPostParams(const httplib::Request& req, Composition::CompositionanyofPostRequest& params, std::vector<std::string>& paramErrors)
{
std::vector<std::string> errors;
if (!req.body.empty())
{
try
{
nlohmann::json json = nlohmann::json::parse(req.body);
from_json(json, params.m_request);
}
catch (const std::exception& e)
{
errors.push_back("Invalid request body: " + std::string(e.what()));
}
}
else
{
errors.push_back("Missing required request body");
}
// Return errors via out-parameter, return false if any errors
if (!errors.empty())
{
paramErrors = std::move(errors);
return false;
}
return true;
}
void Composition::handleCompositionanyofPostResponse(const CompositionanyofPostResponse& result, httplib::Response& res)
{
// Single response type
res.status = HTTP_RESPONSE_CODE_STRING_OR_NUMBER;
nlohmann::json responseJson;
to_json(responseJson, result);
res.set_content(responseJson.dump(), "application/json");
}
bool Composition::parseCompositiononeofPostParams(const httplib::Request& req, Composition::CompositiononeofPostRequest& params, std::vector<std::string>& paramErrors)
{
std::vector<std::string> errors;
if (!req.body.empty())
{
try
{
nlohmann::json json = nlohmann::json::parse(req.body);
from_json(json, params.m_request);
}
catch (const std::exception& e)
{
errors.push_back("Invalid request body: " + std::string(e.what()));
}
}
else
{
errors.push_back("Missing required request body");
}
// Return errors via out-parameter, return false if any errors
if (!errors.empty())
{
paramErrors = std::move(errors);
return false;
}
return true;
}
void Composition::handleCompositiononeofPostResponse(const CompositiononeofPostResponse& result, httplib::Response& res)
{
// Single response type
res.status = HTTP_RESPONSE_CODE_PAYMENT_METHOD;
nlohmann::json responseJson;
to_json(responseJson, result);
res.set_content(responseJson.dump(), "application/json");
}
void Composition::handleCompositionallofPostRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
try
{
CompositionallofPostRequest params;
std::vector<std::string> paramErrors;
if (!parseCompositionallofPostParams(req, params, paramErrors))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid parameters";
errorJson["errors"] = paramErrors;
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
return;
}
auto result = handlePostForCompositionallof(params);
handleCompositionallofPostResponse(result, res);
}
catch (const nlohmann::json::parse_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::invalid_iterator& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::type_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::out_of_range& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::other_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
}
void Composition::handleCompositionanyofPostRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
try
{
CompositionanyofPostRequest params;
std::vector<std::string> paramErrors;
if (!parseCompositionanyofPostParams(req, params, paramErrors))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid parameters";
errorJson["errors"] = paramErrors;
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
return;
}
auto result = handlePostForCompositionanyof(params);
handleCompositionanyofPostResponse(result, res);
}
catch (const nlohmann::json::parse_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::invalid_iterator& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::type_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::out_of_range& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::other_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
}
void Composition::handleCompositiononeofPostRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
try
{
CompositiononeofPostRequest params;
std::vector<std::string> paramErrors;
if (!parseCompositiononeofPostParams(req, params, paramErrors))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid parameters";
errorJson["errors"] = paramErrors;
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
return;
}
auto result = handlePostForCompositiononeof(params);
handleCompositiononeofPostResponse(result, res);
}
catch (const nlohmann::json::parse_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::invalid_iterator& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::type_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::out_of_range& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::other_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
}
void Composition::registerRoutes(httplib::Server& svr)
{
svr.Post("/composition/allof", [this]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleCompositionallofPostRequest(req, res);
});
svr.Post("/composition/anyof", [this]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleCompositionanyofPostRequest(req, res);
});
svr.Post("/composition/oneof", [this]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleCompositiononeofPostRequest(req, res);
});
}
} // namespace api

View File

@@ -0,0 +1,113 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <httplib.h>
#include <memory>
#include <variant>
#include <optional>
// Project headers
#include "models/Dog.h"
#include "models/PaymentMethod.h"
#include "models/StringOrNumber.h"
namespace api {
class AuthenticationManager;
class Composition {
public:
Composition() = default;
virtual ~Composition() = default;
/**
* @brief Register all routes for this API
* @param svr The httplib::Server instance to register routes on
*/
void registerRoutes(httplib::Server& svr);
// =========================
// ===== Request types =====
// =========================
/**
* @brief Request type for handlePostForCompositionallof.
*/
struct CompositionallofPostRequest
{
models::Dog m_request; //Request Body (required)
};
/**
* @brief Request type for handlePostForCompositionanyof.
*/
struct CompositionanyofPostRequest
{
models::StringOrNumber m_request; //Request Body (required)
};
/**
* @brief Request type for handlePostForCompositiononeof.
*/
struct CompositiononeofPostRequest
{
models::PaymentMethod m_request; //Request Body (required)
};
// ==========================
// ===== Response types =====
// ==========================
/**
* @brief Response type for handlePostForCompositionallof.
*/
using CompositionallofPostResponse = models::Dog;
/**
* @brief Response type for handlePostForCompositionanyof.
*/
using CompositionanyofPostResponse = models::StringOrNumber;
/**
* @brief Response type for handlePostForCompositiononeof.
*/
using CompositiononeofPostResponse = models::PaymentMethod;
// ============================================================
// ===== Pure virtual functions to be handled by the user =====
// ============================================================
/**
* CompositionallofPostRequest - struct containing all the query parameters and headers and schemas as available.
* @return CompositionallofPostResponse The response type returned by the handler.
*/
virtual CompositionallofPostResponse handlePostForCompositionallof(const CompositionallofPostRequest& params)=0;
/**
* CompositionanyofPostRequest - struct containing all the query parameters and headers and schemas as available.
* @return CompositionanyofPostResponse The response type returned by the handler.
*/
virtual CompositionanyofPostResponse handlePostForCompositionanyof(const CompositionanyofPostRequest& params)=0;
/**
* CompositiononeofPostRequest - struct containing all the query parameters and headers and schemas as available.
* @return CompositiononeofPostResponse The response type returned by the handler.
*/
virtual CompositiononeofPostResponse handlePostForCompositiononeof(const CompositiononeofPostRequest& params)=0;
private:
// ========================================
// ===== Helper function declarations =====
// ========================================
static bool parseCompositionallofPostParams(const httplib::Request& req, CompositionallofPostRequest& params, std::vector<std::string>& paramErrors);
void handleCompositionallofPostRequest(const httplib::Request& req, httplib::Response& res);
static void handleCompositionallofPostResponse(const CompositionallofPostResponse& result, httplib::Response& res);
static bool parseCompositionanyofPostParams(const httplib::Request& req, CompositionanyofPostRequest& params, std::vector<std::string>& paramErrors);
void handleCompositionanyofPostRequest(const httplib::Request& req, httplib::Response& res);
static void handleCompositionanyofPostResponse(const CompositionanyofPostResponse& result, httplib::Response& res);
static bool parseCompositiononeofPostParams(const httplib::Request& req, CompositiononeofPostRequest& params, std::vector<std::string>& paramErrors);
void handleCompositiononeofPostRequest(const httplib::Request& req, httplib::Response& res);
static void handleCompositiononeofPostResponse(const CompositiononeofPostResponse& result, httplib::Response& res);
};
} // namespace api

View File

@@ -0,0 +1,690 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
// System headers
#include <algorithm>
#include <cctype>
#include <locale>
// Project headers
#include "DatatypesApi.h"
constexpr int HTTP_RESPONSE_CODE_ARRAY_TYPES = 200;
constexpr int HTTP_RESPONSE_CODE_ENUM_TYPES = 200;
constexpr int HTTP_RESPONSE_CODE_SUCCESS_RESPONSE = 200;
constexpr int HTTP_RESPONSE_CODE_CREATED_RESPONSE = 201;
constexpr int HTTP_RESPONSE_CODE_NOT_FOUND_RESPONSE = 404;
constexpr int HTTP_RESPONSE_CODE_ERROR_RESPONSE = 500;
constexpr int HTTP_RESPONSE_CODE_COMPANY = 200;
constexpr int HTTP_RESPONSE_CODE_NULLABLE_OPTIONAL_TYPES = 200;
constexpr int HTTP_RESPONSE_CODE_PRIMITIVE_TYPES = 200;
constexpr int HTTP_RESPONSE_CODE_NO_CONTENT = 204;
constexpr int HTTP_RESPONSE_CODE_BAD_REQUEST = 400;
namespace api {
using namespace models;
bool Datatypes::parseDatatypesarraysPostParams(const httplib::Request& req, Datatypes::DatatypesarraysPostRequest& params, std::vector<std::string>& paramErrors)
{
std::vector<std::string> errors;
if (!req.body.empty())
{
try
{
nlohmann::json json = nlohmann::json::parse(req.body);
from_json(json, params.m_request);
}
catch (const std::exception& e)
{
errors.push_back("Invalid request body: " + std::string(e.what()));
}
}
else
{
errors.push_back("Missing required request body");
}
// Return errors via out-parameter, return false if any errors
if (!errors.empty())
{
paramErrors = std::move(errors);
return false;
}
return true;
}
void Datatypes::handleDatatypesarraysPostResponse(const DatatypesarraysPostResponse& result, httplib::Response& res)
{
// Single response type
res.status = HTTP_RESPONSE_CODE_ARRAY_TYPES;
nlohmann::json responseJson;
to_json(responseJson, result);
res.set_content(responseJson.dump(), "application/json");
}
bool Datatypes::parseDatatypesenumsPostParams(const httplib::Request& req, Datatypes::DatatypesenumsPostRequest& params, std::vector<std::string>& paramErrors)
{
std::vector<std::string> errors;
if (!req.body.empty())
{
try
{
nlohmann::json json = nlohmann::json::parse(req.body);
from_json(json, params.m_request);
}
catch (const std::exception& e)
{
errors.push_back("Invalid request body: " + std::string(e.what()));
}
}
else
{
errors.push_back("Missing required request body");
}
// Return errors via out-parameter, return false if any errors
if (!errors.empty())
{
paramErrors = std::move(errors);
return false;
}
return true;
}
void Datatypes::handleDatatypesenumsPostResponse(const DatatypesenumsPostResponse& result, httplib::Response& res)
{
// Single response type
res.status = HTTP_RESPONSE_CODE_ENUM_TYPES;
nlohmann::json responseJson;
to_json(responseJson, result);
res.set_content(responseJson.dump(), "application/json");
}
bool Datatypes::parseResponsesmultipleGetParams(const httplib::Request& req, Datatypes::ResponsesmultipleGetRequest& params, std::vector<std::string>& paramErrors)
{
std::vector<std::string> errors;
// Query Parameters - scenario
if (req.has_param("scenario"))
{
try
{
params.m_scenario = (req.get_param_value("scenario"));
}
catch (const std::exception& e)
{
errors.push_back("Invalid query parameter 'scenario': " + std::string(e.what()));
}
}
// Return errors via out-parameter, return false if any errors
if (!errors.empty())
{
paramErrors = std::move(errors);
return false;
}
return true;
}
void Datatypes::handleResponsesmultipleGetResponse(const ResponsesmultipleGetResponse& result, httplib::Response& res)
{
std::visit([&](const auto& value)
{
using T = std::decay_t<decltype(value)>;
// Success types
if constexpr (std::is_same_v<T, models::SuccessResponse>)
{
res.status = HTTP_RESPONSE_CODE_SUCCESS_RESPONSE;
nlohmann::json responseJson;
to_json(responseJson, value);
res.set_content(responseJson.dump(), "application/json");
}else if constexpr (std::is_same_v<T, models::CreatedResponse>)
{
res.status = HTTP_RESPONSE_CODE_CREATED_RESPONSE;
nlohmann::json responseJson;
to_json(responseJson, value);
res.set_content(responseJson.dump(), "application/json");
}
// Error types
else if constexpr (std::is_same_v<T, models::NotFoundResponse>)
{
res.status = HTTP_RESPONSE_CODE_NOT_FOUND_RESPONSE;
nlohmann::json errorJson = value;
res.set_content(errorJson.dump(), "application/json");
}
else if constexpr (std::is_same_v<T, models::ErrorResponse>)
{
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
nlohmann::json errorJson = value;
res.set_content(errorJson.dump(), "application/json");
}
}, result);
}
bool Datatypes::parseNestedobjectsPostParams(const httplib::Request& req, Datatypes::NestedobjectsPostRequest& params, std::vector<std::string>& paramErrors)
{
std::vector<std::string> errors;
if (!req.body.empty())
{
try
{
nlohmann::json json = nlohmann::json::parse(req.body);
from_json(json, params.m_request);
}
catch (const std::exception& e)
{
errors.push_back("Invalid request body: " + std::string(e.what()));
}
}
else
{
errors.push_back("Missing required request body");
}
// Return errors via out-parameter, return false if any errors
if (!errors.empty())
{
paramErrors = std::move(errors);
return false;
}
return true;
}
void Datatypes::handleNestedobjectsPostResponse(const NestedobjectsPostResponse& result, httplib::Response& res)
{
// Single response type
res.status = HTTP_RESPONSE_CODE_COMPANY;
nlohmann::json responseJson;
to_json(responseJson, result);
res.set_content(responseJson.dump(), "application/json");
}
bool Datatypes::parseResponsesnocontentDeleteParams(const httplib::Request& req, Datatypes::ResponsesnocontentDeleteRequest& params, std::vector<std::string>& paramErrors)
{
std::vector<std::string> errors;
// Query Parameters - id
if (req.has_param("id"))
{
try
{
params.m_id = std::stoi(req.get_param_value("id"));
}
catch (const std::exception& e)
{
errors.push_back("Invalid query parameter 'id': " + std::string(e.what()));
}
}
// Return errors via out-parameter, return false if any errors
if (!errors.empty())
{
paramErrors = std::move(errors);
return false;
}
return true;
}
bool Datatypes::parseNullableoptionalPostParams(const httplib::Request& req, Datatypes::NullableoptionalPostRequest& params, std::vector<std::string>& paramErrors)
{
std::vector<std::string> errors;
if (!req.body.empty())
{
try
{
nlohmann::json json = nlohmann::json::parse(req.body);
from_json(json, params.m_request);
}
catch (const std::exception& e)
{
errors.push_back("Invalid request body: " + std::string(e.what()));
}
}
else
{
errors.push_back("Missing required request body");
}
// Return errors via out-parameter, return false if any errors
if (!errors.empty())
{
paramErrors = std::move(errors);
return false;
}
return true;
}
void Datatypes::handleNullableoptionalPostResponse(const NullableoptionalPostResponse& result, httplib::Response& res)
{
// Single response type
res.status = HTTP_RESPONSE_CODE_NULLABLE_OPTIONAL_TYPES;
nlohmann::json responseJson;
to_json(responseJson, result);
res.set_content(responseJson.dump(), "application/json");
}
bool Datatypes::parseDatatypesprimitivesPostParams(const httplib::Request& req, Datatypes::DatatypesprimitivesPostRequest& params, std::vector<std::string>& paramErrors)
{
std::vector<std::string> errors;
if (!req.body.empty())
{
try
{
nlohmann::json json = nlohmann::json::parse(req.body);
from_json(json, params.m_request);
}
catch (const std::exception& e)
{
errors.push_back("Invalid request body: " + std::string(e.what()));
}
}
else
{
errors.push_back("Missing required request body");
}
// Return errors via out-parameter, return false if any errors
if (!errors.empty())
{
paramErrors = std::move(errors);
return false;
}
return true;
}
void Datatypes::handleDatatypesprimitivesPostResponse(const DatatypesprimitivesPostResponse& result, httplib::Response& res)
{
std::visit([&](const auto& value)
{
using T = std::decay_t<decltype(value)>;
// Success types
if constexpr (std::is_same_v<T, models::PrimitiveTypes>)
{
res.status = HTTP_RESPONSE_CODE_PRIMITIVE_TYPES;
nlohmann::json responseJson;
to_json(responseJson, value);
res.set_content(responseJson.dump(), "application/json");
}
// Error types
else if constexpr (std::is_same_v<T, models::ErrorResponse>)
{
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
nlohmann::json errorJson = value;
res.set_content(errorJson.dump(), "application/json");
}
}, result);
}
void Datatypes::handleDatatypesarraysPostRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
try
{
DatatypesarraysPostRequest params;
std::vector<std::string> paramErrors;
if (!parseDatatypesarraysPostParams(req, params, paramErrors))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid parameters";
errorJson["errors"] = paramErrors;
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
return;
}
auto result = handlePostForDatatypesarrays(params);
handleDatatypesarraysPostResponse(result, res);
}
catch (const nlohmann::json::parse_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::invalid_iterator& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::type_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::out_of_range& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::other_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
}
void Datatypes::handleDatatypesenumsPostRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
try
{
DatatypesenumsPostRequest params;
std::vector<std::string> paramErrors;
if (!parseDatatypesenumsPostParams(req, params, paramErrors))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid parameters";
errorJson["errors"] = paramErrors;
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
return;
}
auto result = handlePostForDatatypesenums(params);
handleDatatypesenumsPostResponse(result, res);
}
catch (const nlohmann::json::parse_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::invalid_iterator& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::type_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::out_of_range& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::other_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
}
void Datatypes::handleResponsesmultipleGetRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
try
{
ResponsesmultipleGetRequest params;
std::vector<std::string> paramErrors;
if (!parseResponsesmultipleGetParams(req, params, paramErrors))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid parameters";
errorJson["errors"] = paramErrors;
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
return;
}
auto result = handleGetForResponsesmultiple(params);
handleResponsesmultipleGetResponse(result, res);
}
catch (const std::exception& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Internal error: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
res.set_content(errorJson.dump(), "application/json");
}
}
void Datatypes::handleNestedobjectsPostRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
try
{
NestedobjectsPostRequest params;
std::vector<std::string> paramErrors;
if (!parseNestedobjectsPostParams(req, params, paramErrors))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid parameters";
errorJson["errors"] = paramErrors;
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
return;
}
auto result = handlePostForNestedobjects(params);
handleNestedobjectsPostResponse(result, res);
}
catch (const nlohmann::json::parse_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::invalid_iterator& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::type_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::out_of_range& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::other_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
}
void Datatypes::handleResponsesnocontentDeleteRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
try
{
ResponsesnocontentDeleteRequest params;
std::vector<std::string> paramErrors;
if (!parseResponsesnocontentDeleteParams(req, params, paramErrors))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid parameters";
errorJson["errors"] = paramErrors;
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
return;
}
handleDeleteForResponsesnocontent(params);
res.status = HTTP_RESPONSE_CODE_NO_CONTENT;
}
catch (const std::exception& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Internal error: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
res.set_content(errorJson.dump(), "application/json");
}
}
void Datatypes::handleNullableoptionalPostRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
try
{
NullableoptionalPostRequest params;
std::vector<std::string> paramErrors;
if (!parseNullableoptionalPostParams(req, params, paramErrors))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid parameters";
errorJson["errors"] = paramErrors;
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
return;
}
auto result = handlePostForNullableoptional(params);
handleNullableoptionalPostResponse(result, res);
}
catch (const nlohmann::json::parse_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::invalid_iterator& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::type_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::out_of_range& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::other_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
}
void Datatypes::handleDatatypesprimitivesPostRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
try
{
DatatypesprimitivesPostRequest params;
std::vector<std::string> paramErrors;
if (!parseDatatypesprimitivesPostParams(req, params, paramErrors))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid parameters";
errorJson["errors"] = paramErrors;
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
return;
}
auto result = handlePostForDatatypesprimitives(params);
handleDatatypesprimitivesPostResponse(result, res);
}
catch (const nlohmann::json::parse_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::invalid_iterator& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::type_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::out_of_range& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::other_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_BAD_REQUEST;
res.set_content(errorJson.dump(), "application/json");
}
}
void Datatypes::registerRoutes(httplib::Server& svr)
{
svr.Post("/datatypes/arrays", [this]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleDatatypesarraysPostRequest(req, res);
});
svr.Post("/datatypes/enums", [this]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleDatatypesenumsPostRequest(req, res);
});
svr.Get("/responses/multiple", [this]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleResponsesmultipleGetRequest(req, res);
});
svr.Post("/nested/objects", [this]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleNestedobjectsPostRequest(req, res);
});
svr.Delete("/responses/nocontent", [this]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleResponsesnocontentDeleteRequest(req, res);
});
svr.Post("/nullable/optional", [this]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleNullableoptionalPostRequest(req, res);
});
svr.Post("/datatypes/primitives", [this]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleDatatypesprimitivesPostRequest(req, res);
});
}
} // namespace api

View File

@@ -0,0 +1,208 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <httplib.h>
#include <memory>
#include <variant>
#include <optional>
// Project headers
#include "models/ArrayTypes.h"
#include "models/Company.h"
#include "models/CreatedResponse.h"
#include "models/EnumTypes.h"
#include "models/ErrorResponse.h"
#include "models/NotFoundResponse.h"
#include "models/NullableOptionalTypes.h"
#include "models/PrimitiveTypes.h"
#include "models/SuccessResponse.h"
namespace api {
class AuthenticationManager;
class Datatypes {
public:
Datatypes() = default;
virtual ~Datatypes() = default;
/**
* @brief Register all routes for this API
* @param svr The httplib::Server instance to register routes on
*/
void registerRoutes(httplib::Server& svr);
// =========================
// ===== Request types =====
// =========================
/**
* @brief Request type for handlePostForDatatypesarrays.
*/
struct DatatypesarraysPostRequest
{
models::ArrayTypes m_request; //Request Body (required)
};
/**
* @brief Request type for handlePostForDatatypesenums.
*/
struct DatatypesenumsPostRequest
{
models::EnumTypes m_request; //Request Body (required)
};
/**
* @brief Request type for handleGetForResponsesmultiple.
*/
struct ResponsesmultipleGetRequest
{
std::string m_scenario; //Query Params (required)
};
/**
* @brief Request type for handlePostForNestedobjects.
*/
struct NestedobjectsPostRequest
{
models::Company m_request; //Request Body (required)
};
/**
* @brief Request type for handleDeleteForResponsesnocontent.
*/
struct ResponsesnocontentDeleteRequest
{
int m_id; //Query Params (required)
};
/**
* @brief Request type for handlePostForNullableoptional.
*/
struct NullableoptionalPostRequest
{
models::NullableOptionalTypes m_request; //Request Body (required)
};
/**
* @brief Request type for handlePostForDatatypesprimitives.
*/
struct DatatypesprimitivesPostRequest
{
models::PrimitiveTypes m_request; //Request Body (required)
};
// ==========================
// ===== Response types =====
// ==========================
/**
* @brief Response type for handlePostForDatatypesarrays.
*/
using DatatypesarraysPostResponse = models::ArrayTypes;
/**
* @brief Response type for handlePostForDatatypesenums.
*/
using DatatypesenumsPostResponse = models::EnumTypes;
/**
* @brief Response type for handleGetForResponsesmultiple.
*/
using ResponsesmultipleGetResponse = std::variant<
models::SuccessResponse ,
models::CreatedResponse ,
models::NotFoundResponse ,
models::ErrorResponse >;
/**
* @brief Response type for handlePostForNestedobjects.
*/
using NestedobjectsPostResponse = models::Company;
/**
* @brief Response type for handlePostForNullableoptional.
*/
using NullableoptionalPostResponse = models::NullableOptionalTypes;
/**
* @brief Response type for handlePostForDatatypesprimitives.
*/
using DatatypesprimitivesPostResponse = std::variant<
models::PrimitiveTypes ,
models::ErrorResponse >;
// ============================================================
// ===== Pure virtual functions to be handled by the user =====
// ============================================================
/**
* DatatypesarraysPostRequest - struct containing all the query parameters and headers and schemas as available.
* @return DatatypesarraysPostResponse The response type returned by the handler.
*/
virtual DatatypesarraysPostResponse handlePostForDatatypesarrays(const DatatypesarraysPostRequest& params)=0;
/**
* DatatypesenumsPostRequest - struct containing all the query parameters and headers and schemas as available.
* @return DatatypesenumsPostResponse The response type returned by the handler.
*/
virtual DatatypesenumsPostResponse handlePostForDatatypesenums(const DatatypesenumsPostRequest& params)=0;
/**
* ResponsesmultipleGetRequest - struct containing all the query parameters and headers and schemas as available.
* @return ResponsesmultipleGetResponse The response type returned by the handler.
*/
virtual ResponsesmultipleGetResponse handleGetForResponsesmultiple(const ResponsesmultipleGetRequest& params)=0;
/**
* NestedobjectsPostRequest - struct containing all the query parameters and headers and schemas as available.
* @return NestedobjectsPostResponse The response type returned by the handler.
*/
virtual NestedobjectsPostResponse handlePostForNestedobjects(const NestedobjectsPostRequest& params)=0;
/**
* ResponsesnocontentDeleteRequest - struct containing all the query parameters and headers and schemas as available.
*/
virtual void handleDeleteForResponsesnocontent(const ResponsesnocontentDeleteRequest& params)=0;
/**
* NullableoptionalPostRequest - struct containing all the query parameters and headers and schemas as available.
* @return NullableoptionalPostResponse The response type returned by the handler.
*/
virtual NullableoptionalPostResponse handlePostForNullableoptional(const NullableoptionalPostRequest& params)=0;
/**
* DatatypesprimitivesPostRequest - struct containing all the query parameters and headers and schemas as available.
* @return DatatypesprimitivesPostResponse The response type returned by the handler.
*/
virtual DatatypesprimitivesPostResponse handlePostForDatatypesprimitives(const DatatypesprimitivesPostRequest& params)=0;
private:
// ========================================
// ===== Helper function declarations =====
// ========================================
static bool parseDatatypesarraysPostParams(const httplib::Request& req, DatatypesarraysPostRequest& params, std::vector<std::string>& paramErrors);
void handleDatatypesarraysPostRequest(const httplib::Request& req, httplib::Response& res);
static void handleDatatypesarraysPostResponse(const DatatypesarraysPostResponse& result, httplib::Response& res);
static bool parseDatatypesenumsPostParams(const httplib::Request& req, DatatypesenumsPostRequest& params, std::vector<std::string>& paramErrors);
void handleDatatypesenumsPostRequest(const httplib::Request& req, httplib::Response& res);
static void handleDatatypesenumsPostResponse(const DatatypesenumsPostResponse& result, httplib::Response& res);
static bool parseResponsesmultipleGetParams(const httplib::Request& req, ResponsesmultipleGetRequest& params, std::vector<std::string>& paramErrors);
void handleResponsesmultipleGetRequest(const httplib::Request& req, httplib::Response& res);
static void handleResponsesmultipleGetResponse(const ResponsesmultipleGetResponse& result, httplib::Response& res);
static bool parseNestedobjectsPostParams(const httplib::Request& req, NestedobjectsPostRequest& params, std::vector<std::string>& paramErrors);
void handleNestedobjectsPostRequest(const httplib::Request& req, httplib::Response& res);
static void handleNestedobjectsPostResponse(const NestedobjectsPostResponse& result, httplib::Response& res);
static bool parseResponsesnocontentDeleteParams(const httplib::Request& req, ResponsesnocontentDeleteRequest& params, std::vector<std::string>& paramErrors);
void handleResponsesnocontentDeleteRequest(const httplib::Request& req, httplib::Response& res);
static bool parseNullableoptionalPostParams(const httplib::Request& req, NullableoptionalPostRequest& params, std::vector<std::string>& paramErrors);
void handleNullableoptionalPostRequest(const httplib::Request& req, httplib::Response& res);
static void handleNullableoptionalPostResponse(const NullableoptionalPostResponse& result, httplib::Response& res);
static bool parseDatatypesprimitivesPostParams(const httplib::Request& req, DatatypesprimitivesPostRequest& params, std::vector<std::string>& paramErrors);
void handleDatatypesprimitivesPostRequest(const httplib::Request& req, httplib::Response& res);
static void handleDatatypesprimitivesPostResponse(const DatatypesprimitivesPostResponse& result, httplib::Response& res);
};
} // namespace api

View File

@@ -0,0 +1,775 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
// System headers
#include <algorithm>
#include <cctype>
#include <locale>
// Project headers
#include "ParametersApi.h"
constexpr int HTTP_RESPONSE_CODE_TEST_ALL_PARAMETER_TYPES200_RESPONSE = 200;
constexpr int HTTP_RESPONSE_CODE_ERROR_RESPONSE = 400;
constexpr int HTTP_RESPONSE_CODE_TEST_COOKIE_PARAMETERS200_RESPONSE = 200;
constexpr int HTTP_RESPONSE_CODE_TEST_HEADER_PARAMETERS200_RESPONSE = 200;
constexpr int HTTP_RESPONSE_CODE_TEST_HEADER_PARAMETERS401_RESPONSE = 401;
constexpr int HTTP_RESPONSE_CODE_TEST_QUERY_PARAMETERS200_RESPONSE = 200;
constexpr int HTTP_RESPONSE_CODE_INTERNAL_SERVER_ERROR = 500;
namespace api {
using namespace models;
bool Parameters::parseParameterscombinedresourceIdPostParams(const httplib::Request& req, Parameters::ParameterscombinedresourceIdPostRequest& params, std::vector<std::string>& paramErrors)
{
std::vector<std::string> errors;
if (!req.body.empty())
{
try
{
nlohmann::json json = nlohmann::json::parse(req.body);
SimpleObject temp;
from_json(json, temp);
params.m_request = temp;
}
catch (const std::exception& e)
{
errors.push_back("Invalid request body: " + std::string(e.what()));
}
}
// Query Parameters - filter
if (req.has_param("filter"))
{
params.m_filter = req.get_param_value("filter");
}
// Query Parameters - limit
if (req.has_param("limit"))
{
try
{
params.m_limit = std::stoi(req.get_param_value("limit"));
}
catch (const std::exception& e)
{
errors.push_back("Invalid query parameter 'limit': " + std::string(e.what()));
}
}
else
{
// Use default value for optional parameter
params.m_limit = 10;
}
// Header Parameters - X-Correlation-Id
if (!req.get_header_value("X-Correlation-Id").empty())
{
params.m_xCorrelationId = req.get_header_value("X-Correlation-Id");
}
// Header Parameters - X-Client-Version
if (!req.get_header_value("X-Client-Version").empty())
{
params.m_xClientVersion = req.get_header_value("X-Client-Version");
}
else
{
// Use default value for optional parameter
params.m_xClientVersion = "";
}
// Path Parameters - resourceId (index: 1)
if (req.matches.size() < 1 + 1)
{
errors.push_back("Missing path parameter 'resourceId'");
}
else
{
try
{
params.m_resourceId = std::stoi(req.matches[1]);
}
catch (const std::exception& e)
{
errors.push_back("Invalid path parameter 'resourceId': " + std::string(e.what()));
}
}
// Cookie Parameters - authToken
try
{
auto cookieHeader = req.get_header_value("Cookie");
if (!cookieHeader.empty())
{
std::string cookieValue;
std::string key = "authToken=";
size_t start = cookieHeader.find(key);
if (start != std::string::npos)
{
start += key.length();
size_t end = cookieHeader.find(";", start);
if (end == std::string::npos) end = cookieHeader.length();
cookieValue = cookieHeader.substr(start, end - start);
params.m_authToken = cookieValue;
}
}
}
catch (const std::exception& e)
{
errors.push_back("Invalid cookie parameter 'authToken': " + std::string(e.what()));
}
// Cookie Parameters - userPrefs
try
{
auto cookieHeader = req.get_header_value("Cookie");
if (!cookieHeader.empty())
{
std::string cookieValue;
std::string key = "userPrefs=";
size_t start = cookieHeader.find(key);
if (start != std::string::npos)
{
start += key.length();
size_t end = cookieHeader.find(";", start);
if (end == std::string::npos) end = cookieHeader.length();
cookieValue = cookieHeader.substr(start, end - start);
params.m_userPrefs = cookieValue;
}
else
{
// Use default value for optional parameter
params.m_userPrefs = "";
}
}
else
{
// Use default value for optional parameter
params.m_userPrefs = "";
}
}
catch (const std::exception& e)
{
errors.push_back("Invalid cookie parameter 'userPrefs': " + std::string(e.what()));
}
// Return errors via out-parameter, return false if any errors
if (!errors.empty())
{
paramErrors = std::move(errors);
return false;
}
return true;
}
void Parameters::handleParameterscombinedresourceIdPostResponse(const ParameterscombinedresourceIdPostResponse& result, httplib::Response& res)
{
std::visit([&](const auto& value)
{
using T = std::decay_t<decltype(value)>;
// Success types
if constexpr (std::is_same_v<T, models::TestAllParameterTypes200Response>)
{
res.status = HTTP_RESPONSE_CODE_TEST_ALL_PARAMETER_TYPES200_RESPONSE;
nlohmann::json responseJson;
to_json(responseJson, value);
res.set_content(responseJson.dump(), "application/json");
}
// Error types
else if constexpr (std::is_same_v<T, models::ErrorResponse>)
{
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
nlohmann::json errorJson = value;
res.set_content(errorJson.dump(), "application/json");
}
}, result);
}
bool Parameters::parseParameterscookiesGetParams(const httplib::Request& req, Parameters::ParameterscookiesGetRequest& params, std::vector<std::string>& paramErrors)
{
std::vector<std::string> errors;
// Cookie Parameters - sessionId
try
{
auto cookieHeader = req.get_header_value("Cookie");
if (!cookieHeader.empty())
{
std::string cookieValue;
std::string key = "sessionId=";
size_t start = cookieHeader.find(key);
if (start != std::string::npos)
{
start += key.length();
size_t end = cookieHeader.find(";", start);
if (end == std::string::npos) end = cookieHeader.length();
cookieValue = cookieHeader.substr(start, end - start);
params.m_sessionId = cookieValue;
}
}
}
catch (const std::exception& e)
{
errors.push_back("Invalid cookie parameter 'sessionId': " + std::string(e.what()));
}
// Cookie Parameters - userId
try
{
auto cookieHeader = req.get_header_value("Cookie");
if (!cookieHeader.empty())
{
std::string cookieValue;
std::string key = "userId=";
size_t start = cookieHeader.find(key);
if (start != std::string::npos)
{
start += key.length();
size_t end = cookieHeader.find(";", start);
if (end == std::string::npos) end = cookieHeader.length();
cookieValue = cookieHeader.substr(start, end - start);
params.m_userId = std::stoi(cookieValue);
}
else
{
// Use default value for optional parameter
params.m_userId = 0;
}
}
else
{
// Use default value for optional parameter
params.m_userId = 0;
}
}
catch (const std::exception& e)
{
errors.push_back("Invalid cookie parameter 'userId': " + std::string(e.what()));
}
// Cookie Parameters - preferences
try
{
auto cookieHeader = req.get_header_value("Cookie");
if (!cookieHeader.empty())
{
std::string cookieValue;
std::string key = "preferences=";
size_t start = cookieHeader.find(key);
if (start != std::string::npos)
{
start += key.length();
size_t end = cookieHeader.find(";", start);
if (end == std::string::npos) end = cookieHeader.length();
cookieValue = cookieHeader.substr(start, end - start);
params.m_preferences = cookieValue;
}
else
{
// Use default value for optional parameter
params.m_preferences = "";
}
}
else
{
// Use default value for optional parameter
params.m_preferences = "";
}
}
catch (const std::exception& e)
{
errors.push_back("Invalid cookie parameter 'preferences': " + std::string(e.what()));
}
// Return errors via out-parameter, return false if any errors
if (!errors.empty())
{
paramErrors = std::move(errors);
return false;
}
return true;
}
void Parameters::handleParameterscookiesGetResponse(const ParameterscookiesGetResponse& result, httplib::Response& res)
{
// Single response type
res.status = HTTP_RESPONSE_CODE_TEST_COOKIE_PARAMETERS200_RESPONSE;
nlohmann::json responseJson;
to_json(responseJson, result);
res.set_content(responseJson.dump(), "application/json");
}
bool Parameters::parseParametersheadersGetParams(const httplib::Request& req, Parameters::ParametersheadersGetRequest& params, std::vector<std::string>& paramErrors)
{
std::vector<std::string> errors;
// Header Parameters - X-Api-Version
if (!req.get_header_value("X-Api-Version").empty())
{
params.m_xApiVersion = req.get_header_value("X-Api-Version");
}
// Header Parameters - X-Request-Id
if (!req.get_header_value("X-Request-Id").empty())
{
params.m_xRequestId = req.get_header_value("X-Request-Id");
}
else
{
// Use default value for optional parameter
params.m_xRequestId = "";
}
// Header Parameters - X-Rate-Limit
if (!req.get_header_value("X-Rate-Limit").empty())
{
try
{
params.m_xRateLimit = std::stoi(req.get_header_value("X-Rate-Limit"));
}
catch (const std::exception& e)
{
errors.push_back("Invalid header parameter 'X-Rate-Limit': " + std::string(e.what()));
}
}
else
{
// Use default value for optional parameter
params.m_xRateLimit = 0;
}
// Header Parameters - X-Tags
if (!req.get_header_value("X-Tags").empty())
{
try
{
// Header arrays may be comma-separated
auto val = req.get_header_value("X-Tags");
std::stringstream ss(val);
std::string item;
if (!params.m_xTags.has_value())
{
params.m_xTags = std::vector<std::string>{};
}
while (std::getline(ss, item, ','))
{
if (!item.empty())
{
params.m_xTags->emplace_back(item);
}
}
}
catch (const std::exception& e)
{
errors.push_back("Invalid header parameter 'X-Tags': " + std::string(e.what()));
}
}
// Return errors via out-parameter, return false if any errors
if (!errors.empty())
{
paramErrors = std::move(errors);
return false;
}
return true;
}
void Parameters::handleParametersheadersGetResponse(const ParametersheadersGetResponse& result, httplib::Response& res)
{
std::visit([&](const auto& value)
{
using T = std::decay_t<decltype(value)>;
// Success types
if constexpr (std::is_same_v<T, models::TestHeaderParameters200Response>)
{
res.status = HTTP_RESPONSE_CODE_TEST_HEADER_PARAMETERS200_RESPONSE;
nlohmann::json responseJson;
to_json(responseJson, value);
res.set_content(responseJson.dump(), "application/json");
}
// Error types
else if constexpr (std::is_same_v<T, models::TestHeaderParameters401Response>)
{
res.status = HTTP_RESPONSE_CODE_TEST_HEADER_PARAMETERS401_RESPONSE;
nlohmann::json errorJson = value;
res.set_content(errorJson.dump(), "application/json");
}
}, result);
}
bool Parameters::parseParametersquerypathIdGetParams(const httplib::Request& req, Parameters::ParametersquerypathIdGetRequest& params, std::vector<std::string>& paramErrors)
{
std::vector<std::string> errors;
// Query Parameters - stringParam
if (req.has_param("stringParam"))
{
params.m_stringParam = req.get_param_value("stringParam");
}
// Query Parameters - intParam
if (req.has_param("intParam"))
{
try
{
params.m_intParam = std::stoi(req.get_param_value("intParam"));
}
catch (const std::exception& e)
{
errors.push_back("Invalid query parameter 'intParam': " + std::string(e.what()));
}
}
else
{
// Use default value for optional parameter
params.m_intParam = 42;
}
// Query Parameters - boolParam
if (req.has_param("boolParam"))
{
try
{
params.m_boolParam = (req.get_param_value("boolParam") == "true");
}
catch (const std::exception& e)
{
errors.push_back("Invalid query parameter 'boolParam': " + std::string(e.what()));
}
}
else
{
// Use default value for optional parameter
params.m_boolParam = false;
}
// Query Parameters - arrayParam
if (req.has_param("arrayParam"))
{
try
{
// form/simple: multi-param or comma-separated
size_t count = req.get_param_value_count("arrayParam");
if (!params.m_arrayParam.has_value())
{
params.m_arrayParam = std::vector<std::string>{};
}
if (count > 1)
{
for (size_t i = 0; i < count; ++i)
{
auto val = req.get_param_value("arrayParam", i);
params.m_arrayParam->emplace_back(val);
}
}
else if (count == 1)
{
auto val = req.get_param_value("arrayParam", 0);
std::stringstream ss(val);
std::string item;
while (std::getline(ss, item, ','))
{
if (!item.empty())
{
params.m_arrayParam->emplace_back(item);
}
}
}
}
catch (const std::exception& e)
{
errors.push_back("Invalid query parameter 'arrayParam': " + std::string(e.what()));
}
}
// Query Parameters - spaceDelimited
if (req.has_param("spaceDelimited"))
{
try
{
// form/simple: multi-param or comma-separated
size_t count = req.get_param_value_count("spaceDelimited");
if (!params.m_spaceDelimited.has_value())
{
params.m_spaceDelimited = std::vector<std::string>{};
}
if (count > 1)
{
for (size_t i = 0; i < count; ++i)
{
auto val = req.get_param_value("spaceDelimited", i);
params.m_spaceDelimited->emplace_back(val);
}
}
else if (count == 1)
{
auto val = req.get_param_value("spaceDelimited", 0);
std::stringstream ss(val);
std::string item;
while (std::getline(ss, item, ','))
{
if (!item.empty())
{
params.m_spaceDelimited->emplace_back(item);
}
}
}
}
catch (const std::exception& e)
{
errors.push_back("Invalid query parameter 'spaceDelimited': " + std::string(e.what()));
}
}
// Query Parameters - pipeDelimited
if (req.has_param("pipeDelimited"))
{
try
{
// form/simple: multi-param or comma-separated
size_t count = req.get_param_value_count("pipeDelimited");
if (!params.m_pipeDelimited.has_value())
{
params.m_pipeDelimited = std::vector<int>{};
}
if (count > 1)
{
for (size_t i = 0; i < count; ++i)
{
auto val = req.get_param_value("pipeDelimited", i);
params.m_pipeDelimited->emplace_back(std::stoi(val));
}
}
else if (count == 1)
{
auto val = req.get_param_value("pipeDelimited", 0);
std::stringstream ss(val);
std::string item;
while (std::getline(ss, item, ','))
{
if (!item.empty())
{
params.m_pipeDelimited->emplace_back(std::stoi(item));
}
}
}
}
catch (const std::exception& e)
{
errors.push_back("Invalid query parameter 'pipeDelimited': " + std::string(e.what()));
}
}
// Query Parameters - deepObject
if (req.has_param("deepObject"))
{
try
{
// Parse JSON object from query
auto val = req.get_param_value("deepObject", 0);
params.m_deepObject = nlohmann::json::parse(val).get<models::TestQueryParametersDeepObjectParameter>();
}
catch (const std::exception& e)
{
errors.push_back("Invalid query parameter 'deepObject': " + std::string(e.what()));
}
}
// Path Parameters - pathId (index: 1)
if (req.matches.size() < 1 + 1)
{
errors.push_back("Missing path parameter 'pathId'");
}
else
{
try
{
params.m_pathId = std::stoi(req.matches[1]);
}
catch (const std::exception& e)
{
errors.push_back("Invalid path parameter 'pathId': " + std::string(e.what()));
}
}
// Return errors via out-parameter, return false if any errors
if (!errors.empty())
{
paramErrors = std::move(errors);
return false;
}
return true;
}
void Parameters::handleParametersquerypathIdGetResponse(const ParametersquerypathIdGetResponse& result, httplib::Response& res)
{
// Single response type
res.status = HTTP_RESPONSE_CODE_TEST_QUERY_PARAMETERS200_RESPONSE;
nlohmann::json responseJson;
to_json(responseJson, result);
res.set_content(responseJson.dump(), "application/json");
}
void Parameters::handleParameterscombinedresourceIdPostRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
try
{
ParameterscombinedresourceIdPostRequest params;
std::vector<std::string> paramErrors;
if (!parseParameterscombinedresourceIdPostParams(req, params, paramErrors))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid parameters";
errorJson["errors"] = paramErrors;
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
res.set_content(errorJson.dump(), "application/json");
return;
}
auto result = handlePostForParameterscombinedresourceId(params);
handleParameterscombinedresourceIdPostResponse(result, res);
}
catch (const nlohmann::json::parse_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::invalid_iterator& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::type_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::out_of_range& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
res.set_content(errorJson.dump(), "application/json");
}
catch (const nlohmann::json::other_error& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid JSON: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
res.set_content(errorJson.dump(), "application/json");
}
}
void Parameters::handleParameterscookiesGetRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
try
{
ParameterscookiesGetRequest params;
std::vector<std::string> paramErrors;
if (!parseParameterscookiesGetParams(req, params, paramErrors))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid parameters";
errorJson["errors"] = paramErrors;
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
res.set_content(errorJson.dump(), "application/json");
return;
}
auto result = handleGetForParameterscookies(params);
handleParameterscookiesGetResponse(result, res);
}
catch (const std::exception& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Internal error: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_INTERNAL_SERVER_ERROR;
res.set_content(errorJson.dump(), "application/json");
}
}
void Parameters::handleParametersheadersGetRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
try
{
ParametersheadersGetRequest params;
std::vector<std::string> paramErrors;
if (!parseParametersheadersGetParams(req, params, paramErrors))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid parameters";
errorJson["errors"] = paramErrors;
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
res.set_content(errorJson.dump(), "application/json");
return;
}
auto result = handleGetForParametersheaders(params);
handleParametersheadersGetResponse(result, res);
}
catch (const std::exception& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Internal error: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_INTERNAL_SERVER_ERROR;
res.set_content(errorJson.dump(), "application/json");
}
}
void Parameters::handleParametersquerypathIdGetRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
try
{
ParametersquerypathIdGetRequest params;
std::vector<std::string> paramErrors;
if (!parseParametersquerypathIdGetParams(req, params, paramErrors))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Invalid parameters";
errorJson["errors"] = paramErrors;
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
res.set_content(errorJson.dump(), "application/json");
return;
}
auto result = handleGetForParametersquerypathId(params);
handleParametersquerypathIdGetResponse(result, res);
}
catch (const std::exception& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Internal error: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_INTERNAL_SERVER_ERROR;
res.set_content(errorJson.dump(), "application/json");
}
}
void Parameters::registerRoutes(httplib::Server& svr)
{
svr.Post("/parameters/combined/{resourceId}", [this]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleParameterscombinedresourceIdPostRequest(req, res);
});
svr.Get("/parameters/cookies", [this]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleParameterscookiesGetRequest(req, res);
});
svr.Get("/parameters/headers", [this]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleParametersheadersGetRequest(req, res);
});
svr.Get("/parameters/query/{pathId}", [this]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleParametersquerypathIdGetRequest(req, res);
});
}
} // namespace api

View File

@@ -0,0 +1,166 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <httplib.h>
#include <memory>
#include <variant>
#include <optional>
// Project headers
#include "models/ErrorResponse.h"
#include "models/SimpleObject.h"
#include "models/TestAllParameterTypes200Response.h"
#include "models/TestCookieParameters200Response.h"
#include "models/TestHeaderParameters200Response.h"
#include "models/TestHeaderParameters401Response.h"
#include "models/TestQueryParameters200Response.h"
#include "models/TestQueryParametersDeepObjectParameter.h"
namespace api {
class AuthenticationManager;
class Parameters {
public:
Parameters() = default;
virtual ~Parameters() = default;
/**
* @brief Register all routes for this API
* @param svr The httplib::Server instance to register routes on
*/
void registerRoutes(httplib::Server& svr);
// =========================
// ===== Request types =====
// =========================
/**
* @brief Request type for handlePostForParameterscombinedresourceId.
*/
struct ParameterscombinedresourceIdPostRequest
{
std::optional<models::SimpleObject> m_request; //Request Body (optional)
std::string m_filter; //Query Params (required)
std::optional<int> m_limit; //Query Params (optional)
std::string m_xCorrelationId; //HeaderParams (required)
std::optional<std::string> m_xClientVersion; //HeaderParams (optional)
int m_resourceId; //PathParams (always required)
std::string m_authToken; //Cookies (required)
std::optional<std::string> m_userPrefs; //Cookies (optional)
};
/**
* @brief Request type for handleGetForParameterscookies.
*/
struct ParameterscookiesGetRequest
{
std::string m_sessionId; //Cookies (required)
std::optional<int> m_userId; //Cookies (optional)
std::optional<std::string> m_preferences; //Cookies (optional)
};
/**
* @brief Request type for handleGetForParametersheaders.
*/
struct ParametersheadersGetRequest
{
std::string m_xApiVersion; //HeaderParams (required)
std::optional<std::string> m_xRequestId; //HeaderParams (optional)
std::optional<int> m_xRateLimit; //HeaderParams (optional)
std::optional<std::vector<std::string>> m_xTags; //HeaderParams (optional)
};
/**
* @brief Request type for handleGetForParametersquerypathId.
*/
struct ParametersquerypathIdGetRequest
{
std::string m_stringParam; //Query Params (required)
std::optional<int> m_intParam; //Query Params (optional)
std::optional<bool> m_boolParam; //Query Params (optional)
std::optional<std::vector<std::string>> m_arrayParam; //Query Params (optional)
std::optional<std::vector<std::string>> m_spaceDelimited; //Query Params (optional)
std::optional<std::vector<int>> m_pipeDelimited; //Query Params (optional)
std::optional<models::TestQueryParametersDeepObjectParameter> m_deepObject; //Query Params (optional)
int m_pathId; //PathParams (always required)
};
// ==========================
// ===== Response types =====
// ==========================
/**
* @brief Response type for handlePostForParameterscombinedresourceId.
*/
using ParameterscombinedresourceIdPostResponse = std::variant<
models::TestAllParameterTypes200Response ,
models::ErrorResponse >;
/**
* @brief Response type for handleGetForParameterscookies.
*/
using ParameterscookiesGetResponse = models::TestCookieParameters200Response;
/**
* @brief Response type for handleGetForParametersheaders.
*/
using ParametersheadersGetResponse = std::variant<
models::TestHeaderParameters200Response ,
models::TestHeaderParameters401Response >;
/**
* @brief Response type for handleGetForParametersquerypathId.
*/
using ParametersquerypathIdGetResponse = models::TestQueryParameters200Response;
// ============================================================
// ===== Pure virtual functions to be handled by the user =====
// ============================================================
/**
* ParameterscombinedresourceIdPostRequest - struct containing all the query parameters and headers and schemas as available.
* @return ParameterscombinedresourceIdPostResponse The response type returned by the handler.
*/
virtual ParameterscombinedresourceIdPostResponse handlePostForParameterscombinedresourceId(const ParameterscombinedresourceIdPostRequest& params)=0;
/**
* ParameterscookiesGetRequest - struct containing all the query parameters and headers and schemas as available.
* @return ParameterscookiesGetResponse The response type returned by the handler.
*/
virtual ParameterscookiesGetResponse handleGetForParameterscookies(const ParameterscookiesGetRequest& params)=0;
/**
* ParametersheadersGetRequest - struct containing all the query parameters and headers and schemas as available.
* @return ParametersheadersGetResponse The response type returned by the handler.
*/
virtual ParametersheadersGetResponse handleGetForParametersheaders(const ParametersheadersGetRequest& params)=0;
/**
* ParametersquerypathIdGetRequest - struct containing all the query parameters and headers and schemas as available.
* @return ParametersquerypathIdGetResponse The response type returned by the handler.
*/
virtual ParametersquerypathIdGetResponse handleGetForParametersquerypathId(const ParametersquerypathIdGetRequest& params)=0;
private:
// ========================================
// ===== Helper function declarations =====
// ========================================
static bool parseParameterscombinedresourceIdPostParams(const httplib::Request& req, ParameterscombinedresourceIdPostRequest& params, std::vector<std::string>& paramErrors);
void handleParameterscombinedresourceIdPostRequest(const httplib::Request& req, httplib::Response& res);
static void handleParameterscombinedresourceIdPostResponse(const ParameterscombinedresourceIdPostResponse& result, httplib::Response& res);
static bool parseParameterscookiesGetParams(const httplib::Request& req, ParameterscookiesGetRequest& params, std::vector<std::string>& paramErrors);
void handleParameterscookiesGetRequest(const httplib::Request& req, httplib::Response& res);
static void handleParameterscookiesGetResponse(const ParameterscookiesGetResponse& result, httplib::Response& res);
static bool parseParametersheadersGetParams(const httplib::Request& req, ParametersheadersGetRequest& params, std::vector<std::string>& paramErrors);
void handleParametersheadersGetRequest(const httplib::Request& req, httplib::Response& res);
static void handleParametersheadersGetResponse(const ParametersheadersGetResponse& result, httplib::Response& res);
static bool parseParametersquerypathIdGetParams(const httplib::Request& req, ParametersquerypathIdGetRequest& params, std::vector<std::string>& paramErrors);
void handleParametersquerypathIdGetRequest(const httplib::Request& req, httplib::Response& res);
static void handleParametersquerypathIdGetResponse(const ParametersquerypathIdGetResponse& result, httplib::Response& res);
};
} // namespace api

View File

@@ -0,0 +1,298 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
// System headers
#include <algorithm>
#include <cctype>
#include <locale>
// Project headers
#include "SecurityApi.h"
#include "AuthenticationManager.h"
constexpr int HTTP_RESPONSE_CODE_TEST_API_KEY_SECURITY200_RESPONSE = 200;
constexpr int HTTP_RESPONSE_CODE_ERROR_RESPONSE = 401;
constexpr int HTTP_RESPONSE_CODE_TEST_BASIC_SECURITY200_RESPONSE = 200;
constexpr int HTTP_RESPONSE_CODE_TEST_BEARER_SECURITY200_RESPONSE = 200;
constexpr int HTTP_RESPONSE_CODE_TEST_O_AUTH2_SECURITY200_RESPONSE = 200;
constexpr int HTTP_RESPONSE_CODE_INTERNAL_SERVER_ERROR = 500;
namespace api {
using namespace models;
void Security::handleSecurityapikeyGetResponse(const SecurityapikeyGetResponse& result, httplib::Response& res)
{
std::visit([&](const auto& value)
{
using T = std::decay_t<decltype(value)>;
// Success types
if constexpr (std::is_same_v<T, models::TestApiKeySecurity200Response>)
{
res.status = HTTP_RESPONSE_CODE_TEST_API_KEY_SECURITY200_RESPONSE;
nlohmann::json responseJson;
to_json(responseJson, value);
res.set_content(responseJson.dump(), "application/json");
}
// Error types
else if constexpr (std::is_same_v<T, models::ErrorResponse>)
{
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
nlohmann::json errorJson = value;
res.set_content(errorJson.dump(), "application/json");
}
}, result);
}
void Security::handleSecuritybasicGetResponse(const SecuritybasicGetResponse& result, httplib::Response& res)
{
std::visit([&](const auto& value)
{
using T = std::decay_t<decltype(value)>;
// Success types
if constexpr (std::is_same_v<T, models::TestBasicSecurity200Response>)
{
res.status = HTTP_RESPONSE_CODE_TEST_BASIC_SECURITY200_RESPONSE;
nlohmann::json responseJson;
to_json(responseJson, value);
res.set_content(responseJson.dump(), "application/json");
}
// Error types
else if constexpr (std::is_same_v<T, models::ErrorResponse>)
{
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
nlohmann::json errorJson = value;
res.set_content(errorJson.dump(), "application/json");
}
}, result);
}
void Security::handleSecuritybearerGetResponse(const SecuritybearerGetResponse& result, httplib::Response& res)
{
std::visit([&](const auto& value)
{
using T = std::decay_t<decltype(value)>;
// Success types
if constexpr (std::is_same_v<T, models::TestBearerSecurity200Response>)
{
res.status = HTTP_RESPONSE_CODE_TEST_BEARER_SECURITY200_RESPONSE;
nlohmann::json responseJson;
to_json(responseJson, value);
res.set_content(responseJson.dump(), "application/json");
}
// Error types
else if constexpr (std::is_same_v<T, models::ErrorResponse>)
{
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
nlohmann::json errorJson = value;
res.set_content(errorJson.dump(), "application/json");
}
}, result);
}
void Security::handleSecurityoauth2getResponse(const Securityoauth2getResponse& result, httplib::Response& res)
{
std::visit([&](const auto& value)
{
using T = std::decay_t<decltype(value)>;
// Success types
if constexpr (std::is_same_v<T, models::TestOAuth2Security200Response>)
{
res.status = HTTP_RESPONSE_CODE_TEST_O_AUTH2_SECURITY200_RESPONSE;
nlohmann::json responseJson;
to_json(responseJson, value);
res.set_content(responseJson.dump(), "application/json");
}
// Error types
else if constexpr (std::is_same_v<T, models::ErrorResponse>)
{
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
nlohmann::json errorJson = value;
res.set_content(errorJson.dump(), "application/json");
}
}, result);
}
bool Security::performAuthentication(
const httplib::Request& req,
std::shared_ptr<AuthenticationManager> auth,
httplib::Response& res)
{
if (!auth)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "AuthenticationManager not configured";
res.status = HTTP_RESPONSE_CODE_INTERNAL_SERVER_ERROR;
res.set_content(errorJson.dump(), "application/json");
return false;
}
if (req.has_header("X-API-Key"))
{
if (auth->validateApiKey(req.get_header_value("X-API-Key"))) return true;
}
if (req.has_header("Authorization"))
{
auto authHeader = req.get_header_value("Authorization");
if (authHeader.find("Basic ") == 0)
{
std::string credentials = authHeader.substr(6);
if (auth->validateBasicAuth(credentials, "")) return true;
}
}
if (req.has_header("Authorization"))
{
auto authHeader = req.get_header_value("Authorization");
if (authHeader.find("Bearer ") == 0)
{
std::string token = authHeader.substr(7);
if (auth->validateBearerToken(token)) return true;
}
}
if (req.has_header("Authorization"))
{
auto authHeader = req.get_header_value("Authorization");
if (authHeader.find("Bearer ") == 0)
{
std::string token = authHeader.substr(7);
std::vector<std::string> requiredScopes = { "read:users", "write:users" };
if (auth->validateOAuth2(token, requiredScopes)) return true;
}
}
return false;
}
void Security::handleSecurityapikeyGetRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res, std::shared_ptr<AuthenticationManager> auth)
{
try
{
if (!performAuthentication(req, auth, res))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Authentication required";
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
res.set_content(errorJson.dump(), "application/json");
return;
}
auto result = handleGetForSecurityapikey();
handleSecurityapikeyGetResponse(result, res);
}
catch (const std::exception& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Internal error: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_INTERNAL_SERVER_ERROR;
res.set_content(errorJson.dump(), "application/json");
}
}
void Security::handleSecuritybasicGetRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res, std::shared_ptr<AuthenticationManager> auth)
{
try
{
if (!performAuthentication(req, auth, res))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Authentication required";
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
res.set_content(errorJson.dump(), "application/json");
return;
}
auto result = handleGetForSecuritybasic();
handleSecuritybasicGetResponse(result, res);
}
catch (const std::exception& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Internal error: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_INTERNAL_SERVER_ERROR;
res.set_content(errorJson.dump(), "application/json");
}
}
void Security::handleSecuritybearerGetRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res, std::shared_ptr<AuthenticationManager> auth)
{
try
{
if (!performAuthentication(req, auth, res))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Authentication required";
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
res.set_content(errorJson.dump(), "application/json");
return;
}
auto result = handleGetForSecuritybearer();
handleSecuritybearerGetResponse(result, res);
}
catch (const std::exception& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Internal error: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_INTERNAL_SERVER_ERROR;
res.set_content(errorJson.dump(), "application/json");
}
}
void Security::handleSecurityoauth2GetRequest([[maybe_unused]] const httplib::Request& req, httplib::Response& res, std::shared_ptr<AuthenticationManager> auth)
{
try
{
if (!performAuthentication(req, auth, res))
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Authentication required";
res.status = HTTP_RESPONSE_CODE_ERROR_RESPONSE;
res.set_content(errorJson.dump(), "application/json");
return;
}
auto result = handleGetForSecurityoauth2();
handleSecurityoauth2getResponse(result, res);
}
catch (const std::exception& e)
{
nlohmann::json errorJson = nlohmann::json::object();
errorJson["message"] = "Internal error: " + std::string(e.what());
res.status = HTTP_RESPONSE_CODE_INTERNAL_SERVER_ERROR;
res.set_content(errorJson.dump(), "application/json");
}
}
void Security::registerRoutes(httplib::Server& svr, std::shared_ptr<AuthenticationManager> auth)
{
svr.Get("/security/apikey", [this, auth]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleSecurityapikeyGetRequest(req, res, auth);
});
svr.Get("/security/basic", [this, auth]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleSecuritybasicGetRequest(req, res, auth);
});
svr.Get("/security/bearer", [this, auth]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleSecuritybearerGetRequest(req, res, auth);
});
svr.Get("/security/oauth2", [this, auth]([[maybe_unused]] const httplib::Request& req, httplib::Response& res)
{
handleSecurityoauth2GetRequest(req, res, auth);
});
}
} // namespace api

View File

@@ -0,0 +1,106 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <httplib.h>
#include <memory>
#include <variant>
// Project headers
#include "models/ErrorResponse.h"
#include "models/TestApiKeySecurity200Response.h"
#include "models/TestBasicSecurity200Response.h"
#include "models/TestBearerSecurity200Response.h"
#include "models/TestOAuth2Security200Response.h"
namespace api {
class AuthenticationManager;
class Security {
public:
Security() = default;
virtual ~Security() = default;
/**
* @brief Register all routes for this API
* @param svr The httplib::Server instance to register routes on
* @param auth The AuthenticationManager for authentication (optional, defaults to nullptr)
*/
void registerRoutes(httplib::Server& svr, std::shared_ptr<AuthenticationManager> auth = nullptr);
// ==========================
// ===== Response types =====
// ==========================
/**
* @brief Response type for handleGetForSecurityapikey.
*/
using SecurityapikeyGetResponse = std::variant<
models::TestApiKeySecurity200Response ,
models::ErrorResponse >;
/**
* @brief Response type for handleGetForSecuritybasic.
*/
using SecuritybasicGetResponse = std::variant<
models::TestBasicSecurity200Response ,
models::ErrorResponse >;
/**
* @brief Response type for handleGetForSecuritybearer.
*/
using SecuritybearerGetResponse = std::variant<
models::TestBearerSecurity200Response ,
models::ErrorResponse >;
/**
* @brief Response type for handleGetForSecurityoauth2.
*/
using Securityoauth2getResponse = std::variant<
models::TestOAuth2Security200Response ,
models::ErrorResponse >;
// ============================================================
// ===== Pure virtual functions to be handled by the user =====
// ============================================================
/**
* @return SecurityapikeyGetResponse The response type returned by the handler.
*/
virtual SecurityapikeyGetResponse handleGetForSecurityapikey()=0;
/**
* @return SecuritybasicGetResponse The response type returned by the handler.
*/
virtual SecuritybasicGetResponse handleGetForSecuritybasic()=0;
/**
* @return SecuritybearerGetResponse The response type returned by the handler.
*/
virtual SecuritybearerGetResponse handleGetForSecuritybearer()=0;
/**
* @return Securityoauth2getResponse The response type returned by the handler.
*/
virtual Securityoauth2getResponse handleGetForSecurityoauth2()=0;
private:
// ========================================
// ===== Helper function declarations =====
// ========================================
void handleSecurityapikeyGetRequest(const httplib::Request& req, httplib::Response& res, std::shared_ptr<AuthenticationManager> auth);
static void handleSecurityapikeyGetResponse(const SecurityapikeyGetResponse& result, httplib::Response& res);
void handleSecuritybasicGetRequest(const httplib::Request& req, httplib::Response& res, std::shared_ptr<AuthenticationManager> auth);
static void handleSecuritybasicGetResponse(const SecuritybasicGetResponse& result, httplib::Response& res);
void handleSecuritybearerGetRequest(const httplib::Request& req, httplib::Response& res, std::shared_ptr<AuthenticationManager> auth);
static void handleSecuritybearerGetResponse(const SecuritybearerGetResponse& result, httplib::Response& res);
void handleSecurityoauth2GetRequest(const httplib::Request& req, httplib::Response& res, std::shared_ptr<AuthenticationManager> auth);
static void handleSecurityoauth2getResponse(const Securityoauth2getResponse& result, httplib::Response& res);
static bool performAuthentication(
const httplib::Request& req,
std::shared_ptr<AuthenticationManager> auth,
httplib::Response& res);
};
} // namespace api

View File

@@ -0,0 +1,67 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "Address.h"
namespace models {
Address::Address()
: street("")
, city("")
, zipCode("")
, country("USA")
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string Address::getStreet() const
{
return street;
}
std::string Address::getCity() const
{
return city;
}
std::string Address::getZipCode() const
{
return zipCode;
}
std::string Address::getCountry() const
{
return country;
}
// ===================
// ===== Setters =====
// ===================
void Address::setStreet(const std::string& streetObj)
{
street = streetObj;
}
void Address::setCity(const std::string& cityObj)
{
city = cityObj;
}
void Address::setZipCode(const std::string& zipCodeObj)
{
zipCode = zipCodeObj;
}
void Address::setCountry(const std::string& countryObj)
{
country = countryObj;
}
} // namespace models

View File

@@ -0,0 +1,48 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <string>
namespace models {
class Address
{
public:
Address();
virtual ~Address() = default;
// Getters and setters
[[nodiscard]] std::string getStreet() const;
void setStreet(const std::string& street);
[[nodiscard]] std::string getCity() const;
void setCity(const std::string& city);
[[nodiscard]] std::string getZipCode() const;
void setZipCode(const std::string& zipCode);
[[nodiscard]] std::string getCountry() const;
void setCountry(const std::string& country);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(Address,
street, city, zipCode, country)
private:
std::string street;
std::string city;
std::string zipCode;
std::string country;
};
} // namespace models

View File

@@ -0,0 +1,49 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "Animal.h"
namespace models {
Animal::Animal()
: name("")
, type("")
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string Animal::getName() const
{
return name;
}
std::string Animal::getType() const
{
return type;
}
// ===================
// ===== Setters =====
// ===================
void Animal::setName(const std::string& nameObj)
{
name = nameObj;
}
void Animal::setType(const std::string& typeObj)
{
type = typeObj;
}
} // namespace models

View File

@@ -0,0 +1,42 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <string>
namespace models {
class Animal
{
public:
Animal();
virtual ~Animal() = default;
// Getters and setters
[[nodiscard]] std::string getName() const;
void setName(const std::string& name);
[[nodiscard]] std::string getType() const;
void setType(const std::string& type);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(Animal,
name, type)
private:
std::string name;
std::string type;
};
} // namespace models

View File

@@ -0,0 +1,76 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "ArrayTypes.h"
namespace models {
ArrayTypes::ArrayTypes()
: stringArray(std::vector<std::string>())
, intArray(std::vector<int>())
, objectArray(std::vector<SimpleObject>())
, enumArray(std::vector<ArrayTypes::EnumArrayEnum>())
, nestedArray(std::vector<std::vector<int>>())
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::vector<std::string> ArrayTypes::getStringArray() const
{
return stringArray;
}
std::vector<int> ArrayTypes::getIntArray() const
{
return intArray;
}
std::vector<SimpleObject> ArrayTypes::getObjectArray() const
{
return objectArray;
}
std::vector<ArrayTypes::EnumArrayEnum> ArrayTypes::getEnumArray() const
{
return enumArray;
}
std::vector<std::vector<int>> ArrayTypes::getNestedArray() const
{
return nestedArray;
}
// ===================
// ===== Setters =====
// ===================
void ArrayTypes::setStringArray(const std::vector<std::string>& stringArrayObj)
{
stringArray = stringArrayObj;
}
void ArrayTypes::setIntArray(const std::vector<int>& intArrayObj)
{
intArray = intArrayObj;
}
void ArrayTypes::setObjectArray(const std::vector<SimpleObject>& objectArrayObj)
{
objectArray = objectArrayObj;
}
void ArrayTypes::setEnumArray(const std::vector<ArrayTypes::EnumArrayEnum>& enumArrayObj)
{
enumArray = enumArrayObj;
}
void ArrayTypes::setNestedArray(const std::vector<std::vector<int>>& nestedArrayObj)
{
nestedArray = nestedArrayObj;
}
} // namespace models

View File

@@ -0,0 +1,64 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <cstdint>
#include <string>
#include <vector>
#include "SimpleObject.h"
namespace models {
class ArrayTypes
{
public:
enum class EnumArrayEnum {
RED,
GREEN,
BLUE
};
// Enum conversion functions (definitions in .cpp)
static std::string EnumArrayEnumToString(EnumArrayEnum value);
static EnumArrayEnum EnumArrayEnumFromString(const std::string& str);
ArrayTypes();
virtual ~ArrayTypes() = default;
// Getters and setters
[[nodiscard]] std::vector<std::string> getStringArray() const;
void setStringArray(const std::vector<std::string>& stringArray);
[[nodiscard]] std::vector<int> getIntArray() const;
void setIntArray(const std::vector<int>& intArray);
[[nodiscard]] std::vector<SimpleObject> getObjectArray() const;
void setObjectArray(const std::vector<SimpleObject>& objectArray);
[[nodiscard]] std::vector<ArrayTypes::EnumArrayEnum> getEnumArray() const;
void setEnumArray(const std::vector<ArrayTypes::EnumArrayEnum>& enumArray);
[[nodiscard]] std::vector<std::vector<int>> getNestedArray() const;
void setNestedArray(const std::vector<std::vector<int>>& nestedArray);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(ArrayTypes,
stringArray, intArray, objectArray, enumArray, nestedArray)
private:
std::vector<std::string> stringArray;
std::vector<int> intArray;
std::vector<SimpleObject> objectArray;
std::vector<ArrayTypes::EnumArrayEnum> enumArray;
std::vector<std::vector<int>> nestedArray;
};
} // namespace models

View File

@@ -0,0 +1,58 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "BankAccount.h"
namespace models {
BankAccount::BankAccount()
: paymentType("")
, accountNumber("")
, bankName("")
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string BankAccount::getPaymentType() const
{
return paymentType;
}
std::string BankAccount::getAccountNumber() const
{
return accountNumber;
}
std::string BankAccount::getBankName() const
{
return bankName;
}
// ===================
// ===== Setters =====
// ===================
void BankAccount::setPaymentType(const std::string& paymentTypeObj)
{
paymentType = paymentTypeObj;
}
void BankAccount::setAccountNumber(const std::string& accountNumberObj)
{
accountNumber = accountNumberObj;
}
void BankAccount::setBankName(const std::string& bankNameObj)
{
bankName = bankNameObj;
}
} // namespace models

View File

@@ -0,0 +1,45 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <string>
namespace models {
class BankAccount
{
public:
BankAccount();
virtual ~BankAccount() = default;
// Getters and setters
[[nodiscard]] std::string getPaymentType() const;
void setPaymentType(const std::string& paymentType);
[[nodiscard]] std::string getAccountNumber() const;
void setAccountNumber(const std::string& accountNumber);
[[nodiscard]] std::string getBankName() const;
void setBankName(const std::string& bankName);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(BankAccount,
paymentType, accountNumber, bankName)
private:
std::string paymentType;
std::string accountNumber;
std::string bankName;
};
} // namespace models

View File

@@ -0,0 +1,67 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "Company.h"
namespace models {
Company::Company()
: name("")
, headquarters(Address())
, departments(std::vector<Department>())
, metadata(std::map<std::string, nlohmann::json>())
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string Company::getName() const
{
return name;
}
Address Company::getHeadquarters() const
{
return headquarters;
}
std::vector<Department> Company::getDepartments() const
{
return departments;
}
std::map<std::string, nlohmann::json> Company::getMetadata() const
{
return metadata;
}
// ===================
// ===== Setters =====
// ===================
void Company::setName(const std::string& nameObj)
{
name = nameObj;
}
void Company::setHeadquarters(const Address& headquartersObj)
{
headquarters = headquartersObj;
}
void Company::setDepartments(const std::vector<Department>& departmentsObj)
{
departments = departmentsObj;
}
void Company::setMetadata(const std::map<std::string, nlohmann::json>& metadataObj)
{
metadata = metadataObj;
}
} // namespace models

View File

@@ -0,0 +1,51 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <string>
#include <vector>
#include "Address.h"
#include "Department.h"
namespace models {
class Company
{
public:
Company();
virtual ~Company() = default;
// Getters and setters
[[nodiscard]] std::string getName() const;
void setName(const std::string& name);
[[nodiscard]] Address getHeadquarters() const;
void setHeadquarters(const Address& headquarters);
[[nodiscard]] std::vector<Department> getDepartments() const;
void setDepartments(const std::vector<Department>& departments);
[[nodiscard]] std::map<std::string, nlohmann::json> getMetadata() const;
void setMetadata(const std::map<std::string, nlohmann::json>& metadata);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(Company,
name, headquarters, departments, metadata)
private:
std::string name;
Address headquarters;
std::vector<Department> departments;
std::map<std::string, nlohmann::json> metadata;
};
} // namespace models

View File

@@ -0,0 +1,58 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "CreatedResponse.h"
namespace models {
CreatedResponse::CreatedResponse()
: status("")
, id(0)
, location("")
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string CreatedResponse::getStatus() const
{
return status;
}
int CreatedResponse::getId() const
{
return id;
}
std::string CreatedResponse::getLocation() const
{
return location;
}
// ===================
// ===== Setters =====
// ===================
void CreatedResponse::setStatus(const std::string& statusObj)
{
status = statusObj;
}
void CreatedResponse::setId(const int& idObj)
{
id = idObj;
}
void CreatedResponse::setLocation(const std::string& locationObj)
{
location = locationObj;
}
} // namespace models

View File

@@ -0,0 +1,46 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <cstdint>
#include <string>
namespace models {
class CreatedResponse
{
public:
CreatedResponse();
virtual ~CreatedResponse() = default;
// Getters and setters
[[nodiscard]] std::string getStatus() const;
void setStatus(const std::string& status);
[[nodiscard]] int getId() const;
void setId(const int& id);
[[nodiscard]] std::string getLocation() const;
void setLocation(const std::string& location);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(CreatedResponse,
status, id, location)
private:
std::string status;
int id;
std::string location;
};
} // namespace models

View File

@@ -0,0 +1,94 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "CreditCard.h"
namespace models {
CreditCard::CreditCard()
: paymentType("")
, cardNumber("")
, cardType(CardTypeEnum::UNSPECIFIED)
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string CreditCard::getPaymentType() const
{
return paymentType;
}
std::string CreditCard::getCardNumber() const
{
return cardNumber;
}
CreditCard::CardTypeEnum CreditCard::getCardType() const
{
return cardType;
}
// ===================
// ===== Setters =====
// ===================
void CreditCard::setPaymentType(const std::string& paymentTypeObj)
{
paymentType = paymentTypeObj;
}
void CreditCard::setCardNumber(const std::string& cardNumberObj)
{
cardNumber = cardNumberObj;
}
void CreditCard::setCardType(const CardTypeEnum& cardTypeObj)
{
cardType = cardTypeObj;
}
// =========================================
// ===== Enum CardTypeEnum Conversions =====
// =========================================
std::string CreditCard::CardTypeEnumToString(CreditCard::CardTypeEnum value)
{
switch (value)
{
case CardTypeEnum::UNSPECIFIED: return "UNSPECIFIED";
case CardTypeEnum::VISA: return "VISA";
case CardTypeEnum::MASTERCARD: return "MASTERCARD";
case CardTypeEnum::AMEX: return "AMEX";
default: return {};
}
}
CreditCard::CardTypeEnum CreditCard::CardTypeEnumFromString(const std::string& str)
{
if (str == "UNSPECIFIED")
{
return CardTypeEnum::UNSPECIFIED;
}
if (str == "VISA")
{
return CardTypeEnum::VISA;
}
if (str == "MASTERCARD")
{
return CardTypeEnum::MASTERCARD;
}
if (str == "AMEX")
{
return CardTypeEnum::AMEX;
}
throw std::invalid_argument("Invalid enum value");
}
} // namespace models

View File

@@ -0,0 +1,68 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <string>
namespace models {
class CreditCard
{
public:
enum class CardTypeEnum {
UNSPECIFIED,
VISA,
MASTERCARD,
AMEX
};
// Enum conversion functions (definitions in .cpp)
static std::string CardTypeEnumToString(CardTypeEnum value);
static CardTypeEnum CardTypeEnumFromString(const std::string& str);
CreditCard();
virtual ~CreditCard() = default;
// Getters and setters
[[nodiscard]] std::string getPaymentType() const;
void setPaymentType(const std::string& paymentType);
[[nodiscard]] std::string getCardNumber() const;
void setCardNumber(const std::string& cardNumber);
[[nodiscard]] CardTypeEnum getCardType() const;
void setCardType(const CardTypeEnum& cardType);
// Serialization helpers for CardTypeEnum
friend inline void to_json(nlohmann::json& j, const CardTypeEnum& e)
{
j = CardTypeEnumToString(e);
}
friend inline void from_json(const nlohmann::json& j, CardTypeEnum& e)
{
e = CardTypeEnumFromString(j.get<std::string>());
}
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(CreditCard,
paymentType, cardNumber, cardType)
private:
std::string paymentType;
std::string cardNumber;
CardTypeEnum cardType;
};
} // namespace models

View File

@@ -0,0 +1,58 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "Department.h"
namespace models {
Department::Department()
: name("")
, manager(Employee())
, employees(std::vector<Employee>())
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string Department::getName() const
{
return name;
}
Employee Department::getManager() const
{
return manager;
}
std::vector<Employee> Department::getEmployees() const
{
return employees;
}
// ===================
// ===== Setters =====
// ===================
void Department::setName(const std::string& nameObj)
{
name = nameObj;
}
void Department::setManager(const Employee& managerObj)
{
manager = managerObj;
}
void Department::setEmployees(const std::vector<Employee>& employeesObj)
{
employees = employeesObj;
}
} // namespace models

View File

@@ -0,0 +1,47 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <string>
#include <vector>
#include "Employee.h"
namespace models {
class Department
{
public:
Department();
virtual ~Department() = default;
// Getters and setters
[[nodiscard]] std::string getName() const;
void setName(const std::string& name);
[[nodiscard]] Employee getManager() const;
void setManager(const Employee& manager);
[[nodiscard]] std::vector<Employee> getEmployees() const;
void setEmployees(const std::vector<Employee>& employees);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(Department,
name, manager, employees)
private:
std::string name;
Employee manager;
std::vector<Employee> employees;
};
} // namespace models

View File

@@ -0,0 +1,49 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "Dog.h"
namespace models {
Dog::Dog()
: breed("")
, barkVolume(0)
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string Dog::getBreed() const
{
return breed;
}
int Dog::getBarkVolume() const
{
return barkVolume;
}
// ===================
// ===== Setters =====
// ===================
void Dog::setBreed(const std::string& breedObj)
{
breed = breedObj;
}
void Dog::setBarkVolume(const int& barkVolumeObj)
{
barkVolume = barkVolumeObj;
}
} // namespace models

View File

@@ -0,0 +1,45 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <cstdint>
#include <string>
// Project headers
#include "Animal.h"
namespace models {
class Dog : public Animal
{
public:
Dog();
virtual ~Dog() = default;
// Getters and setters
[[nodiscard]] std::string getBreed() const;
void setBreed(const std::string& breed);
[[nodiscard]] int getBarkVolume() const;
void setBarkVolume(const int& barkVolume);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(Dog,
breed, barkVolume)
private:
std::string breed;
int barkVolume;
};
} // namespace models

View File

@@ -0,0 +1,76 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "Employee.h"
namespace models {
Employee::Employee()
: id(0)
, name("")
, email("")
, address(Address())
, skills(std::vector<std::string>())
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
int Employee::getId() const
{
return id;
}
std::string Employee::getName() const
{
return name;
}
std::string Employee::getEmail() const
{
return email;
}
Address Employee::getAddress() const
{
return address;
}
std::vector<std::string> Employee::getSkills() const
{
return skills;
}
// ===================
// ===== Setters =====
// ===================
void Employee::setId(const int& idObj)
{
id = idObj;
}
void Employee::setName(const std::string& nameObj)
{
name = nameObj;
}
void Employee::setEmail(const std::string& emailObj)
{
email = emailObj;
}
void Employee::setAddress(const Address& addressObj)
{
address = addressObj;
}
void Employee::setSkills(const std::vector<std::string>& skillsObj)
{
skills = skillsObj;
}
} // namespace models

View File

@@ -0,0 +1,54 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <cstdint>
#include <string>
#include <vector>
#include "Address.h"
namespace models {
class Employee
{
public:
Employee();
virtual ~Employee() = default;
// Getters and setters
[[nodiscard]] int getId() const;
void setId(const int& id);
[[nodiscard]] std::string getName() const;
void setName(const std::string& name);
[[nodiscard]] std::string getEmail() const;
void setEmail(const std::string& email);
[[nodiscard]] Address getAddress() const;
void setAddress(const Address& address);
[[nodiscard]] std::vector<std::string> getSkills() const;
void setSkills(const std::vector<std::string>& skills);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(Employee,
id, name, email, address, skills)
private:
int id;
std::string name;
std::string email;
Address address;
std::vector<std::string> skills;
};
} // namespace models

View File

@@ -0,0 +1,176 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "EnumTypes.h"
namespace models {
EnumTypes::EnumTypes()
: stringEnum(std::nullopt)
, numericEnum(std::nullopt)
, statusCode(std::nullopt)
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::optional<EnumTypes::StringEnumEnum> EnumTypes::getStringEnum() const
{
return stringEnum;
}
std::optional<EnumTypes::NumericEnumEnum> EnumTypes::getNumericEnum() const
{
return numericEnum;
}
std::optional<EnumTypes::StatusCodeEnum> EnumTypes::getStatusCode() const
{
return statusCode;
}
// ===================
// ===== Setters =====
// ===================
void EnumTypes::setStringEnum(const std::optional<StringEnumEnum>& stringEnumObj)
{
stringEnum = stringEnumObj;
}
void EnumTypes::setNumericEnum(const std::optional<NumericEnumEnum>& numericEnumObj)
{
numericEnum = numericEnumObj;
}
void EnumTypes::setStatusCode(const std::optional<StatusCodeEnum>& statusCodeObj)
{
statusCode = statusCodeObj;
}
// =========================================
// ===== Enum StringEnumEnum Conversions =====
// =========================================
std::string EnumTypes::StringEnumEnumToString(EnumTypes::StringEnumEnum value)
{
switch (value)
{
case StringEnumEnum::UNSPECIFIED: return "UNSPECIFIED";
case StringEnumEnum::PENDING: return "PENDING";
case StringEnumEnum::APPROVED: return "APPROVED";
case StringEnumEnum::REJECTED: return "REJECTED";
default: return {};
}
}
EnumTypes::StringEnumEnum EnumTypes::StringEnumEnumFromString(const std::string& str)
{
if (str == "UNSPECIFIED")
{
return StringEnumEnum::UNSPECIFIED;
}
if (str == "PENDING")
{
return StringEnumEnum::PENDING;
}
if (str == "APPROVED")
{
return StringEnumEnum::APPROVED;
}
if (str == "REJECTED")
{
return StringEnumEnum::REJECTED;
}
throw std::invalid_argument("Invalid enum value");
}
// =========================================
// ===== Enum NumericEnumEnum Conversions =====
// =========================================
std::string EnumTypes::NumericEnumEnumToString(EnumTypes::NumericEnumEnum value)
{
switch (value)
{
case NumericEnumEnum::UNSPECIFIED: return "UNSPECIFIED";
case NumericEnumEnum::_100: return "_100";
case NumericEnumEnum::_200: return "_200";
case NumericEnumEnum::_300: return "_300";
case NumericEnumEnum::_404: return "_404";
case NumericEnumEnum::_500: return "_500";
default: return {};
}
}
EnumTypes::NumericEnumEnum EnumTypes::NumericEnumEnumFromString(const std::string& str)
{
if (str == "UNSPECIFIED")
{
return NumericEnumEnum::UNSPECIFIED;
}
if (str == "_100")
{
return NumericEnumEnum::_100;
}
if (str == "_200")
{
return NumericEnumEnum::_200;
}
if (str == "_300")
{
return NumericEnumEnum::_300;
}
if (str == "_404")
{
return NumericEnumEnum::_404;
}
if (str == "_500")
{
return NumericEnumEnum::_500;
}
throw std::invalid_argument("Invalid enum value");
}
// =========================================
// ===== Enum StatusCodeEnum Conversions =====
// =========================================
std::string EnumTypes::StatusCodeEnumToString(EnumTypes::StatusCodeEnum value)
{
switch (value)
{
case StatusCodeEnum::UNSPECIFIED: return "UNSPECIFIED";
case StatusCodeEnum::_200: return "_200";
case StatusCodeEnum::_404: return "_404";
case StatusCodeEnum::_500: return "_500";
default: return {};
}
}
EnumTypes::StatusCodeEnum EnumTypes::StatusCodeEnumFromString(const std::string& str)
{
if (str == "UNSPECIFIED")
{
return StatusCodeEnum::UNSPECIFIED;
}
if (str == "_200")
{
return StatusCodeEnum::_200;
}
if (str == "_404")
{
return StatusCodeEnum::_404;
}
if (str == "_500")
{
return StatusCodeEnum::_500;
}
throw std::invalid_argument("Invalid enum value");
}
} // namespace models

View File

@@ -0,0 +1,171 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <optional>
#include <cstdint>
#include <string>
namespace models {
class EnumTypes
{
public:
// ===================
// ===== Enums =======
// ===================
enum class StringEnumEnum {
UNSPECIFIED,
PENDING,
APPROVED,
REJECTED
};
// Enum conversion functions (definitions in .cpp)
static std::string StringEnumEnumToString(StringEnumEnum value);
static StringEnumEnum StringEnumEnumFromString(const std::string& str);
enum class NumericEnumEnum {
UNSPECIFIED,
_100,
_200,
_300,
_404,
_500
};
// Enum conversion functions (definitions in .cpp)
static std::string NumericEnumEnumToString(NumericEnumEnum value);
static NumericEnumEnum NumericEnumEnumFromString(const std::string& str);
enum class StatusCodeEnum {
UNSPECIFIED,
_200,
_404,
_500
};
// Enum conversion functions (definitions in .cpp)
static std::string StatusCodeEnumToString(StatusCodeEnum value);
static StatusCodeEnum StatusCodeEnumFromString(const std::string& str);
EnumTypes();
virtual ~EnumTypes() = default;
// Getters and setters
[[nodiscard]] std::optional<StringEnumEnum> getStringEnum() const;
void setStringEnum(const std::optional<StringEnumEnum>& stringEnum);
[[nodiscard]] std::optional<NumericEnumEnum> getNumericEnum() const;
void setNumericEnum(const std::optional<NumericEnumEnum>& numericEnum);
[[nodiscard]] std::optional<StatusCodeEnum> getStatusCode() const;
void setStatusCode(const std::optional<StatusCodeEnum>& statusCode);
// =============================================================================
// Friend Enum Serialization Helpers (Required for NLOHMANN JSON serialization)
// =============================================================================
// These friend functions must be declared inside the class because:
// 1. The enum types are nested and don't exist before the class is defined
// 2. NLOHMANN macros need custom serialization for enum types (uses ToString/FromString)
// 3. The 'friend' keyword makes them free functions in the namespace (not member functions)
// so ADL (Argument-Dependent Lookup) can find them during JSON serialization
// =============================================================================
// Serialization helpers for std::optional<StringEnumEnum>
friend inline void to_json(nlohmann::json& j, const std::optional<StringEnumEnum>& opt)
{
if (opt.has_value())
{
j = StringEnumEnumToString(opt.value());
}
else
{
j = nullptr;
}
}
friend inline void from_json(const nlohmann::json& j, std::optional<StringEnumEnum>& opt)
{
if (j.is_null())
{
opt = std::nullopt;
}
else
{
opt = StringEnumEnumFromString(j.get<std::string>());
}
}
// Serialization helpers for std::optional<NumericEnumEnum>
friend inline void to_json(nlohmann::json& j, const std::optional<NumericEnumEnum>& opt)
{
if (opt.has_value())
{
j = NumericEnumEnumToString(opt.value());
}
else
{
j = nullptr;
}
}
friend inline void from_json(const nlohmann::json& j, std::optional<NumericEnumEnum>& opt)
{
if (j.is_null())
{
opt = std::nullopt;
}
else
{
opt = NumericEnumEnumFromString(j.get<std::string>());
}
}
// Serialization helpers for std::optional<StatusCodeEnum>
friend inline void to_json(nlohmann::json& j, const std::optional<StatusCodeEnum>& opt)
{
if (opt.has_value())
{
j = StatusCodeEnumToString(opt.value());
}
else
{
j = nullptr;
}
}
friend inline void from_json(const nlohmann::json& j, std::optional<StatusCodeEnum>& opt)
{
if (j.is_null())
{
opt = std::nullopt;
}
else
{
opt = StatusCodeEnumFromString(j.get<std::string>());
}
}
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(EnumTypes,
stringEnum, numericEnum, statusCode)
private:
std::optional<StringEnumEnum> stringEnum;
std::optional<NumericEnumEnum> numericEnum;
std::optional<StatusCodeEnum> statusCode;
};
} // namespace models

View File

@@ -0,0 +1,58 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "ErrorResponse.h"
namespace models {
ErrorResponse::ErrorResponse()
: message("")
, code(0)
, details(std::vector<std::string>())
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string ErrorResponse::getMessage() const
{
return message;
}
int ErrorResponse::getCode() const
{
return code;
}
std::vector<std::string> ErrorResponse::getDetails() const
{
return details;
}
// ===================
// ===== Setters =====
// ===================
void ErrorResponse::setMessage(const std::string& messageObj)
{
message = messageObj;
}
void ErrorResponse::setCode(const int& codeObj)
{
code = codeObj;
}
void ErrorResponse::setDetails(const std::vector<std::string>& detailsObj)
{
details = detailsObj;
}
} // namespace models

View File

@@ -0,0 +1,47 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <cstdint>
#include <string>
#include <vector>
namespace models {
class ErrorResponse
{
public:
ErrorResponse();
virtual ~ErrorResponse() = default;
// Getters and setters
[[nodiscard]] std::string getMessage() const;
void setMessage(const std::string& message);
[[nodiscard]] int getCode() const;
void setCode(const int& code);
[[nodiscard]] std::vector<std::string> getDetails() const;
void setDetails(const std::vector<std::string>& details);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(ErrorResponse,
message, code, details)
private:
std::string message;
int code;
std::vector<std::string> details;
};
} // namespace models

View File

@@ -0,0 +1,49 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "NotFoundResponse.h"
namespace models {
NotFoundResponse::NotFoundResponse()
: error("")
, resource("")
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string NotFoundResponse::getError() const
{
return error;
}
std::string NotFoundResponse::getResource() const
{
return resource;
}
// ===================
// ===== Setters =====
// ===================
void NotFoundResponse::setError(const std::string& errorObj)
{
error = errorObj;
}
void NotFoundResponse::setResource(const std::string& resourceObj)
{
resource = resourceObj;
}
} // namespace models

View File

@@ -0,0 +1,42 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <string>
namespace models {
class NotFoundResponse
{
public:
NotFoundResponse();
virtual ~NotFoundResponse() = default;
// Getters and setters
[[nodiscard]] std::string getError() const;
void setError(const std::string& error);
[[nodiscard]] std::string getResource() const;
void setResource(const std::string& resource);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(NotFoundResponse,
error, resource)
private:
std::string error;
std::string resource;
};
} // namespace models

View File

@@ -0,0 +1,76 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "NullableOptionalTypes.h"
namespace models {
NullableOptionalTypes::NullableOptionalTypes()
: requiredField("")
, optionalField("")
, nullableField("")
, optionalNullableField("")
, fieldWithDefault(42)
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string NullableOptionalTypes::getRequiredField() const
{
return requiredField;
}
std::string NullableOptionalTypes::getOptionalField() const
{
return optionalField;
}
std::string NullableOptionalTypes::getNullableField() const
{
return nullableField;
}
std::string NullableOptionalTypes::getOptionalNullableField() const
{
return optionalNullableField;
}
int NullableOptionalTypes::getFieldWithDefault() const
{
return fieldWithDefault;
}
// ===================
// ===== Setters =====
// ===================
void NullableOptionalTypes::setRequiredField(const std::string& requiredFieldObj)
{
requiredField = requiredFieldObj;
}
void NullableOptionalTypes::setOptionalField(const std::string& optionalFieldObj)
{
optionalField = optionalFieldObj;
}
void NullableOptionalTypes::setNullableField(const std::string& nullableFieldObj)
{
nullableField = nullableFieldObj;
}
void NullableOptionalTypes::setOptionalNullableField(const std::string& optionalNullableFieldObj)
{
optionalNullableField = optionalNullableFieldObj;
}
void NullableOptionalTypes::setFieldWithDefault(const int& fieldWithDefaultObj)
{
fieldWithDefault = fieldWithDefaultObj;
}
} // namespace models

View File

@@ -0,0 +1,53 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <optional>
#include <cstdint>
#include <string>
namespace models {
class NullableOptionalTypes
{
public:
NullableOptionalTypes();
virtual ~NullableOptionalTypes() = default;
// Getters and setters
[[nodiscard]] std::string getRequiredField() const;
void setRequiredField(const std::string& requiredField);
[[nodiscard]] std::string getOptionalField() const;
void setOptionalField(const std::string& optionalField);
[[nodiscard]] std::string getNullableField() const;
void setNullableField(const std::string& nullableField);
[[nodiscard]] std::string getOptionalNullableField() const;
void setOptionalNullableField(const std::string& optionalNullableField);
[[nodiscard]] int getFieldWithDefault() const;
void setFieldWithDefault(const int& fieldWithDefault);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(NullableOptionalTypes,
requiredField, optionalField, nullableField, optionalNullableField, fieldWithDefault)
private:
std::string requiredField;
std::string optionalField;
std::string nullableField;
std::string optionalNullableField;
int fieldWithDefault;
};
} // namespace models

View File

@@ -0,0 +1,7 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/

View File

@@ -0,0 +1,48 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <variant>
#include <string>
#include "BankAccount.h"
#include "CreditCard.h"
namespace models {
// oneOf schema - type alias for std::variant
using PaymentMethod = std::variant<
CreditCard,
BankAccount>;
// JSON serialization functions (inline for header-only)
inline void from_json(const nlohmann::json& j, PaymentMethod& obj) {
if (!j.contains("paymentType")) {
throw nlohmann::json::type_error::create(302, "Discriminator property 'paymentType' not found in JSON", &j);
}
std::string discriminatorValue = j["paymentType"].get<std::string>();
if (discriminatorValue == "credit_card") {
obj = j.get<CreditCard>();
return;
}
if (discriminatorValue == "bank_account") {
obj = j.get<BankAccount>();
return;
}
throw nlohmann::json::type_error::create(302, "Unknown discriminator value: " + discriminatorValue, &j);
}
inline void to_json(nlohmann::json& j, const PaymentMethod& obj)
{
std::visit([&j](const auto& val) { j = nlohmann::json(val); }, obj);
}
} // namespace models

View File

@@ -0,0 +1,130 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "PrimitiveTypes.h"
namespace models {
PrimitiveTypes::PrimitiveTypes()
: stringField("")
, intField(0)
, longField(0)
, floatField(0.0f)
, doubleField(0.0)
, boolField(false)
, byteField(std::vector<uint8_t>())
, binaryField("")
, dateField("")
, dateTimeField("")
, passwordField("")
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string PrimitiveTypes::getStringField() const
{
return stringField;
}
int PrimitiveTypes::getIntField() const
{
return intField;
}
long PrimitiveTypes::getLongField() const
{
return longField;
}
float PrimitiveTypes::getFloatField() const
{
return floatField;
}
double PrimitiveTypes::getDoubleField() const
{
return doubleField;
}
bool PrimitiveTypes::isBoolField() const
{
return boolField;
}
std::vector<uint8_t> PrimitiveTypes::getByteField() const
{
return byteField;
}
std::string PrimitiveTypes::getBinaryField() const
{
return binaryField;
}
std::string PrimitiveTypes::getDateField() const
{
return dateField;
}
std::string PrimitiveTypes::getDateTimeField() const
{
return dateTimeField;
}
std::string PrimitiveTypes::getPasswordField() const
{
return passwordField;
}
// ===================
// ===== Setters =====
// ===================
void PrimitiveTypes::setStringField(const std::string& stringFieldObj)
{
stringField = stringFieldObj;
}
void PrimitiveTypes::setIntField(const int& intFieldObj)
{
intField = intFieldObj;
}
void PrimitiveTypes::setLongField(const long& longFieldObj)
{
longField = longFieldObj;
}
void PrimitiveTypes::setFloatField(const float& floatFieldObj)
{
floatField = floatFieldObj;
}
void PrimitiveTypes::setDoubleField(const double& doubleFieldObj)
{
doubleField = doubleFieldObj;
}
void PrimitiveTypes::setBoolField(const bool& boolFieldObj)
{
boolField = boolFieldObj;
}
void PrimitiveTypes::setByteField(const std::vector<uint8_t>& byteFieldObj)
{
byteField = byteFieldObj;
}
void PrimitiveTypes::setBinaryField(const std::string& binaryFieldObj)
{
binaryField = binaryFieldObj;
}
void PrimitiveTypes::setDateField(const std::string& dateFieldObj)
{
dateField = dateFieldObj;
}
void PrimitiveTypes::setDateTimeField(const std::string& dateTimeFieldObj)
{
dateTimeField = dateTimeFieldObj;
}
void PrimitiveTypes::setPasswordField(const std::string& passwordFieldObj)
{
passwordField = passwordFieldObj;
}
} // namespace models

View File

@@ -0,0 +1,70 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <cstdint>
#include <string>
namespace models {
class PrimitiveTypes
{
public:
PrimitiveTypes();
virtual ~PrimitiveTypes() = default;
// Getters and setters
[[nodiscard]] std::string getStringField() const;
void setStringField(const std::string& stringField);
[[nodiscard]] int getIntField() const;
void setIntField(const int& intField);
[[nodiscard]] long getLongField() const;
void setLongField(const long& longField);
[[nodiscard]] float getFloatField() const;
void setFloatField(const float& floatField);
[[nodiscard]] double getDoubleField() const;
void setDoubleField(const double& doubleField);
[[nodiscard]] bool isBoolField() const;
void setBoolField(const bool& boolField);
[[nodiscard]] std::vector<uint8_t> getByteField() const;
void setByteField(const std::vector<uint8_t>& byteField);
[[nodiscard]] std::string getBinaryField() const;
void setBinaryField(const std::string& binaryField);
[[nodiscard]] std::string getDateField() const;
void setDateField(const std::string& dateField);
[[nodiscard]] std::string getDateTimeField() const;
void setDateTimeField(const std::string& dateTimeField);
[[nodiscard]] std::string getPasswordField() const;
void setPasswordField(const std::string& passwordField);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(PrimitiveTypes,
stringField, intField, longField, floatField, doubleField, boolField, byteField, binaryField, dateField, dateTimeField, passwordField)
private:
std::string stringField;
int intField;
long longField;
float floatField;
double doubleField;
bool boolField;
std::vector<uint8_t> byteField;
std::string binaryField;
std::string dateField;
std::string dateTimeField;
std::string passwordField;
};
} // namespace models

View File

@@ -0,0 +1,58 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "SimpleObject.h"
namespace models {
SimpleObject::SimpleObject()
: id(0)
, name("")
, description("")
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
int SimpleObject::getId() const
{
return id;
}
std::string SimpleObject::getName() const
{
return name;
}
std::string SimpleObject::getDescription() const
{
return description;
}
// ===================
// ===== Setters =====
// ===================
void SimpleObject::setId(const int& idObj)
{
id = idObj;
}
void SimpleObject::setName(const std::string& nameObj)
{
name = nameObj;
}
void SimpleObject::setDescription(const std::string& descriptionObj)
{
description = descriptionObj;
}
} // namespace models

View File

@@ -0,0 +1,46 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <cstdint>
#include <string>
namespace models {
class SimpleObject
{
public:
SimpleObject();
virtual ~SimpleObject() = default;
// Getters and setters
[[nodiscard]] int getId() const;
void setId(const int& id);
[[nodiscard]] std::string getName() const;
void setName(const std::string& name);
[[nodiscard]] std::string getDescription() const;
void setDescription(const std::string& description);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(SimpleObject,
id, name, description)
private:
int id;
std::string name;
std::string description;
};
} // namespace models

View File

@@ -0,0 +1,7 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/

View File

@@ -0,0 +1,52 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <variant>
namespace models {
// anyOf schema - type alias for std::variant
using StringOrNumber = std::variant<
std::string,
double >;
// JSON serialization functions (inline for header-only)
inline void from_json(const nlohmann::json& j, StringOrNumber& obj)
{
try
{
obj = j.get<std::string>();
return;
}
catch (const nlohmann::json::exception&)
{
// Type mismatch, try next variant alternative
}
try
{
obj = j.get<double>();
return;
}
catch (const nlohmann::json::exception&)
{
// Type mismatch, try next variant alternative
}
throw nlohmann::json::type_error::create(302, "Could not deserialize into any variant type of StringOrNumber", &j);
}
inline void to_json(nlohmann::json& j, const StringOrNumber& obj)
{
std::visit([&j](const auto& val) { j = nlohmann::json(val); }, obj);
}
} // namespace models

View File

@@ -0,0 +1,48 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "SuccessResponse.h"
namespace models {
SuccessResponse::SuccessResponse()
: status("")
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string SuccessResponse::getStatus() const
{
return status;
}
nlohmann::json SuccessResponse::getData() const
{
return data;
}
// ===================
// ===== Setters =====
// ===================
void SuccessResponse::setStatus(const std::string& statusObj)
{
status = statusObj;
}
void SuccessResponse::setData(const nlohmann::json& dataObj)
{
data = dataObj;
}
} // namespace models

View File

@@ -0,0 +1,42 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <string>
namespace models {
class SuccessResponse
{
public:
SuccessResponse();
virtual ~SuccessResponse() = default;
// Getters and setters
[[nodiscard]] std::string getStatus() const;
void setStatus(const std::string& status);
[[nodiscard]] nlohmann::json getData() const;
void setData(const nlohmann::json& data);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(SuccessResponse,
status, data)
private:
std::string status;
nlohmann::json data;
};
} // namespace models

View File

@@ -0,0 +1,67 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "TestAllParameterTypes200Response.h"
namespace models {
TestAllParameterTypes200Response::TestAllParameterTypes200Response()
: message("")
, resourceId(0)
, filter("")
, correlationId("")
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string TestAllParameterTypes200Response::getMessage() const
{
return message;
}
int TestAllParameterTypes200Response::getResourceId() const
{
return resourceId;
}
std::string TestAllParameterTypes200Response::getFilter() const
{
return filter;
}
std::string TestAllParameterTypes200Response::getCorrelationId() const
{
return correlationId;
}
// ===================
// ===== Setters =====
// ===================
void TestAllParameterTypes200Response::setMessage(const std::string& messageObj)
{
message = messageObj;
}
void TestAllParameterTypes200Response::setResourceId(const int& resourceIdObj)
{
resourceId = resourceIdObj;
}
void TestAllParameterTypes200Response::setFilter(const std::string& filterObj)
{
filter = filterObj;
}
void TestAllParameterTypes200Response::setCorrelationId(const std::string& correlationIdObj)
{
correlationId = correlationIdObj;
}
} // namespace models

View File

@@ -0,0 +1,49 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <cstdint>
#include <string>
namespace models {
class TestAllParameterTypes200Response
{
public:
TestAllParameterTypes200Response();
virtual ~TestAllParameterTypes200Response() = default;
// Getters and setters
[[nodiscard]] std::string getMessage() const;
void setMessage(const std::string& message);
[[nodiscard]] int getResourceId() const;
void setResourceId(const int& resourceId);
[[nodiscard]] std::string getFilter() const;
void setFilter(const std::string& filter);
[[nodiscard]] std::string getCorrelationId() const;
void setCorrelationId(const std::string& correlationId);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(TestAllParameterTypes200Response,
message, resourceId, filter, correlationId)
private:
std::string message;
int resourceId;
std::string filter;
std::string correlationId;
};
} // namespace models

View File

@@ -0,0 +1,40 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "TestApiKeySecurity200Response.h"
namespace models {
TestApiKeySecurity200Response::TestApiKeySecurity200Response()
: message("")
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string TestApiKeySecurity200Response::getMessage() const
{
return message;
}
// ===================
// ===== Setters =====
// ===================
void TestApiKeySecurity200Response::setMessage(const std::string& messageObj)
{
message = messageObj;
}
} // namespace models

View File

@@ -0,0 +1,39 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <string>
namespace models {
class TestApiKeySecurity200Response
{
public:
TestApiKeySecurity200Response();
virtual ~TestApiKeySecurity200Response() = default;
// Getters and setters
[[nodiscard]] std::string getMessage() const;
void setMessage(const std::string& message);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(TestApiKeySecurity200Response,
message)
private:
std::string message;
};
} // namespace models

View File

@@ -0,0 +1,40 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "TestBasicSecurity200Response.h"
namespace models {
TestBasicSecurity200Response::TestBasicSecurity200Response()
: message("")
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string TestBasicSecurity200Response::getMessage() const
{
return message;
}
// ===================
// ===== Setters =====
// ===================
void TestBasicSecurity200Response::setMessage(const std::string& messageObj)
{
message = messageObj;
}
} // namespace models

View File

@@ -0,0 +1,39 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <string>
namespace models {
class TestBasicSecurity200Response
{
public:
TestBasicSecurity200Response();
virtual ~TestBasicSecurity200Response() = default;
// Getters and setters
[[nodiscard]] std::string getMessage() const;
void setMessage(const std::string& message);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(TestBasicSecurity200Response,
message)
private:
std::string message;
};
} // namespace models

View File

@@ -0,0 +1,40 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "TestBearerSecurity200Response.h"
namespace models {
TestBearerSecurity200Response::TestBearerSecurity200Response()
: message("")
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string TestBearerSecurity200Response::getMessage() const
{
return message;
}
// ===================
// ===== Setters =====
// ===================
void TestBearerSecurity200Response::setMessage(const std::string& messageObj)
{
message = messageObj;
}
} // namespace models

View File

@@ -0,0 +1,39 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <string>
namespace models {
class TestBearerSecurity200Response
{
public:
TestBearerSecurity200Response();
virtual ~TestBearerSecurity200Response() = default;
// Getters and setters
[[nodiscard]] std::string getMessage() const;
void setMessage(const std::string& message);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(TestBearerSecurity200Response,
message)
private:
std::string message;
};
} // namespace models

View File

@@ -0,0 +1,40 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "TestCookieParameters200Response.h"
namespace models {
TestCookieParameters200Response::TestCookieParameters200Response()
: message("")
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string TestCookieParameters200Response::getMessage() const
{
return message;
}
// ===================
// ===== Setters =====
// ===================
void TestCookieParameters200Response::setMessage(const std::string& messageObj)
{
message = messageObj;
}
} // namespace models

View File

@@ -0,0 +1,39 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <string>
namespace models {
class TestCookieParameters200Response
{
public:
TestCookieParameters200Response();
virtual ~TestCookieParameters200Response() = default;
// Getters and setters
[[nodiscard]] std::string getMessage() const;
void setMessage(const std::string& message);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(TestCookieParameters200Response,
message)
private:
std::string message;
};
} // namespace models

View File

@@ -0,0 +1,40 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "TestHeaderParameters200Response.h"
namespace models {
TestHeaderParameters200Response::TestHeaderParameters200Response()
: message("")
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string TestHeaderParameters200Response::getMessage() const
{
return message;
}
// ===================
// ===== Setters =====
// ===================
void TestHeaderParameters200Response::setMessage(const std::string& messageObj)
{
message = messageObj;
}
} // namespace models

View File

@@ -0,0 +1,39 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <string>
namespace models {
class TestHeaderParameters200Response
{
public:
TestHeaderParameters200Response();
virtual ~TestHeaderParameters200Response() = default;
// Getters and setters
[[nodiscard]] std::string getMessage() const;
void setMessage(const std::string& message);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(TestHeaderParameters200Response,
message)
private:
std::string message;
};
} // namespace models

View File

@@ -0,0 +1,40 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "TestHeaderParameters401Response.h"
namespace models {
TestHeaderParameters401Response::TestHeaderParameters401Response()
: message("")
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string TestHeaderParameters401Response::getMessage() const
{
return message;
}
// ===================
// ===== Setters =====
// ===================
void TestHeaderParameters401Response::setMessage(const std::string& messageObj)
{
message = messageObj;
}
} // namespace models

View File

@@ -0,0 +1,39 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <string>
namespace models {
class TestHeaderParameters401Response
{
public:
TestHeaderParameters401Response();
virtual ~TestHeaderParameters401Response() = default;
// Getters and setters
[[nodiscard]] std::string getMessage() const;
void setMessage(const std::string& message);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(TestHeaderParameters401Response,
message)
private:
std::string message;
};
} // namespace models

View File

@@ -0,0 +1,40 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "TestOAuth2Security200Response.h"
namespace models {
TestOAuth2Security200Response::TestOAuth2Security200Response()
: message("")
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string TestOAuth2Security200Response::getMessage() const
{
return message;
}
// ===================
// ===== Setters =====
// ===================
void TestOAuth2Security200Response::setMessage(const std::string& messageObj)
{
message = messageObj;
}
} // namespace models

View File

@@ -0,0 +1,39 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <string>
namespace models {
class TestOAuth2Security200Response
{
public:
TestOAuth2Security200Response();
virtual ~TestOAuth2Security200Response() = default;
// Getters and setters
[[nodiscard]] std::string getMessage() const;
void setMessage(const std::string& message);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(TestOAuth2Security200Response,
message)
private:
std::string message;
};
} // namespace models

View File

@@ -0,0 +1,40 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "TestQueryParameters200Response.h"
namespace models {
TestQueryParameters200Response::TestQueryParameters200Response()
: message("")
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string TestQueryParameters200Response::getMessage() const
{
return message;
}
// ===================
// ===== Setters =====
// ===================
void TestQueryParameters200Response::setMessage(const std::string& messageObj)
{
message = messageObj;
}
} // namespace models

View File

@@ -0,0 +1,39 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <string>
namespace models {
class TestQueryParameters200Response
{
public:
TestQueryParameters200Response();
virtual ~TestQueryParameters200Response() = default;
// Getters and setters
[[nodiscard]] std::string getMessage() const;
void setMessage(const std::string& message);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(TestQueryParameters200Response,
message)
private:
std::string message;
};
} // namespace models

View File

@@ -0,0 +1,49 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "TestQueryParametersDeepObjectParameter.h"
namespace models {
TestQueryParametersDeepObjectParameter::TestQueryParametersDeepObjectParameter()
: name("")
, age(0)
{
}
// =========================================
// ===== Getters/Setters =====
// =========================================
// ===================
// ===== Getters =====
// ===================
std::string TestQueryParametersDeepObjectParameter::getName() const
{
return name;
}
int TestQueryParametersDeepObjectParameter::getAge() const
{
return age;
}
// ===================
// ===== Setters =====
// ===================
void TestQueryParametersDeepObjectParameter::setName(const std::string& nameObj)
{
name = nameObj;
}
void TestQueryParametersDeepObjectParameter::setAge(const int& ageObj)
{
age = ageObj;
}
} // namespace models

View File

@@ -0,0 +1,43 @@
/**
* This file is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#pragma once
// System headers
#include <nlohmann/json.hpp>
#include <cstdint>
#include <string>
namespace models {
class TestQueryParametersDeepObjectParameter
{
public:
TestQueryParametersDeepObjectParameter();
virtual ~TestQueryParametersDeepObjectParameter() = default;
// Getters and setters
[[nodiscard]] std::string getName() const;
void setName(const std::string& name);
[[nodiscard]] int getAge() const;
void setAge(const int& age);
// JSON serialization using NLOHMANN INTRUSIVE macro (must be inside class to access private members)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(TestQueryParametersDeepObjectParameter,
name, age)
private:
std::string name;
int age;
};
} // namespace models

View File

@@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@@ -0,0 +1,31 @@
CMakeLists.txt
LICENSE
README.md
api/PetApi.cpp
api/PetApi.h
api/StoreApi.cpp
api/StoreApi.h
api/UserApi.cpp
api/UserApi.h
models/ApiResponse.cpp
models/ApiResponse.h
models/Category.cpp
models/Category.h
models/ComplexParamsResponse.cpp
models/ComplexParamsResponse.h
models/DeepObj.cpp
models/DeepObj.h
models/DeepObjBaz.cpp
models/DeepObjBaz.h
models/NullableExample.cpp
models/NullableExample.h
models/Order.cpp
models/Order.h
models/Pet.cpp
models/Pet.h
models/PetOrCategory.cpp
models/PetOrCategory.h
models/Tag.cpp
models/Tag.h
models/User.cpp
models/User.h

View File

@@ -0,0 +1 @@
7.16.0-SNAPSHOT

Some files were not shown because too many files have changed in this diff Show More