AnCH Framework 0.2
Another C++ Hack: C++23 utility libraries
Loading...
Searching...
No Matches
anch::rest Namespace Reference

AnCH REST library namespace. More...

Namespaces

namespace  header
 Common HTTP header names.
namespace  nginx
 nginx applications bridge (see ANCH_REST_APPLICATION ).

Classes

class  Api
class  Body
struct  BodyStream
class  Call
struct  CaseInsensitiveLess
class  Client
struct  CorsOptions
class  CurlTransport
class  Endpoint
class  Form
struct  FormLimits
struct  FormMapper
struct  FormUrlEncoded
class  GrpcServer
class  Headers
class  HttpError
class  HttpException
struct  Multipart
struct  ParamConverter
struct  ParamConverter< anch::UUID >
struct  ParamConverter< bool >
struct  ParamConverter< std::string >
struct  ParamConverter< T >
class  Part
struct  RawBody
class  Request
class  Response
class  Route
class  RpcContext
class  RpcError
class  RpcService
class  ThriftTransport
class  Transport
struct  TransportConfig
class  TransportError

Concepts

concept  FormMapped
concept  ParameterValue
concept  PathParameter

Typedefs

using Next = std::function<anch::rest::Response(anch::rest::Request&)>
using Filter = std::function<anch::rest::Response(anch::rest::Request&, const anch::rest::Next&)>
using BodyWriter = std::function<void(std::ostream&)>

Enumerations

enum class  Method {
  GET , HEAD , POST , PUT ,
  DELETE , CONNECT , OPTIONS , TRACE ,
  PATCH
}
enum class  Status : uint16_t {
  CONTINUE = 100 , SWITCHING_PROTOCOLS = 101 , PROCESSING = 102 , EARLY_HINTS = 103 ,
  OK = 200 , CREATED = 201 , ACCEPTED = 202 , NON_AUTHORITATIVE_INFORMATION = 203 ,
  NO_CONTENT = 204 , RESET_CONTENT = 205 , PARTIAL_CONTENT = 206 , MULTI_STATUS = 207 ,
  ALREADY_REPORTED = 208 , IM_USED = 226 , MULTIPLE_CHOICES = 300 , MOVED_PERMANENTLY = 301 ,
  FOUND = 302 , SEE_OTHER = 303 , NOT_MODIFIED = 304 , TEMPORARY_REDIRECT = 307 ,
  PERMANENT_REDIRECT = 308 , BAD_REQUEST = 400 , UNAUTHORIZED = 401 , PAYMENT_REQUIRED = 402 ,
  FORBIDDEN = 403 , NOT_FOUND = 404 , METHOD_NOT_ALLOWED = 405 , NOT_ACCEPTABLE = 406 ,
  PROXY_AUTHENTICATION_REQUIRED = 407 , REQUEST_TIMEOUT = 408 , CONFLICT = 409 , GONE = 410 ,
  LENGTH_REQUIRED = 411 , PRECONDITION_FAILED = 412 , CONTENT_TOO_LARGE = 413 , URI_TOO_LONG = 414 ,
  UNSUPPORTED_MEDIA_TYPE = 415 , RANGE_NOT_SATISFIABLE = 416 , EXPECTATION_FAILED = 417 , IM_A_TEAPOT = 418 ,
  MISDIRECTED_REQUEST = 421 , UNPROCESSABLE_CONTENT = 422 , LOCKED = 423 , FAILED_DEPENDENCY = 424 ,
  TOO_EARLY = 425 , UPGRADE_REQUIRED = 426 , PRECONDITION_REQUIRED = 428 , TOO_MANY_REQUESTS = 429 ,
  REQUEST_HEADER_FIELDS_TOO_LARGE = 431 , UNAVAILABLE_FOR_LEGAL_REASONS = 451 , INTERNAL_SERVER_ERROR = 500 , NOT_IMPLEMENTED = 501 ,
  BAD_GATEWAY = 502 , SERVICE_UNAVAILABLE = 503 , GATEWAY_TIMEOUT = 504 , HTTP_VERSION_NOT_SUPPORTED = 505 ,
  VARIANT_ALSO_NEGOTIATES = 506 , INSUFFICIENT_STORAGE = 507 , LOOP_DETECTED = 508 , NETWORK_AUTHENTICATION_REQUIRED = 511
}
enum class  RpcCode : uint8_t {
  OK = 0 , CANCELLED = 1 , UNKNOWN = 2 , INVALID_ARGUMENT = 3 ,
  DEADLINE_EXCEEDED = 4 , NOT_FOUND = 5 , ALREADY_EXISTS = 6 , PERMISSION_DENIED = 7 ,
  RESOURCE_EXHAUSTED = 8 , FAILED_PRECONDITION = 9 , ABORTED = 10 , OUT_OF_RANGE = 11 ,
  UNIMPLEMENTED = 12 , INTERNAL = 13 , UNAVAILABLE = 14 , DATA_LOSS = 15 ,
  UNAUTHENTICATED = 16
}
enum class  RpcFormat { BINARY , JSON }

