Skip to main content

Crate typeway

Crate typeway 

Source
Expand description

§Typeway — Type-Level Web Framework for Rust

Typeway is a web framework where your entire API is described as a Rust type. Servers, clients, and OpenAPI schemas are all derived from that single type definition. If the types compile, the pieces fit together.

Built on Tokio, Tower, and Hyper — fully compatible with the Axum ecosystem.

§Quick Start

use typeway::prelude::*;

// 1. Define path types
typeway_path!(type HelloPath = "hello");
typeway_path!(type GreetPath = "greet" / String);

// 2. Define the API as a type
type API = (
    GetEndpoint<HelloPath, String>,
    GetEndpoint<GreetPath, String>,
);

// 3. Write handlers
async fn hello() -> &'static str { "Hello, world!" }
async fn greet(path: Path<GreetPath>) -> String {
    let (name,) = path.0;
    format!("Hello, {name}!")
}

// 4. Serve — the compiler verifies every endpoint has a handler
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    Server::<API>::new((
        bind!(hello),
        bind!(greet),
    ))
    .serve("0.0.0.0:3000".parse()?)
    .await?;
    Ok(())
}

§Feature Flags

FlagDefaultDescription
serveryesHTTP server (Tower/Hyper)
clientnoType-safe HTTP client (reqwest)
openapinoOpenAPI 3.1 spec generation
fullnoAll features

Re-exports§

pub use http;
pub use serde;
pub use serde_json;
pub use typeway_server::tower_http;

Modules§

api
The ApiSpec trait — marks a type as a valid API specification.
docs
Handler documentation metadata for OpenAPI spec generation.
effects
Type-level middleware effects for compile-time enforcement.
endpoint
The Endpoint type — a type-level HTTP endpoint descriptor.
method
HTTP method types for type-level route encoding.
negotiate
Content negotiation type-level primitives.
path
Type-level path segment encoding using heterogeneous lists.
prelude
Convenience prelude — import everything you typically need.
session
Session type primitives for protocol-typed WebSocket channels.
versioning
Type-level API versioning with typed deltas and compile-time compatibility checks.

Macros§

assert_api_compatible
Verify at compile time that every endpoint in the old API exists in the new API (type equality on the full endpoint type).
bind
Convenience macro to bind a handler to an endpoint without turbofish.
endpoint
Defines an endpoint type with builder-style options.
path
Constructs a path type expression. Unlike typeway_path!, this does NOT generate marker types — it references markers that were already defined by a typeway_path! or typeway_api! invocation.
typeway_api
Defines a complete API type with inline route definitions.
typeway_path
Defines a path type with auto-generated literal segment markers.

Structs§

Added
Marks an endpoint as added in this version (not present in the base).
AuthRequired
Authentication middleware required.
BoundHandler
A handler bound to a specific endpoint type, with the handler’s arg types erased.
Capture
A captured path segment of type T.
CaptureRest
Matches all remaining path segments as a Vec<String>.
CorsRequired
CORS middleware required.
Delete
HTTP DELETE method.
Deprecated
Marks an endpoint as deprecated but still present.
ECons
Type-level cons cell for effect lists.
EHere
Type-level index: the effect is at this position in the list.
ENil
Type-level empty effect list.
EThere
Type-level index: the effect is at a later position in the list.
EffectfulLayeredServer
An effectful server with Tower middleware layers applied.
EffectfulServer
A server builder that tracks which middleware effects have been provided.
End
Protocol termination. No further messages can be sent or received.
Endpoint
A type-level HTTP endpoint descriptor.
Extension
Extracts a value from request extensions.
Get
HTTP GET method.
HCons
Heterogeneous list cons cell.
HNil
Heterogeneous list terminator.
HandlerDoc
Documentation metadata extracted from a handler function’s doc comments.
Head
HTTP HEAD method.
Header
Extracts a single header value by name.
Here
Type-level index: the endpoint is at this position in the tuple.
Json
A JSON response wrapper.
JsonError
A structured JSON error response.
LayeredServer
A server with Tower middleware layers applied.
Lit
A literal path segment wrapper in the HList.
Negotiated
A response that supports multiple content types via negotiation.
NoBody
Marker type indicating no request body.
Offer
Offer a choice between two protocol branches.
Options
HTTP OPTIONS method.
Patch
HTTP PATCH method.
Path
Extracts typed path captures from the URL.
Post
HTTP POST method.
Put
HTTP PUT method.
Query
Extracts typed query string parameters.
RateLimitRequired
Rate limiting middleware required.
Rec
Recursive protocol marker.
Recv
Receive a message of type T, then continue with protocol Next.
Removed
Marks an endpoint as removed in this version.
Replaced
Marks an endpoint as replaced: the old signature becomes the new one.
Requires
An endpoint that requires a specific middleware effect.
Router
A runtime HTTP router.
RouterService
A tower::Service wrapper around a shared Router.
SecureHeadersLayer
A Tower layer that adds security headers to every response.
Select
Select one of two protocol branches.
Server
A type-safe HTTP server parameterized by an API specification.
State
Extracts shared application state.
There
Type-level index: the endpoint is at a later position in the tuple.
TracingRequired
Tracing/logging middleware required.
Var
Variable referencing the enclosing Rec.
VersionedApi
A versioned API type carrying its lineage as type parameters.

