Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allows passing the style of a parameter in the openapi spec. #940

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion poem-openapi-derive/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::{
APIMethod, CodeSample, DefaultValue, ExampleValue, ExternalDocument, ExtraHeader,
},
error::GeneratorResult,
parameter_style::ParameterStyle,
utils::{
convert_oai_path, get_crate_name, get_description, get_summary_and_description,
optional_literal, optional_literal_string, parse_oai_attrs, remove_description,
Expand Down Expand Up @@ -75,7 +76,8 @@ struct APIOperationParam {
validator: Option<Validators>,
#[darling(default)]
explode: Option<bool>,

#[darling(default)]
style: Option<ParameterStyle>,
// for oauth
#[darling(multiple, default, rename = "scope")]
scopes: Vec<Path>,
Expand Down Expand Up @@ -347,12 +349,20 @@ fn generate_operation(
// do extract
let explode = operation_param.explode.unwrap_or(true);

let style = match &operation_param.style {
Some(operation_param) => {
quote!(::std::option::Option::Some(#crate_name::ParameterStyle::#operation_param))
}
None => quote!(::std::option::Option::None),
};

parse_args.push(quote! {
let mut param_opts = #crate_name::ExtractParamOptions {
name: #param_name,
default_value: #default_value,
example_value: #example_value,
explode: #explode,
style: #style,
};

let #pname = match <#arg_ty as #crate_name::ApiExtractor>::from_request(&request, &mut body, param_opts).await {
Expand Down Expand Up @@ -390,6 +400,7 @@ fn generate_operation(
required: <#arg_ty as #crate_name::ApiExtractor>::PARAM_IS_REQUIRED && !#has_default,
deprecated: #deprecated,
explode: #explode,
style: #style,
};
params.push(meta_param);
}
Expand Down Expand Up @@ -523,6 +534,7 @@ fn generate_operation(
required: <#ty as #crate_name::types::Type>::IS_REQUIRED,
deprecated: #deprecated,
explode: true,
style: None,
});
});
}
Expand Down
2 changes: 2 additions & 0 deletions poem-openapi-derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ mod union;
mod utils;
mod webhook;

mod parameter_style;

use darling::FromMeta;
use proc_macro::TokenStream;
use syn::{parse_macro_input, DeriveInput, ItemImpl, ItemTrait};
Expand Down
30 changes: 30 additions & 0 deletions poem-openapi-derive/src/parameter_style.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use darling::FromMeta;
use proc_macro2::Ident;
use quote::{ToTokens, TokenStreamExt};

#[derive(FromMeta)]
pub(crate) enum ParameterStyle {
Label,
Matrix,
Form,
Simple,
SpaceDelimited,
PipeDelimited,
DeepObject,
}

impl ToTokens for ParameterStyle {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let name = match self {
ParameterStyle::Label => "Label",
ParameterStyle::Matrix => "Matrix",
ParameterStyle::Form => "Form",
ParameterStyle::Simple => "Simple",
ParameterStyle::SpaceDelimited => "SpaceDelimited",
ParameterStyle::PipeDelimited => "PipeDelimited",
ParameterStyle::DeepObject => "DeepObject",
};

tokens.append(Ident::new(name, proc_macro2::Span::call_site()));
}
}
1 change: 1 addition & 0 deletions poem-openapi-derive/src/webhook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ fn generate_operation(
required: <#arg_ty as #crate_name::ApiExtractor>::PARAM_IS_REQUIRED,
deprecated: #deprecated,
explode: #explode,
style: ::std::option::Option::None
};
params.push(meta_param);
}
Expand Down
27 changes: 27 additions & 0 deletions poem-openapi/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::{

use futures_util::FutureExt;
use poem::{endpoint::BoxEndpoint, http::Method, Error, FromRequest, Request, RequestBody, Result};
use serde::Serialize;

use crate::{
payload::Payload,
Expand All @@ -16,6 +17,28 @@ use crate::{
},
};

/// The style of the passed parameter. See https://swagger.io/docs/specification/v3_0/serialization/ for details
#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ParameterStyle {
/// Dot-prefixed values, also known as label expansion.
Label,
/// Semicolon-prefixed values, also known as path-style expansion.
Matrix,
/// Ampersand-separated values, also known as form-style query expansion.
Form,
/// Comma-separated values
Simple,
/// Space-separated array values. Has effect only for non-exploded arrays.
SpaceDelimited,
/// Pipeline-separated array values. Has effect only for non-exploded
/// arrays.
PipeDelimited,
/// Bracket-nested objects, e.g.
/// `paramName[prop1]=value1&paramName[prop2]=value2`
DeepObject,
}