Functions

anch::rest::Filter basicAuth (std::string_view user, std::string_view password)
anch::rest::Filter bearerAuth (std::string_view token)
std::string base64Encode (std::string_view value)
template<anch::rest::ParameterValue T>
void addFormField (anch::rest::Form &form, std::string_view name, const T &value)
template<anch::rest::ParameterValue T>
void addFormField (anch::rest::Form &form, std::string_view name, const std::optional< T > &value)
template<anch::rest::ParameterValue T>
void addFormField (anch::rest::Form &form, std::string_view name, const std::vector< T > &values)
void addFormFile (anch::rest::Form &form, std::string_view name, const anch::rest::Part &part)
void addFormFile (anch::rest::Form &form, std::string_view name, const std::optional< anch::rest::Part > &part)
void addFormFile (anch::rest::Form &form, std::string_view name, const std::vector< anch::rest::Part > &parts)
template<typename T>
void addJsonFormField (anch::rest::Form &form, std::string_view name, const T &value, anch::codec::Side side)
template<anch::rest::PathParameter T>
std::vector< T > formFields (const anch::rest::Form &form, std::string_view name)
std::optional< anch::rest::Part > formFile (const anch::rest::Form &form, std::string_view name)
anch::rest::Part requiredFormFile (const anch::rest::Form &form, std::string_view name)
std::vector< anch::rest::Part > formFiles (const anch::rest::Form &form, std::string_view name)
template<typename T>
std::optional< T > jsonFormField (const anch::rest::Form &form, std::string_view name, anch::codec::Side side)
template<typename T>
T requiredJsonFormField (const anch::rest::Form &form, std::string_view name, anch::codec::Side side)
template<typename T>
void checkFormConstraints (const T &value, anch::codec::Side side)
std::string_view toString (anch::rest::Method method) noexcept
std::optional< anch::rest::Method > parseMethod (std::string_view name) noexcept
template<anch::rest::PathParameter T>
std::optional< T > queryParameter (const anch::rest::Request &request, std::string_view name)
template<anch::rest::PathParameter T>
T requiredQueryParameter (const anch::rest::Request &request, std::string_view name)
template<anch::rest::PathParameter T>
std::optional< T > formField (const anch::rest::Form &form, std::string_view name)
template<anch::rest::PathParameter T>
T requiredFormField (const anch::rest::Form &form, std::string_view name)
template<anch::rest::ParameterValue T>
std::string toParameterString (const T &value)
std::optional< std::string > percentDecode (std::string_view value, bool plusAsSpace=false)
std::string percentEncode (std::string_view value)
constexpr uint16_t code (anch::rest::Status status) noexcept
std::string_view reasonPhrase (anch::rest::Status status) noexcept
void installRpc (anch::rest::Api &api, const anch::rest::RpcService &service, std::string_view prefix=std::string_view())
template<anch::codec::ProtobufMessage Res, anch::codec::ProtobufMessage Req>
Res callRpc (anch::rest::Client &client, std::string_view service, std::string_view method, const Req &request, anch::rest::RpcFormat format=anch::rest::RpcFormat::BINARY)
void installThrift (anch::rest::Api &api, std::string_view path, std::shared_ptr< apache::thrift::TProcessor > processor, std::size_t maxMessageSize=16 *1024 *1024)

Detailed Description

AnCH REST library namespace.

It contains the HTTP model (Request, Response, ...), HTTP codecs (forms, multipart ; other codecs are in anch::codec ), the server API declaration (Api) and the HTTP client (Client). See AnCH REST library documentation.

Typedef Documentation

◆ BodyWriter

using anch::rest::BodyWriter = std::function<void(std::ostream&)>

Response body writer: it is called by the server adapter to write the body

◆ Filter

Filter: executed around endpoints (server) or requests (client), it can change the request or the response, or answer itself without calling next

◆ Next

Next step of a filter chain (next filter, then endpoint on server side or transport on client side)

Enumeration Type Documentation

◆ Method

enum class anch::rest::Method
strong

HTTP request methods

Author
Vincent Lachenal
Since
0.2
Enumerator
GET 

