Function utoipa_swagger_ui::serve

source ·
pub fn serve<'a>(
    path: &str,
    config: Arc<Config<'a>>
) -> Result<Option<SwaggerFile<'a>>, Box<dyn Error>>
Expand description

User friendly way to serve Swagger UI and its content via web server.

  • path Should be the relative path to Swagger UI resource within the web server.
  • config Swagger Config to use for the Swagger UI. Currently supported configuration options are managing Urls.

Typically this function is implemented within handler what handles GET operations related to the Swagger UI. Handler itself must match to user defined path that points to the root of the Swagger UI and matches everything relatively from the root of the Swagger UI. The relative path from root of the Swagger UI must be taken to tail path variable which is used to serve SwaggerFiles. If Swagger UI is served from path /swagger-ui/ then the tail is everything under the /swagger-ui/ prefix.

There are also implementations in examples of utoipa repository.

Examples

Reference implementation with actix-web.

// The config should be created in main function or in initialization before
// creation of the handler which will handle serving the Swagger UI.
let config = Arc::new(Config::from("/api-doc.json"));
// This "/" is for demonstrative purposes only. The actual path should point to
// file within Swagger UI. In real implementation this is the `tail` path from root of the
// Swagger UI to the file served.
let path = "/";

match utoipa_swagger_ui::serve(path, config) {
    Ok(swagger_file) => swagger_file
        .map(|file| {
            HttpResponse::Ok()
                .content_type(file.content_type)
                .body(file.bytes.to_vec())
        })
        .unwrap_or_else(|| HttpResponse::NotFound().finish()),
    Err(error) => HttpResponse::InternalServerError().body(error.to_string()),
};