Skip to content

Instantly share code, notes, and snippets.

@stella3d
Last active July 29, 2025 19:35
Show Gist options
  • Save stella3d/51e679e55b264adff89d00a1e58d0272 to your computer and use it in GitHub Desktop.
Save stella3d/51e679e55b264adff89d00a1e58d0272 to your computer and use it in GitHub Desktop.
rough BinaryJson response type for `poem-openapi`
use poem_openapi::registry::{
MetaHeader, MetaResponse, MetaResponses, MetaSchema, MetaSchemaRef, Registry,
};
struct BinaryJson<'a>(pub &'a [u8]);
impl<'a> BinaryJson<'a> {
pub fn new(data: &'a [u8]) -> Self {
Self(data)
}
}
impl<'a> ApiResponse for BinaryJson<'a> {
fn meta() -> MetaResponses {
MetaResponses {
responses: vec![MetaResponse {
description: "Binary JSON response",
status: Some(200),
status_range: None, // whatever you decide
content: vec![],
headers: vec![MetaHeader {
name: "Content-Type".to_string(),
description: None,
required: true,
deprecated: false,
schema: MetaSchemaRef::Reference("String".to_string()),
}],
}],
}
}
fn register(registry: &mut Registry) {
registry.create_schema::<BinaryJson, _>("BinaryJson".to_string(), |_| {
MetaSchema::new("BinaryJson")
});
}
}
impl IntoResponse for BinaryJson<'_> {
fn into_response(self) -> poem::Response {
poem::Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "application/json")
.body(self.0.to_vec()) // couldn't find a way around, Response wants owned data
}
}
// then define your API...
pub struct Api;
#[OpenApi]
impl Api {
#[oai(path = "/rawjson", method = "get")]
async fn raw_json(&self) -> BinaryJson {
BinaryJson::new(b"{\"a\": 1}")
}
}
use bytes::Bytes;
use poem_openapi::registry::{
MetaHeader, MetaResponse, MetaResponses, MetaSchema, MetaSchemaRef, Registry,
};
struct BinaryJson(pub Bytes);
impl BinaryJson {
pub fn new(data: &[u8]) -> Self {
Self(Bytes::copy_from_slice(data))
}
}
impl ApiResponse for BinaryJson {
fn meta() -> MetaResponses {
MetaResponses {
responses: vec![MetaResponse {
description: "Binary JSON response",
status: Some(200),
status_range: None, // whatever you decide
content: vec![],
headers: vec![MetaHeader {
name: "Content-Type".to_string(),
description: None,
required: true,
deprecated: false,
schema: MetaSchemaRef::Reference("String".to_string()),
}],
}],
}
}
fn register(registry: &mut Registry) {
registry.create_schema::<BinaryJson, _>("BinaryJson".to_string(), |_| {
MetaSchema::new("BinaryJson")
});
}
}
impl IntoResponse for BinaryJson {
fn into_response(self) -> poem::Response {
poem::Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "application/json")
.body(self.0)
}
}
pub struct Api; // then define your API
#[OpenApi]
impl Api {
#[oai(path = "/rawjson", method = "get")]
async fn raw_json(&self) -> BinaryJson {
BinaryJson::new(b"{\"a\": 1}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment