userver: Chaotic clients
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
Chaotic clients

Chaotic is able to generate a http client from OpenAPI schema. You declare API of the endpoint in OpenAPI format and chaotic generates parsers, serializers and a client for you.

Quickstart

First, define OpenAPI schema in one or multiple yaml files.

openapi: 3.0.0
...

Second, declare the client in CMakeLists.txt:

userver_target_generate_openapi_client(
${PROJECT_NAME}-client-test_objs
NAME test
OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/client/test"
SCHEMAS ${CMAKE_CURRENT_SOURCE_DIR}/clients/test.yaml
)
target_link_libraries(${PROJECT_NAME}_objs ${PROJECT_NAME}-client-test_objs)

Third, register the client component in the component system:

int main(int argc, char* argv[]) {
...
.Append<::clients::test::Component>();

Fourth, get a reference to the client...

HelloHandler::HelloHandler(const components::ComponentConfig& config, const components::ComponentContext& context)
: server::handlers::HttpHandlerBase(config, context),
test_(context.FindComponent<::clients::test::Component>().GetClient()) {}

...and use it:

auto response = test_.TestGet({name});

Testing

If you test a service with testsuite, you mock the client.

Change client URL in conftest.py:

@pytest.fixture(scope='session')
def userver_config_client(mockserver_info):
def do_patch(config_yaml, config_vars):
components = config_yaml['components_manager']['components']
components['test-client']['base-url'] = mockserver_info.url('test')
return do_patch

Now you may mock the client with mockserver:

Extending the client

The client logic may be extended with middlewares. Middleware's code can be executed before the request is sent to the server and after it is processed.

Logging

If you want to log every in/out client body, use logging middleware in static config:

test-client:
middlewares:
logging:
request_level: info # log level to log request body
response_level: warning # log level to log response body
body_limit: 10000 # trim body to max size

Dynamic Quality-of-service configs (QOS)

Clients may fetch attempts and retries from dynamic config. Use qos-{client_name} middleware in static config (change "test-client" to your client name):

test-client:
middlewares:
qos-test-client: {}

And register it in main.cpp:

auto component_list =
userver::components::ComponentList()
.Append<userver::chaotic::openapi::QosMiddleware<clients::test_client::kQosConfig>>("chaotic-client-middleware-qos-test-client")

Proxy

HTTP proxy may be enabled using proxy middleware in static config:

test-client:
middlewares:
proxy:
url: my-proxy.org

HTTP Redirects

By default a client stops at the first redirect and interprets it as a response. If you want to follow redirects, use follow-redirects middleware:

test-client:
middlewares:
follow-redirects: {}