Traits§

AllProvided
Asserts that all effects required by an API type are present in the provided effects list P.
ApiChangelog
Describes the changes between two API versions.
ApiSpec
Marker trait for valid API specifications.
BackwardCompatible
Marker trait asserting that a newer API version is backward-compatible with an older one.
CapturesPrepend
Runtime counterpart of Prepend — constructs a tuple value by prepending a value onto an existing tuple value.
ChangeMarker
Sealed helper trait implemented by each change marker. Used internally by ApiChangelog counting logic.
ContentFormat
Trait implemented by format marker types that represent a content type.
Dual
Compute the dual (mirror) of a session type.
Effect
Marker trait for middleware effects.
ExtractPath
Runtime path parsing, paired with the compile-time PathSpec.
FromRequest
Extract a value by consuming the request body.
FromRequestParts
Extract a value from request metadata (URI, headers, extensions).
Handler
A handler that can process an HTTP request and produce a response.
HasEffect
Trait asserting that an effect list contains a specific effect.
HasEndpoint
Trait asserting that an API tuple contains a specific endpoint type.
HttpMethod
Associates a zero-sized method type with its http::Method value.
IntoResponse
Trait for types that can be converted into an HTTP response.
IsEndpoint
Helper trait that is satisfied when Self is the same type as E.
LitSegment
Trait implemented by literal path segment marker types.
NamedHeader
Trait for types that can be extracted from a named HTTP header.
PathSpec
Computes the tuple of captured types from a path HList.
Prepend
Prepends a type T onto a tuple, producing a tuple one element larger.
Serves
A tuple of bound handlers that fully covers an API specification.
SessionType
Marker trait for valid session types.
VersionInfo
Metadata about an API version, used by OpenAPI generation and documentation tooling.

Functions§

bind
Bind a handler to an endpoint type, erasing the handler’s arg types.
body_from_stream
Create a streaming BoxBody from a Stream of Result<Frame<Bytes>, E>.
empty_body
Create an empty BoxBody.
serve
Convenience function to create and serve an API.
sse_body
Create an SSE (Server-Sent Events) body from a stream of event strings.

Type Aliases§

DeleteEndpoint
DELETE endpoint with no request body.
GetEndpoint
GET endpoint with no request body.
PatchEndpoint
PATCH endpoint with a request body.
PostEndpoint
POST endpoint with a request body.
PutEndpoint
PUT endpoint with a request body.

Attribute Macros§

api_description
Defines an API as a trait, generating endpoint types and a Serves bridge.
documented_handler
Extracts doc comments from a handler function and generates a companion const of type HandlerDoc (from typeway_core) containing the summary, description, operation ID, and tags.
handler
Validates a handler function at its definition site.

Derive Macros§

ToProtoType
Derives a ToProtoType implementation for a struct with named fields.
TypestateBuilder
Derive a typestate builder for a struct.
TypewayCodec
Derive TypewayEncode and TypewayDecode for a struct.
TypewaySchema
Derives a ToSchema implementation for a struct with named fields.