GET method

HEAD 

HEAD method

POST 

POST method

PUT 

PUT method

DELETE 

DELETE method

CONNECT 

CONNECT method

OPTIONS 

OPTIONS method

TRACE 

TRACE method

PATCH 

PATCH method

◆ RpcCode

enum class anch::rest::RpcCode : uint8_t
strong

RPC status codes (gRPC codes, shared by gRPC, gRPC-Web and Connect protocols)

Since
0.2
Enumerator
OK 

Success

CANCELLED 

Call cancelled

UNKNOWN 

Unknown error

INVALID_ARGUMENT 

Invalid argument

DEADLINE_EXCEEDED 

Deadline exceeded

NOT_FOUND 

Not found

ALREADY_EXISTS 

Already exists

PERMISSION_DENIED 

Permission denied

RESOURCE_EXHAUSTED 

Resource exhausted

FAILED_PRECONDITION 

Failed precondition

ABORTED 

Aborted

OUT_OF_RANGE 

Out of range

UNIMPLEMENTED 

Not implemented

INTERNAL 

Internal error

UNAVAILABLE 

Unavailable

DATA_LOSS 

Data loss

UNAUTHENTICATED 

Not authenticated

◆ RpcFormat

enum class anch::rest::RpcFormat
strong

Messages encoding of an RPC call

Since
0.2
Enumerator
BINARY 

Protocol Buffers binary encoding

JSON 

Protocol Buffers JSON mapping

◆ Status

enum class anch::rest::Status : uint16_t
strong

HTTP response status codes

Author
Vincent Lachenal
Since
0.2

Function Documentation

◆ addFormField() [1/3]

void anch::rest::addFormField ( anch::rest::Form & form,
std::string_view name,
const std::optional< T > & value )

Add field when value is set

Parameters
formthe form
namethe field name
valuethe value
Since
0.2
Here is the call graph for this function:

◆ addFormField() [2/3]

void anch::rest::addFormField ( anch::rest::Form & form,
std::string_view name,
const std::vector< T > & values )

Add one field per value (repeated name)

Parameters
formthe form
namethe field name
valuesthe values
Since
0.2
Here is the call graph for this function:

◆ addFormField() [3/3]

void anch::rest::addFormField ( anch::rest::Form & form,
std::string_view name,
const T & value )

Add field formatted with toParameterString

Parameters
formthe form
namethe field name
valuethe value
Since
0.2
Here is the call graph for this function:

◆ addFormFile() [1/3]

void anch::rest::addFormFile ( anch::rest::Form & form,
std::string_view name,
const anch::rest::Part & part )

Add part (file) with name

Parameters
formthe form
namethe part name (replaces the part one)
partthe part
Since
0.2
Here is the call graph for this function:

◆ addFormFile() [2/3]

void anch::rest::addFormFile ( anch::rest::Form & form,
std::string_view name,
const std::optional< anch::rest::Part > & part )

Add part (file) with name when it is set

Parameters
formthe form
namethe part name
partthe part
Since
0.2
Here is the call graph for this function:

◆ addFormFile() [3/3]

void anch::rest::addFormFile ( anch::rest::Form & form,
std::string_view name,
const std::vector< anch::rest::Part > & parts )

Add parts (files) with name

Parameters
formthe form
namethe parts name
partsthe parts
Since
0.2
Here is the call graph for this function:

◆ addJsonFormField()

template<typename T>
void anch::rest::addJsonFormField ( anch::rest::Form & form,
std::string_view name,
const T & value,
anch::codec::Side side )

Add application/json part serialized with anch::codec::Json codec (constraints checked according to side)

Parameters
formthe form
namethe part name
valuethe value
sidethe side which writes form
Since
0.2
Here is the call graph for this function:

◆ base64Encode()

std::string anch::rest::base64Encode ( std::string_view value)

Base64 encoding (RFC 4648, with padding)

Parameters
valuethe value to encode
Returns
the encoded value
Since
0.2
Here is the call graph for this function:

◆ basicAuth()

anch::rest::Filter anch::rest::basicAuth ( std::string_view user,
std::string_view password )

HTTP Basic authentication filter: sets Authorization header

Parameters
userthe user
passwordthe password
Returns
the filter
Since
0.2
Here is the call graph for this function:

◆ bearerAuth()

anch::rest::Filter anch::rest::bearerAuth ( std::string_view token)

Bearer token authentication filter: sets Authorization header

Parameters
tokenthe token
Returns
the filter
Since
0.2
Here is the call graph for this function:

◆ callRpc()

