ruma_common::api

Attribute Macro response

Source
#[response]
Available on crate feature api only.
Expand description

Generates OutgoingResponse and IncomingResponse implementations.

The OutgoingResponse impl is feature-gated behind cfg(feature = "server"). The IncomingResponse impl is feature-gated behind cfg(feature = "client").

The generated code expects a METADATA constant of type Metadata to be in scope.

By default, the type this macro is used on gets a #[non_exhaustive] attribute. This behavior can be controlled by defining an unstable-exhaustive-types cargo feature on the crate where this macro is called. When that feature is activated, the attribute is not applied so the type is exhaustive.

The status code of OutgoingResponse can be optionally overridden by adding the status attribute to response. The attribute value must be a status code constant from http::StatusCode, e.g. IM_A_TEAPOT.

§Attributes

To declare which part of the response a field belongs to:

  • #[ruma_api(header = HEADER_NAME)]: Fields with this attribute will be treated as HTTP headers on the response. The value must implement ToString and FromStr. Generally this is a String. The attribute value shown above as HEADER_NAME must be a header name constant from http::header, e.g. CONTENT_TYPE. During deserialization of the response, if the field is an Option and parsing the header fails, the error will be ignored and the value will be None.
  • No attribute: Fields without an attribute are part of the body. They can use #[serde] attributes to customize (de)serialization.
  • #[ruma_api(body)]: Use this if multiple endpoints should share a response body type, or the response body is better expressed as an enum rather than a struct. The value of the field will be used as the JSON body (rather than being a field in the response body object).
  • #[ruma_api(raw_body)]: Like body in that the field annotated with it represents the entire response body, but this attribute is for endpoints where the body can be anything, not just JSON. The field type must be Vec<u8>.

§Examples

pub mod do_a_thing {
    use ruma_common::{api::response, OwnedRoomId};

    // const METADATA: Metadata = metadata! { ... };

    // #[request]
    // pub struct Request { ... }

    #[response(status = IM_A_TEAPOT)]
    pub struct Response {
        #[serde(skip_serializing_if = "Option::is_none")]
        pub foo: Option<String>,
    }
}

pub mod download_file {
    use http::header::CONTENT_TYPE;
    use ruma_common::api::response;

    // const METADATA: Metadata = metadata! { ... };

    // #[request]
    // pub struct Request { ... }

    #[response]
    pub struct Response {
        #[ruma_api(header = CONTENT_TYPE)]
        pub content_type: String,

        #[ruma_api(raw_body)]
        pub file: Vec<u8>,
    }
}

⚠ If this is the only documentation you see, please navigate to the docs for ruma_common::api::response, where actual documentation can be found.