/// API extractor types.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum ApiExtractorType {
Expand Down Expand Up @@ -75,6 +98,9 @@ pub struct ExtractParamOptions<T> {
/// separate parameters for each value of the array or key-value pair of the
/// map.
pub explode: bool,

/// The style of the parameter.
pub style: Option<ParameterStyle>,
}

impl<T> Default for ExtractParamOptions<T> {
Expand All @@ -84,6 +110,7 @@ impl<T> Default for ExtractParamOptions<T> {
default_value: None,
example_value: None,
explode: true,
style: None,
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion poem-openapi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ mod ui;

pub use base::{
ApiExtractor, ApiExtractorType, ApiResponse, ExtractParamOptions, OAuthScopes, OpenApi,
OperationId, ResponseContent, Tags, Webhook,
OperationId, ParameterStyle, ResponseContent, Tags, Webhook,
};
pub use openapi::{
ContactObject, ExternalDocumentObject, ExtraHeader, LicenseObject, OpenApiService, ServerObject,
Expand Down
1 change: 1 addition & 0 deletions poem-openapi/src/openapi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,7 @@ impl<T, W> OpenApiService<T, W> {
required: *is_required,
deprecated: header.deprecated,
explode: true,
style: None,
},
);
}
Expand Down
3 changes: 2 additions & 1 deletion poem-openapi/src/registry/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub(crate) use ser::Document;
use serde::{ser::SerializeMap, Serialize, Serializer};
use serde_json::Value;

use crate::types::Type;
use crate::{types::Type, ParameterStyle};

#[allow(clippy::trivially_copy_pass_by_ref)]
#[inline]
Expand Down Expand Up @@ -372,6 +372,7 @@ pub struct MetaOperationParam {
pub required: bool,
pub deprecated: bool,
pub explode: bool,
pub style: Option<ParameterStyle>,
}

#[derive(Debug, PartialEq, Serialize)]
Expand Down
25 changes: 24 additions & 1 deletion poem-openapi/tests/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use poem_openapi::{
payload::{Binary, Json, Payload, PlainText},
registry::{MetaApi, MetaExternalDocument, MetaOperation, MetaParamIn, MetaSchema, Registry},
types::Type,
ApiRequest, ApiResponse, Object, OpenApi, OpenApiService, Tags,
ApiRequest, ApiResponse, Object, OpenApi, OpenApiService, ParameterStyle, Tags,
};

#[tokio::test]
Expand Down Expand Up @@ -999,3 +999,26 @@ async fn issue_489() {
.await
.assert_status(StatusCode::METHOD_NOT_ALLOWED);
}

#[tokio::test]
async fn parameter_style() {
#[allow(dead_code)]
struct Api;

#[OpenApi]
impl Api {
#[oai(path = "/hello", method = "get")]
#[allow(dead_code)]
async fn index(
&self,
#[oai(style = "deep_object")] Query(input): Query<String>,
) -> PlainText<String> {
PlainText(format!("hello, world! {input}"))
}
}

assert_eq!(
Api::meta()[0].paths[0].operations[0].params[0].style,
Some(ParameterStyle::DeepObject)
)
}
2 changes: 2 additions & 0 deletions poem-openapi/tests/webhook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ async fn parameters() {
required: true,
deprecated: false,
explode: true,
style: None,
},
MetaOperationParam {
name: "b".to_string(),
Expand All @@ -135,6 +136,7 @@ async fn parameters() {
required: true,
deprecated: false,
explode: true,
style: None,
}
]
);
Expand Down
Loading