Res anch::rest::callRpc ( anch::rest::Client & client,
std::string_view service,
std::string_view method,
const Req & request,
anch::rest::RpcFormat format = anch::rest::RpcFormat::BINARY )

Call RPC method with Connect protocol (unary call, header only: link anch::rest-client ): POST /package.Service/Method on client base URL. The server can be an anch-rest API ( installRpc ) or any Connect server.

pets::GetPetRequest request;
request.set_id(1);
pets::Pet pet = anch::rest::callRpc<pets::Pet>(client, "pets.PetStore", "GetPet", request); // Connect client: rest/rpcClient.hpp
Template Parameters
Resthe response message type
Reqthe request message type
Parameters
clientthe anch-rest client
servicethe service full name ( package.Service )
methodthe method name
requestthe request message
formatthe messages encoding ( application/proto or application/json )
Returns
the response message
Exceptions
RpcErroron error response (Connect error code and message) or invalid response message
TransportErroron network error
Since
0.2
Here is the call graph for this function:

◆ checkFormConstraints()

template<typename T>
void anch::rest::checkFormConstraints ( const T & value,
anch::codec::Side side )

Check anch-json constraints of a value read from a form on server side ( anch::codec::Json codec checks request bodies, form mappers do the same with this function). Nothing is checked on client side.

Parameters
valuethe value
sidethe side which reads value
Exceptions
std::invalid_argumentwith the first violation ( "/name: ..." ) on server side
Since
0.2
Here is the call graph for this function:

◆ code()

uint16_t anch::rest::code ( anch::rest::Status status)
constexprnoexcept

Get status numeric code

Parameters
statusthe status
Returns
the code (200 , ...)
Here is the call graph for this function:

◆ formField()

std::optional< T > anch::rest::formField ( const anch::rest::Form & form,
std::string_view name )

Optional form field converted with ParamConverter (first part with this name)

Template Parameters
Tthe field type
Parameters
formthe form
namethe field name
Returns
the field value, empty when the field is absent
Exceptions
anch::rest::HttpException400 when value is invalid
Since
0.2
Here is the call graph for this function:

◆ formFields()

std::vector< T > anch::rest::formFields ( const anch::rest::Form & form,
std::string_view name )

Get every field converted with ParamConverter

Parameters
formthe form
namethe field name
Returns
the values, in order
Exceptions
HttpException400 when a value is invalid
Since
0.2
Here is the call graph for this function:

◆ formFile()

std::optional< anch::rest::Part > anch::rest::formFile ( const anch::rest::Form & form,
std::string_view name )

Get first part with name (file or field)

Parameters
formthe form
namethe part name
Returns
the part, empty when absent
Since
0.2
Here is the call graph for this function:

◆ formFiles()

std::vector< anch::rest::Part > anch::rest::formFiles ( const anch::rest::Form & form,
std::string_view name )

Get every part with name

Parameters
formthe form
namethe parts name
Returns
the parts, in order
Since
0.2
Here is the call graph for this function:

◆ installRpc()

void anch::rest::installRpc ( anch::rest::Api & api,
const anch::rest::RpcService & service,
std::string_view prefix = std::string_view() )

Install RPC service methods in API (header only: link anch::rest-server ): one POST [prefix]/package.Service/Method route per method, which serves:

  • Connect unary calls: application/proto (or application/x-protobuf ) and application/json bodies, 200 with the response message or Connect error ( {"code":"not_found","message":"..."} with the HTTP status of the code) ;
  • gRPC-Web unary calls: application/grpc-web , application/grpc-web+proto and application/grpc-web+json bodies (message frame), 200 with the response message frame and the trailers frame ( grpc-status , grpc-message ). Other content types are refused ( 415 ). Response metadata are HTTP headers. API filters and CORS apply (gRPC-Web browser clients need grpc-status and grpc-message exposed headers).
Parameters
apithe API
servicethe service (it has to outlive the API)
prefixthe routes prefix ( /rpc , empty by default)
Since
0.2
Here is the call graph for this function:

◆ installThrift()

void anch::rest::installThrift ( anch::rest::Api & api,
std::string_view path,
std::shared_ptr< apache::thrift::TProcessor > processor,
std::size_t maxMessageSize = 16 *1024 *1024 )

Install Thrift service in API (header only: link anch::rest-server ): POST path processes Thrift messages with the processor generated by thrift –gen cpp , as Thrift THttpServer . The protocol is chosen with the request Content-Type ( application/x-thrift and application/vnd.apache.thrift.binary , .compact , .json ), the response has the same content type. Declared exceptions and unknown methods are answered by the processor (Thrift application exceptions), unsupported content types with 415 , invalid messages with 400 .

