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.

Typically this function is implemented within handler what serves the Swagger UI. Handler itself must match to user defined path that points to the root of the Swagger UI and match everything relatively from the root of the Swagger UI (tail path). The relative path from root of the Swagger UI 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 tail_path = "/";

fn get_swagger_ui(tail_path: String, config: Arc<Config>) -> HttpResponse {
  match utoipa_swagger_ui::serve(tail_path.as_ref(), 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()),
  }
}