auto handler = std::make_shared<PetStoreHandler>(); // implements generated PetStoreIf
anch::rest::installThrift(api, "/thrift/pets", std::make_shared<pets::PetStoreProcessor>(handler)); // rest/thriftRpc.hpp
Parameters
apithe API
paththe path pattern
processorthe Thrift processor
maxMessageSizethe maximum request message size (default: 16 MiB)
Since
0.2
Here is the call graph for this function:

◆ jsonFormField()

template<typename T>
std::optional< T > anch::rest::jsonFormField ( const anch::rest::Form & form,
std::string_view name,
anch::codec::Side side )

Get first part with name deserialized with anch::codec::Json codec (constraints checked according to side)

Parameters
formthe form
namethe part name
sidethe side which reads form
Returns
the value, empty when part is absent
Exceptions
anch::json::MappingErrorwhen part is not a valid JSON value
Since
0.2
Here is the call graph for this function:

◆ parseMethod()

std::optional< anch::rest::Method > anch::rest::parseMethod ( std::string_view name)
noexcept

Parse HTTP method name (case sensitive)

Parameters
namethe method name
Returns
the method, empty when the method is unknown
Here is the call graph for this function:

◆ percentDecode()

std::optional< std::string > anch::rest::percentDecode ( std::string_view value,
bool plusAsSpace = false )

Decode percent-encoded string

Parameters
valuethe value to decode
plusAsSpacedecode + as space (query strings)
Returns
the decoded value, empty when value is invalid
Here is the call graph for this function:

◆ percentEncode()

std::string anch::rest::percentEncode ( std::string_view value)

Percent-encode string (RFC 3986 unreserved characters are kept)

Parameters
valuethe value to encode
Returns
the encoded value
Here is the call graph for this function:

◆ queryParameter()

std::optional< T > anch::rest::queryParameter ( const anch::rest::Request & request,
std::string_view name )

Optional query parameter converted with ParamConverter

Template Parameters
Tthe parameter type
Parameters
requestthe request
namethe parameter name
Returns
the parameter value, empty when the parameter is absent
Exceptions
anch::rest::HttpException400 when value is invalid
Since
0.2
Here is the call graph for this function:

◆ reasonPhrase()

std::string_view anch::rest::reasonPhrase ( anch::rest::Status status)
noexcept

Get status reason phrase (RFC 9110)

Parameters
statusthe status
Returns
the reason phrase ("OK" , ...), empty for unknown status
Here is the call graph for this function:

◆ requiredFormField()

T anch::rest::requiredFormField ( const anch::rest::Form & form,
std::string_view name )

Required form field converted with ParamConverter (first part with this name)

Template Parameters
Tthe field type
Parameters
formthe form
namethe field name
Returns
the field value
Exceptions
anch::rest::HttpException400 when field is absent or its value is invalid
Since
0.2
Here is the call graph for this function:

◆ requiredFormFile()

anch::rest::Part anch::rest::requiredFormFile ( const anch::rest::Form & form,
std::string_view name )

Get first part with name (file or field)

Parameters
formthe form
namethe part name
Returns
the part
Exceptions
HttpException400 when part is absent
Since
0.2
Here is the call graph for this function:

◆ requiredJsonFormField()

template<typename T>
T anch::rest::requiredJsonFormField ( const anch::rest::Form & form,
std::string_view name,
anch::codec::Side side )

Get first part with name deserialized with anch::codec::Json codec (constraints checked according to side)

Parameters
formthe form
namethe part name
sidethe side which reads form
Returns
the value
Exceptions
HttpException400 when part is absent
anch::json::MappingErrorwhen part is not a valid JSON value
Since
0.2
Here is the call graph for this function:

◆ requiredQueryParameter()

T anch::rest::requiredQueryParameter ( const anch::rest::Request & request,
std::string_view name )

Required query parameter converted with ParamConverter

Template Parameters
Tthe parameter type
Parameters
requestthe request
namethe parameter name
Returns
the parameter value
Exceptions
anch::rest::HttpException400 when parameter is absent or its value is invalid
Since
0.2
Here is the call graph for this function:

◆ toParameterString()

std::string anch::rest::toParameterString ( const T & value)

Format parameter value

Parameters
valuethe value
Returns
the formatted value (not encoded)
Since
0.2
Here is the call graph for this function:

◆ toString()

std::string_view anch::rest::toString ( anch::rest::Method method)
noexcept

Get HTTP method name

Parameters
methodthe method
Returns
the method name ("GET" , ...)
Here is the call graph for this function: