Page MenuHomePhorge

No OneTemporary

Size
64 KB
Referenced Files
None
Subscribers
None
diff --git a/README.md b/README.md
index c3419c5..5921c79 100644
--- a/README.md
+++ b/README.md
@@ -1,384 +1,414 @@
# Open API Spex
[![Build Status](https://travis-ci.com/open-api-spex/open_api_spex.svg?branch=master)](https://travis-ci.com/open-api-spex/open_api_spex)
[![Hex.pm](https://img.shields.io/hexpm/v/open_api_spex.svg)](https://hex.pm/packages/open_api_spex)
Leverage Open Api Specification 3 (swagger) to document, test, validate and explore your Plug and Phoenix APIs.
- Generate and serve a JSON Open Api Spec document from your code
- Use the spec to cast request params to well defined schema structs
- Validate params against schemas, eliminate bad requests before they hit your controllers
- Validate responses against schemas in tests, ensuring your docs are accurate and reliable
- Explore the API interactively with with [SwaggerUI](https://swagger.io/swagger-ui/)
Full documentation available on [hexdocs](https://hexdocs.pm/open_api_spex/)
## Installation
The package can be installed by adding `open_api_spex` to your list of dependencies in `mix.exs`:
```elixir
def deps do
[
{:open_api_spex, "~> 3.4"}
]
end
```
## Generate Spec
Start by adding an `ApiSpec` module to your application to populate an `OpenApiSpex.OpenApi` struct.
```elixir
defmodule MyAppWeb.ApiSpec do
alias OpenApiSpex.{OpenApi, Server, Info, Paths}
alias MyAppWeb.{Endpoint, Router}
@behaviour OpenApi
@impl OpenApi
def spec do
%OpenApi{
servers: [
# Populate the Server info from a phoenix endpoint
Server.from_endpoint(Endpoint)
],
info: %Info{
title: "My App",
version: "1.0"
},
# populate the paths from a phoenix router
paths: Paths.from_router(Router)
}
|> OpenApiSpex.resolve_schema_modules() # discover request/response schemas from path specs
end
end
```
For each plug (controller) that will handle api requests, add an `open_api_operation` callback.
It will be passed the plug opts that were declared in the router, this will be the action for a phoenix controller. The callback populates an `OpenApiSpex.Operation` struct describing the plug/action.
```elixir
defmodule MyAppWeb.UserController do
alias OpenApiSpex.Operation
alias MyAppWeb.Schemas.UserResponse
@spec open_api_operation(atom) :: Operation.t()
def open_api_operation(action) do
operation = String.to_existing_atom("#{action}_operation")
apply(__MODULE__, operation, [])
end
@spec show_operation() :: Operation.t()
def show_operation() do
%Operation{
tags: ["users"],
summary: "Show user",
description: "Show a user by ID",
operationId: "UserController.show",
parameters: [
Operation.parameter(:id, :path, :integer, "User ID", example: 123, required: true)
],
responses: %{
200 => Operation.response("User", "application/json", UserResponse)
}
}
end
# Controller's `show` action
def show(conn, %{id: id}) do
{:ok, user} = MyApp.Users.find_by_id(id)
json(conn, 200, user)
end
end
```
Alternatively, you can create an operation file separately using `defdelegate`.
```elixir
# Phoenix's controller
defmodule MyAppWeb.UserController do
defdelegate open_api_operation(action), to: MyAppWeb.UserApiOperation
def show(conn, %{id: id}) do
{:ok, user} = MyApp.Users.find_by_id(id)
json(conn, 200, user)
end
end
# Open API Spex operations
defmodule MyAppWeb.UserApiOperation do
alias OpenApiSpex.Operation
alias MyAppWeb.Schemas.UserResponse
@spec open_api_operation(atom) :: Operation.t()
def open_api_operation(action) do
operation = String.to_existing_atom("#{action}_operation")
apply(__MODULE__, operation, [])
end
@spec show_operation() :: Operation.t()
def show_operation() do
%Operation{
tags: ["users"],
summary: "Show user",
description: "Show a user by ID",
operationId: "UserController.show",
parameters: [
Operation.parameter(:id, :path, :integer, "User ID", example: 123, required: true)
],
responses: %{
200 => Operation.response("User", "application/json", UserResponse)
}
}
end
end
```
For examples of other action operations, see the
[example web app](https://github.com/open-api-spex/open_api_spex/blob/master/examples/phoenix_app/lib/phoenix_app_web/controllers/user_controller.ex).
Next, declare JSON schema modules for the request and response bodies.
In each schema module, call `OpenApiSpex.schema/1`, passing the schema definition. The schema must
have keys described in `OpenApiSpex.Schema.t`. This will define a `%OpenApiSpex.Schema{}` struct.
This struct is made available from the `schema/0` public function, which is generated by `OpenApiSpex.schema/1`.
You may optionally have the data described by the schema turned into a struct linked to the JSON schema by adding `"x-struct": __MODULE__`
to the schema.
```elixir
defmodule MyAppWeb.Schemas do
alias OpenApiSpex.Schema
defmodule User do
require OpenApiSpex
OpenApiSpex.schema(%{
title: "User",
description: "A user of the app",
type: :object,
properties: %{
id: %Schema{type: :integer, description: "User ID"},
name: %Schema{type: :string, description: "User name", pattern: ~r/[a-zA-Z][a-zA-Z0-9_]+/},
email: %Schema{type: :string, description: "Email address", format: :email},
birthday: %Schema{type: :string, description: "Birth date", format: :date},
inserted_at: %Schema{
type: :string,
description: "Creation timestamp",
format: :"date-time"
},
updated_at: %Schema{type: :string, description: "Update timestamp", format: :"date-time"}
},
required: [:name, :email],
example: %{
"id" => 123,
"name" => "Joe User",
"email" => "joe@gmail.com",
"birthday" => "1970-01-01T12:34:55Z",
"inserted_at" => "2017-09-12T12:34:55Z",
"updated_at" => "2017-09-13T10:11:12Z"
}
})
end
defmodule UserResponse do
require OpenApiSpex
OpenApiSpex.schema(%{
title: "UserResponse",
description: "Response schema for single user",
type: :object,
properties: %{
data: User
},
example: %{
"data" => %{
"id" => 123,
"name" => "Joe User",
"email" => "joe@gmail.com",
"birthday" => "1970-01-01T12:34:55Z",
"inserted_at" => "2017-09-12T12:34:55Z",
"updated_at" => "2017-09-13T10:11:12Z"
}
}
})
end
end
```
For more examples of schema definitions, see the
[sample Phoenix app](https://github.com/open-api-spex/open_api_spex/blob/master/examples/phoenix_app/lib/phoenix_app_web/schemas.ex)
## Serve the Spec
To serve the API spec from your application, first add the `OpenApiSpex.Plug.PutApiSpec` plug somewhere in the pipeline.
```elixir
pipeline :api do
plug OpenApiSpex.Plug.PutApiSpec, module: MyAppWeb.ApiSpec
end
```
Now the spec will be available for use in downstream plugs.
The `OpenApiSpex.Plug.RenderSpec` plug will render the spec as JSON:
```elixir
scope "/api" do
pipe_through :api
resources "/users", MyAppWeb.UserController, only: [:create, :index, :show]
get "/openapi", OpenApiSpex.Plug.RenderSpec, []
end
```
## Generating the Spec
Optionally, you can create a mix task to write the swagger file to disk:
```elixir
defmodule Mix.Tasks.MyApp.OpenApiSpec do
def run([output_file]) do
MyAppWeb.Endpoint.start_link() # Required if using for OpenApiSpex.Server.from_endpoint/1
json =
MyAppWeb.ApiSpec.spec()
|> Jason.encode!(pretty: true)
:ok = File.write!(output_file, json)
end
end
```
Generate the file with: `mix my_app.openapispec spec.json`
## Serve Swagger UI
Once your API spec is available through a route (see "Serve the Spec"), the `OpenApiSpex.Plug.SwaggerUI` plug can be used to
serve a SwaggerUI interface. The `path:` plug option must be supplied to give the path to the API spec.
All JavaScript and CSS assets are sourced from cdnjs.cloudflare.com, rather than vendoring into this package.
```elixir
scope "/" do
pipe_through :browser # Use the default browser stack
get "/", MyAppWeb.PageController, :index
get "/swaggerui", OpenApiSpex.Plug.SwaggerUI, path: "/api/openapi"
end
scope "/api" do
pipe_through :api
resources "/users", MyAppWeb.UserController, only: [:create, :index, :show]
get "/openapi", OpenApiSpex.Plug.RenderSpec, []
end
```
+## Importing an existing schema file
+
+> :warning: This functionality currently converts Strings into Atoms, which makes it potentially [vulnerable to DoS attacks](https://til.hashrocket.com/posts/gkwwfy9xvw-converting-strings-to-atoms-safely). We recommend that you load Open API Schemas from *known files* during application startup and *not dynamically from external sources at runtime*.
+
+OpenApiSpex has functionality to import an existing schema, casting it into an %OpenApi{} struct. This means you can load a schema that is JSON or YAML encoded. See the example below:
+
+```elixir
+# Importing an existing JSON encoded schema
+open_api_spec_from_json = "encoded_schema.json"
+ |> File.read!()
+ |> Jason.decode!()
+ |> OpenApiSpex.OpenApi.Decode.decode()
+
+# Importing an existing YAML encoded schema
+open_api_spec_from_yaml = "encoded_schema.yaml"
+ |> YamlElixir.read_all_from_file!()
+ |> OpenApiSpex.OpenApi.Decode.decode()
+```
+
+You can then use the loaded spec to with `OpenApiSpex.cast_and_validate/4`, like:
+
+```elixir
+{:ok, _} = OpenApiSpex.cast_and_validate(
+ open_api_spec_from_json, # or open_api_spec_from_yaml
+ spec.paths["/some_path"].post,
+ test_conn,
+ "application/json"
+)
+```
+
## Validating and Casting Params
OpenApiSpex can automatically validate requests before they reach the controller action function. Or if you prefer,
you can explicitly call on OpenApiSpex to cast and validate the params within the controller action. This section
describes the former.
First, the `plug OpenApiSpex.Plug.PutApiSpec` needs to be called in the Router, as described above.
Add the `OpenApiSpex.Plug.CastAndValidate` plug to a controller to validate request parameters and to cast to Elixir types defined by the operation schema.
```elixir
# Phoenix
plug OpenApiSpex.Plug.CastAndValidate
# Plug
plug OpenApiSpex.Plug.CastAndValidate, operation_id: "UserController.create
```
For Phoenix apps, the `operation_id` can be inferred from the contents of `conn.private`.
```elixir
defmodule MyAppWeb.UserController do
use MyAppWeb, :controller
alias OpenApiSpex.Operation
alias MyAppWeb.Schemas.{User, UserRequest, UserResponse}
plug OpenApiSpex.Plug.CastAndValidate
def open_api_operation(action) do
apply(__MODULE__, :"#{action}_operation", [])
end
def create_operation do
import Operation
%Operation{
tags: ["users"],
summary: "Create user",
description: "Create a user",
operationId: "UserController.create",
parameters: [
parameter(:id, :query, :integer, "user ID")
],
requestBody: request_body("The user attributes", "application/json", UserRequest),
responses: %{
201 => response("User", "application/json", UserResponse)
}
}
end
def create(conn = %{body_params: %UserRequest{user: %User{name: name, email: email, birthday: birthday = %Date{}}}}, %{id: id}) do
# conn.body_params cast to UserRequest struct
# conn.params.id cast to integer
end
end
```
Now the client will receive a 422 response whenever the request fails to meet the validation rules from the api spec.
The response body will include the validation error message:
```json
{
"errors": [
{
"message": "Invalid format. Expected :date",
"source": {
"pointer": "/data/birthday"
},
"title": "Invalid value"
}
]
}
```
See also `OpenApiSpex.cast_value/3` for casting and validating outside of a `plug` pipeline.
## Validate Examples
As schemas evolve, you may want to confirm that the examples given match the schemas.
Use the `OpenApiSpex.TestAssertions` module to assert on schema validations.
```elixir
use ExUnit.Case
import OpenApiSpex.TestAssertions
test "UsersResponse example matches schema" do
api_spec = MyAppWeb.ApiSpec.spec()
schema = MyAppWeb.Schemas.UsersResponse.schema()
assert_schema(schema.example, "UsersResponse", api_spec)
end
```
## Validate Responses
API responses can be tested against schemas using `OpenApiSpex.TestAssertions` also:
```elixir
use MyAppWeb.ConnCase
import OpenApiSpex.TestAssertions
test "UserController produces a UsersResponse", %{conn: conn} do
api_spec = MyAppWeb.ApiSpec.spec()
json =
conn
|> get(user_path(conn, :index))
|> json_response(200)
assert_schema(json, "UsersResponse", api_spec)
end
```
diff --git a/lib/open_api_spex.ex b/lib/open_api_spex.ex
index 1801f4e..b1ca5a1 100644
--- a/lib/open_api_spex.ex
+++ b/lib/open_api_spex.ex
@@ -1,255 +1,274 @@
defmodule OpenApiSpex do
@moduledoc """
Provides the entry-points for defining schemas, validating and casting.
"""
alias OpenApiSpex.{
Components,
OpenApi,
Operation,
Operation2,
Reference,
Schema,
SchemaException,
SchemaResolver,
SchemaConsistency
}
alias OpenApiSpex.Cast.Error
@doc """
Adds schemas to the api spec from the modules specified in the Operations.
Eg, if the response schema for an operation is defined with:
responses: %{
200 => Operation.response("User", "application/json", UserResponse)
}
Then the `UserResponse.schema()` function will be called to load the schema, and
a `Reference` to the loaded schema will be used in the operation response.
See `OpenApiSpex.schema` macro for a convenient syntax for defining schema modules.
"""
@spec resolve_schema_modules(OpenApi.t()) :: OpenApi.t()
def resolve_schema_modules(spec = %OpenApi{}) do
SchemaResolver.resolve_schema_modules(spec)
end
@doc """
Cast and validate a value against a given Schema.
"""
def cast_value(value, schema = %schema_mod{}) when schema_mod in [Schema, Reference] do
OpenApiSpex.Cast.cast(schema, value)
end
@doc """
Cast and validate a value against a given Schema belonging to a given OpenApi spec.
"""
def cast_value(value, schema = %schema_mod{}, spec = %OpenApi{})
when schema_mod in [Schema, Reference] do
OpenApiSpex.Cast.cast(schema, value, spec.components.schemas)
end
def cast_and_validate(
spec = %OpenApi{},
operation = %Operation{},
conn = %Plug.Conn{},
content_type \\ nil
) do
Operation2.cast(operation, conn, content_type, spec.components)
end
@doc """
Cast params to conform to a `OpenApiSpex.Schema`.
See `OpenApiSpex.Schema.cast/3` for additional examples and details.
"""
@spec cast(OpenApi.t(), Schema.t() | Reference.t(), any) :: {:ok, any} | {:error, String.t()}
@deprecated "Use OpenApiSpex.cast_value/3 or cast_value/2 instead"
def cast(spec = %OpenApi{}, schema = %Schema{}, params) do
Schema.cast(schema, params, spec.components.schemas)
end
def cast(spec = %OpenApi{}, schema = %Reference{}, params) do
Schema.cast(schema, params, spec.components.schemas)
end
@doc """
Cast all params in `Plug.Conn` to conform to the schemas for `OpenApiSpex.Operation`.
Returns `{:ok, Plug.Conn.t}` with `params` and `body_params` fields updated if successful,
or `{:error, reason}` if casting fails.
`content_type` may optionally be supplied to select the `requestBody` schema.
"""
@spec cast(OpenApi.t(), Operation.t(), Plug.Conn.t(), content_type | nil) ::
{:ok, Plug.Conn.t()} | {:error, String.t()}
when content_type: String.t()
@deprecated "Use OpenApiSpex.cast_and_validate/3 instead"
def cast(spec = %OpenApi{}, operation = %Operation{}, conn = %Plug.Conn{}, content_type \\ nil) do
Operation.cast(operation, conn, content_type, spec.components.schemas)
end
@doc """
Validate params against `OpenApiSpex.Schema`.
See `OpenApiSpex.Schema.validate/3` for examples of error messages.
"""
@spec validate(OpenApi.t(), Schema.t() | Reference.t(), any) :: :ok | {:error, String.t()}
@deprecated "Use OpenApiSpex.cast_value/3 or cast_value/2 instead"
def validate(spec = %OpenApi{}, schema = %Schema{}, params) do
Schema.validate(schema, params, spec.components.schemas)
end
def validate(spec = %OpenApi{}, schema = %Reference{}, params) do
Schema.validate(schema, params, spec.components.schemas)
end
@doc """
Validate all params in `Plug.Conn` against `OpenApiSpex.Operation` `parameter` and `requestBody` schemas.
`content_type` may be optionally supplied to select the `requestBody` schema.
"""
@spec validate(OpenApi.t(), Operation.t(), Plug.Conn.t(), content_type | nil) ::
:ok | {:error, String.t()}
when content_type: String.t()
@deprecated "Use OpenApiSpex.cast_and_validate/4 instead"
def validate(
spec = %OpenApi{},
operation = %Operation{},
conn = %Plug.Conn{},
content_type \\ nil
) do
Operation.validate(operation, conn, content_type, spec.components.schemas)
end
def path_to_string(%Error{} = error) do
Error.path_to_string(error)
end
def error_message(%Error{} = error) do
Error.message(error)
end
@doc """
Declares a struct based `OpenApiSpex.Schema`
- defines the schema/0 callback
- ensures the schema is linked to the module by "x-struct" extension property
- defines a struct with keys matching the schema properties
- defines a @type `t` for the struct
- derives a `Jason.Encoder` and/or `Poison.Encoder` for the struct
See `OpenApiSpex.Schema` for additional examples and details.
## Example
require OpenApiSpex
defmodule User do
OpenApiSpex.schema %{
title: "User",
description: "A user of the app",
type: :object,
properties: %{
id: %Schema{type: :integer, description: "User ID"},
name: %Schema{type: :string, description: "User name", pattern: ~r/[a-zA-Z][a-zA-Z0-9_]+/},
email: %Schema{type: :string, description: "Email address", format: :email},
inserted_at: %Schema{type: :string, description: "Creation timestamp", format: :'date-time'},
updated_at: %Schema{type: :string, description: "Update timestamp", format: :'date-time'}
},
required: [:name, :email],
example: %{
"id" => 123,
"name" => "Joe User",
"email" => "joe@gmail.com",
"inserted_at" => "2017-09-12T12:34:55Z",
"updated_at" => "2017-09-13T10:11:12Z"
}
}
end
"""
defmacro schema(body) do
quote do
@compile {:report_warnings, false}
@behaviour OpenApiSpex.Schema
@schema struct(
OpenApiSpex.Schema,
Map.put(Map.delete(unquote(body), :__struct__), :"x-struct", __MODULE__)
)
def schema, do: @schema
@derive Enum.filter([Poison.Encoder, Jason.Encoder], &Code.ensure_loaded?/1)
defstruct Schema.properties(@schema)
@type t :: %__MODULE__{}
Map.from_struct(@schema) |> OpenApiSpex.validate_compiled_schema()
# Throwing warnings to prevent runtime bugs (like in issue #144)
@schema
|> SchemaConsistency.warnings()
|> Enum.each(&IO.warn("Inconsistent schema: #{&1}", Macro.Env.stacktrace(__ENV__)))
end
end
+ @doc """
+ Creates an `%OpenApi{}` struct from a map.
+
+ This is useful when importing existing JSON or YAML encoded schemas.
+
+ ## Example
+ # Importing an existing JSON encoded schema
+ open_api_spec_from_json = "encoded_schema.json"
+ |> File.read!()
+ |> Jason.decode!()
+ |> OpenApiSpex.OpenApi.Decode.decode()
+
+ # Importing an existing YAML encoded schema
+ open_api_spec_from_yaml = "encoded_schema.yaml"
+ |> YamlElixir.read_all_from_file!()
+ |> OpenApiSpex.OpenApi.Decode.decode()
+ """
+ def schema_from_map(map), do: OpenApiSpex.OpenApi.from_map(map)
+
@doc """
Validate the compiled schema's properties to ensure the schema is not improperly
defined. Only errors which would cause a given schema to _always_ fail should be
raised here.
"""
def validate_compiled_schema(schema) do
Enum.each(schema, fn prop_and_val ->
:ok = validate_compiled_schema(prop_and_val, schema)
end)
end
def validate_compiled_schema({_, %Schema{} = schema}, _parent) do
validate_compiled_schema(schema)
end
@doc """
Used for validating the schema at compile time, otherwise we're forced
to raise errors for improperly defined schemas at runtime.
"""
def validate_compiled_schema({:discriminator, %{propertyName: property, mapping: _}}, %{
anyOf: schemas
})
when is_list(schemas) do
Enum.each(schemas, fn schema ->
case schema do
%Schema{title: title} when is_binary(title) -> :ok
_ -> error!(:discriminator_schema_missing_title, schema, property_name: property)
end
end)
end
def validate_compiled_schema({:discriminator, %{propertyName: _, mapping: _}}, schema) do
case {schema.anyOf, schema.allOf, schema.oneOf} do
{nil, nil, nil} ->
error!(:discriminator_missing_composite_key, schema)
_ ->
:ok
end
end
def validate_compiled_schema({_property, _value}, _schema), do: :ok
@doc """
Raises compile time errors for improperly defined schemas.
"""
@spec error!(atom(), Schema.t(), keyword()) :: no_return()
@spec error!(atom(), Schema.t()) :: no_return()
def error!(error, schema, details \\ []) do
raise SchemaException, %{error: error, schema: schema, details: details}
end
@doc """
Resolve a schema or reference to a schema.
"""
@spec resolve_schema(Schema.t() | Reference.t(), Components.schemas_map()) :: Schema.t()
def resolve_schema(%Schema{} = schema, _), do: schema
def resolve_schema(%Reference{} = ref, schemas), do: Reference.resolve_schema(ref, schemas)
end
diff --git a/lib/open_api_spex/open_api.ex b/lib/open_api_spex/open_api.ex
index 0e076a4..50bdb5f 100644
--- a/lib/open_api_spex/open_api.ex
+++ b/lib/open_api_spex/open_api.ex
@@ -1,149 +1,153 @@
defmodule OpenApiSpex.OpenApi do
@moduledoc """
Defines the `OpenApiSpex.OpenApi.t` type and the behaviour for application modules that
construct an `OpenApiSpex.OpenApi.t` at runtime.
"""
alias OpenApiSpex.{
Extendable,
Info,
Server,
Paths,
Components,
SecurityRequirement,
Tag,
ExternalDocumentation,
OpenApi,
MediaType,
Schema,
Example
}
@enforce_keys [:info, :paths]
defstruct openapi: "3.0.0",
info: nil,
servers: [],
paths: nil,
components: nil,
security: [],
tags: [],
externalDocs: nil,
extensions: nil
@typedoc """
[OpenAPI Object](https://swagger.io/specification/#oasObject)
This is the root document object of the OpenAPI document.
"""
@type t :: %OpenApi{
openapi: String.t(),
info: Info.t(),
servers: [Server.t()] | nil,
paths: Paths.t(),
components: Components.t() | nil,
security: [SecurityRequirement.t()] | nil,
tags: [Tag.t()] | nil,
externalDocs: ExternalDocumentation.t() | nil,
extensions: %{String.t() => any()} | nil
}
@doc """
A spec/0 callback function is required for use with the `OpenApiSpex.Plug.PutApiSpec` plug.
## Example
@impl OpenApiSpex.OpenApi
def spec do
%OpenApi{
servers: [
# Populate the Server info from a phoenix endpoint
Server.from_endpoint(MyAppWeb.Endpoint)
],
info: %Info{
title: "My App",
version: "1.0"
},
# populate the paths from a phoenix router
paths: Paths.from_router(MyAppWeb.Router)
}
|> OpenApiSpex.resolve_schema_modules() # discover request/response schemas from path specs
end
"""
@callback spec() :: t
@json_encoder Enum.find([Jason, Poison], &Code.ensure_loaded?/1)
def json_encoder, do: @json_encoder
for encoder <- [Poison.Encoder, Jason.Encoder] do
if Code.ensure_loaded?(encoder) do
defimpl encoder do
def encode(api_spec = %OpenApi{}, options) do
api_spec
|> to_json()
|> unquote(encoder).encode(options)
end
defp to_json(%Regex{source: source}), do: source
defp to_json(%object{} = value) when object in [MediaType, Schema, Example] do
value
|> Extendable.to_map()
|> Stream.map(fn
{:value, v} when object == Example -> {"value", to_json_example(v)}
{:example, v} -> {"example", to_json_example(v)}
{k, v} -> {to_string(k), to_json(v)}
end)
|> Stream.filter(fn
{_, nil} -> false
_ -> true
end)
|> Enum.into(%{})
end
defp to_json(value = %{__struct__: _}) do
value
|> Extendable.to_map()
|> to_json()
end
defp to_json(value) when is_map(value) do
value
|> Stream.map(fn {k, v} -> {to_string(k), to_json(v)} end)
|> Stream.filter(fn
{_, nil} -> false
_ -> true
end)
|> Enum.into(%{})
end
defp to_json(value) when is_list(value) do
Enum.map(value, &to_json/1)
end
defp to_json(nil), do: nil
defp to_json(true), do: true
defp to_json(false), do: false
defp to_json(value) when is_atom(value), do: to_string(value)
defp to_json(value), do: value
defp to_json_example(value = %{__struct__: _}) do
value
|> Extendable.to_map()
|> to_json_example()
end
defp to_json_example(value) when is_map(value) do
value
|> Stream.map(fn {k, v} -> {to_string(k), to_json_example(v)} end)
|> Enum.into(%{})
end
defp to_json_example(value) when is_list(value) do
Enum.map(value, &to_json_example/1)
end
defp to_json_example(value), do: to_json(value)
end
end
end
+
+ def from_map(map) do
+ OpenApi.Decode.decode(map)
+ end
end
diff --git a/lib/open_api_spex/open_api/decode.ex b/lib/open_api_spex/open_api/decode.ex
new file mode 100644
index 0000000..3d944a5
--- /dev/null
+++ b/lib/open_api_spex/open_api/decode.ex
@@ -0,0 +1,402 @@
+defmodule OpenApiSpex.OpenApi.Decode do
+ # This module exposes functionality to convert an arbitrary map into a OpenApi struct.
+ alias OpenApiSpex.{
+ Components,
+ Contact,
+ Discriminator,
+ Encoding,
+ Example,
+ ExternalDocumentation,
+ Header,
+ Info,
+ License,
+ Link,
+ MediaType,
+ OAuthFlow,
+ OAuthFlows,
+ OpenApi,
+ Operation,
+ Parameter,
+ PathItem,
+ Reference,
+ RequestBody,
+ Response,
+ Schema,
+ SecurityScheme,
+ Server,
+ ServerVariable,
+ Tag,
+ Xml
+ }
+
+ def decode(%{"openapi" => _openapi, "info" => _info, "paths" => _paths} = map) do
+ map
+ |> to_struct(OpenApi)
+ |> prop_to_struct(:info, Info)
+ |> prop_to_struct(:paths, PathItems)
+ |> prop_to_struct(:servers, Servers)
+ |> prop_to_struct(:components, Components)
+ |> prop_to_struct(:tags, Tag)
+ |> prop_to_struct(:externalDocs, ExternalDocumentation)
+ end
+
+ defp struct_from_map(struct, map) when is_atom(struct) do
+ struct_from_map(struct.__struct__(), map)
+ end
+
+ defp struct_from_map(%_{} = struct, map) do
+ keys = struct |> Map.from_struct() |> Map.keys()
+
+ Enum.reduce(keys, struct, fn key, struct ->
+ case map_get(map, key) do
+ {_, value} -> Map.put(struct, key, value)
+ _ -> struct
+ end
+ end)
+ end
+
+ defp map_get(map, atom_key) when is_atom(atom_key) do
+ with %{^atom_key => value} <- map do
+ {atom_key, value}
+ else
+ _ -> map_get(map, to_string(atom_key))
+ end
+ end
+
+ defp map_get(map, string_key) when is_binary(string_key) do
+ case map do
+ %{^string_key => value} -> {string_key, value}
+ _ -> nil
+ end
+ end
+
+ defp embedded_ref_or_struct(list, mod) when is_list(list) do
+ list
+ |> Enum.map(fn
+ %{"$ref" => _} = v -> struct_from_map(Reference, v)
+ v -> to_struct(v, mod)
+ end)
+ end
+
+ defp embedded_ref_or_struct(map, mod) when is_map(map) do
+ map
+ |> Map.new(fn
+ {k, %{"$ref" => _} = v} ->
+ {k, struct_from_map(Reference, v)}
+
+ {k, v} ->
+ {k, to_struct(v, mod)}
+ end)
+ end
+
+ defp update_map_if_key_present(map, key, fun) do
+ case map do
+ %{^key => value} -> %{map | key => fun.(value)}
+ %{} -> map
+ end
+ end
+
+ # In some cases, e.g. Schema type we must convert values that are strings to atoms,
+ # for example Schema.type should be one of:
+ #
+ # :string | :number | :integer | :boolean | :array | :object
+ #
+ # This function, ensures that if the map has the key — it'll convert the corresponding value
+ # to an atom.
+ defp convert_value_to_atom_if_present(map, key),
+ do: update_map_if_key_present(map, key, &String.to_atom/1)
+
+ # In some cases, e.g. Schema type we must convert values that are list of strings to a list atoms,
+ #
+ # This function, ensures that if the map has the key — it'll convert the corresponding value
+ # to a list of atoms.
+ defp convert_value_to_list_of_atoms_if_present(map, key) do
+ map_fn = &String.to_atom/1
+ update_map_if_key_present(map, key, &Enum.map(&1, map_fn))
+ end
+
+ # The Schema.type and Schema.required keys require some special treatment since their
+ # values should be converted to atoms
+ defp prepare_schema(map) do
+ map
+ |> convert_value_to_atom_if_present("type")
+ |> convert_value_to_list_of_atoms_if_present("required")
+ end
+
+ defp to_struct(nil, _mod), do: nil
+
+ defp to_struct(tag, Tag) when is_binary(tag), do: tag
+
+ defp to_struct(map, Tag) when is_map(map) do
+ Tag
+ |> struct_from_map(map)
+ |> prop_to_struct(:externalDocs, ExternalDocumentation)
+ end
+
+ defp to_struct(list, Tag) when is_list(list) do
+ list
+ |> Enum.map(&to_struct(&1, Tag))
+ end
+
+ defp to_struct(map, Components) do
+ Components
+ |> struct_from_map(map)
+ |> prop_to_struct(:schemas, Schemas)
+ |> prop_to_struct(:responses, Responses)
+ |> prop_to_struct(:parameters, Parameters)
+ |> prop_to_struct(:examples, Examples)
+ |> prop_to_struct(:requestBodies, RequestBodies)
+ |> prop_to_struct(:headers, Headers)
+ |> prop_to_struct(:securitySchemes, SecuritySchemes)
+ |> prop_to_struct(:links, Links)
+ |> prop_to_struct(:callbacks, Callbacks)
+ end
+
+ defp to_struct(map, Link) do
+ Link
+ |> struct_from_map(map)
+ |> prop_to_struct(:server, Server)
+ |> prop_to_struct(:requestBody, RequestBody)
+ |> prop_to_struct(:parameters, Parameters)
+ end
+
+ defp to_struct(map, Links), do: embedded_ref_or_struct(map, Link)
+
+ defp to_struct(map, SecurityScheme) do
+ SecurityScheme
+ |> struct_from_map(map)
+ |> prop_to_struct(:flows, OAuthFlows)
+ end
+
+ defp to_struct(map, SecuritySchemes), do: embedded_ref_or_struct(map, SecurityScheme)
+
+ defp to_struct(map, OAuthFlow) do
+ struct_from_map(OAuthFlow, map)
+ end
+
+ defp to_struct(map, OAuthFlows) do
+ OAuthFlows
+ |> struct_from_map(map)
+ |> prop_to_struct(:implicit, OAuthFlow)
+ |> prop_to_struct(:password, OAuthFlow)
+ |> prop_to_struct(:clientCredentials, OAuthFlow)
+ |> prop_to_struct(:authorizationCode, OAuthFlow)
+ end
+
+ defp to_struct(%{"$ref" => _} = map, Schema), do: struct_from_map(Reference, map)
+
+ defp to_struct(%{"type" => type} = map, Schema)
+ when type in ~w(number integer boolean string) do
+ map
+ |> prepare_schema()
+ |> (&struct_from_map(Schema, &1)).()
+ |> prop_to_struct(:xml, Xml)
+ end
+
+ defp to_struct(%{"type" => "array"} = map, Schema) do
+ map
+ |> prepare_schema()
+ |> (&struct_from_map(Schema, &1)).()
+ |> prop_to_struct(:items, Schema)
+ |> prop_to_struct(:xml, Xml)
+ end
+
+ defp to_struct(%{"type" => "object"} = map, Schema) do
+ map
+ |> Map.update!("properties", fn v ->
+ v
+ |> Map.new(fn {k, v} ->
+ {String.to_atom(k), v}
+ end)
+ end)
+ |> prepare_schema()
+ |> (&struct_from_map(Schema, &1)).()
+ |> prop_to_struct(:properties, Schemas)
+ |> prop_to_struct(:externalDocs, ExternalDocumentation)
+ end
+
+ defp to_struct(%{"anyOf" => _valid_schemas} = map, Schema) do
+ Schema
+ |> struct_from_map(map)
+ |> prop_to_struct(:anyOf, Schemas)
+ |> prop_to_struct(:discriminator, Discriminator)
+ end
+
+ defp to_struct(%{"oneOf" => _valid_schemas} = map, Schema) do
+ Schema
+ |> struct_from_map(map)
+ |> prop_to_struct(:oneOf, Schemas)
+ |> prop_to_struct(:discriminator, Discriminator)
+ end
+
+ defp to_struct(%{"allOf" => _valid_schemas} = map, Schema) do
+ Schema
+ |> struct_from_map(map)
+ |> prop_to_struct(:allOf, Schemas)
+ |> prop_to_struct(:discriminator, Discriminator)
+ end
+
+ defp to_struct(%{"not" => _valid_schemas} = map, Schema) do
+ Schema
+ |> struct_from_map(map)
+ |> prop_to_struct(:not, Schemas)
+ end
+
+ defp to_struct(map, Schemas) when is_map(map), do: embedded_ref_or_struct(map, Schema)
+ defp to_struct(list, Schemas) when is_list(list), do: embedded_ref_or_struct(list, Schema)
+
+ defp to_struct(map, OAuthFlow) do
+ struct_from_map(OAuthFlow, map)
+ end
+
+ defp to_struct(map, Callback) do
+ map
+ |> Map.new(fn {k, v} ->
+ {k, to_struct(v, PathItem)}
+ end)
+ end
+
+ defp to_struct(map_or_list, Callbacks), do: embedded_ref_or_struct(map_or_list, Callback)
+
+ defp to_struct(map, Operation) do
+ Operation
+ |> struct_from_map(map)
+ |> prop_to_struct(:tags, Tag)
+ |> prop_to_struct(:externalDocs, ExternalDocumentation)
+ |> prop_to_struct(:responses, Responses)
+ |> prop_to_struct(:parameters, Parameters)
+ |> prop_to_struct(:requestBody, RequestBody)
+ |> prop_to_struct(:callbacks, Callbacks)
+ |> prop_to_struct(:servers, Server)
+ end
+
+ defp to_struct(map, RequestBody) do
+ RequestBody
+ |> struct_from_map(map)
+ |> prop_to_struct(:content, Content)
+ end
+
+ defp to_struct(map, RequestBodies), do: embedded_ref_or_struct(map, RequestBody)
+
+ defp to_struct(map, Parameter) do
+ map
+ |> convert_value_to_atom_if_present("name")
+ |> convert_value_to_atom_if_present("in")
+ |> convert_value_to_atom_if_present("style")
+ |> (&struct_from_map(Parameter, &1)).()
+ |> prop_to_struct(:examples, Examples)
+ |> prop_to_struct(:content, Content)
+ |> prop_to_struct(:schema, Schema)
+ end
+
+ defp to_struct(map_or_list, Parameters), do: embedded_ref_or_struct(map_or_list, Parameter)
+
+ defp to_struct(map, ServerVariable) do
+ struct_from_map(ServerVariable, map)
+ end
+
+ defp to_struct(map, ServerVariables) do
+ map
+ |> Map.new(fn {k, v} ->
+ {k, to_struct(v, ServerVariable)}
+ end)
+ end
+
+ defp to_struct(map, Server) do
+ Server
+ |> struct_from_map(map)
+ |> prop_to_struct(:variables, ServerVariables)
+ end
+
+ defp to_struct(list, Servers) when is_list(list) do
+ Enum.map(list, &to_struct(&1, Server))
+ end
+
+ defp to_struct(map, Response) do
+ Response
+ |> struct_from_map(map)
+ |> prop_to_struct(:headers, Headers)
+ |> prop_to_struct(:content, Content)
+ |> prop_to_struct(:links, Links)
+ end
+
+ defp to_struct(map, Responses), do: embedded_ref_or_struct(map, Response)
+
+ defp to_struct(map, MediaType) do
+ MediaType
+ |> struct_from_map(map)
+ |> prop_to_struct(:examples, Examples)
+ |> prop_to_struct(:encoding, Encoding)
+ |> prop_to_struct(:schema, Schema)
+ end
+
+ defp to_struct(map, Content) do
+ map
+ |> Map.new(fn {k, v} ->
+ {k, to_struct(v, MediaType)}
+ end)
+ end
+
+ defp to_struct(map, Encoding) do
+ map
+ |> Map.new(fn {k, v} ->
+ {k,
+ Encoding
+ |> struct_from_map(v)
+ |> convert_value_to_atom_if_present(:style)
+ |> prop_to_struct(:headers, Headers)}
+ end)
+ end
+
+ defp to_struct(map, Example), do: struct_from_map(Example, map)
+ defp to_struct(map_or_list, Examples), do: embedded_ref_or_struct(map_or_list, Example)
+
+ defp to_struct(map, Header) do
+ Header
+ |> struct_from_map(map)
+ |> prop_to_struct(:schema, Schema)
+ end
+
+ defp to_struct(map, Headers), do: embedded_ref_or_struct(map, Header)
+
+ defp to_struct(map, PathItem) do
+ PathItem
+ |> struct_from_map(map)
+ |> prop_to_struct(:delete, Operation)
+ |> prop_to_struct(:get, Operation)
+ |> prop_to_struct(:head, Operation)
+ |> prop_to_struct(:options, Operation)
+ |> prop_to_struct(:patch, Operation)
+ |> prop_to_struct(:post, Operation)
+ |> prop_to_struct(:put, Operation)
+ |> prop_to_struct(:trace, Operation)
+ |> prop_to_struct(:parameters, Parameters)
+ |> prop_to_struct(:servers, Servers)
+ end
+
+ defp to_struct(map, PathItems) do
+ map
+ |> Map.new(fn {k, v} ->
+ {k, to_struct(v, PathItem)}
+ end)
+ end
+
+ defp to_struct(map, Info) do
+ Info
+ |> struct_from_map(map)
+ |> prop_to_struct(:contact, Contact)
+ |> prop_to_struct(:license, License)
+ end
+
+ defp to_struct(list, mod) when is_list(list) and is_atom(mod),
+ do: Enum.map(list, &to_struct(&1, mod))
+
+ defp to_struct(map, module) when is_map(map) and is_atom(module),
+ do: struct_from_map(module, map)
+
+ defp prop_to_struct(map, key, mod) when is_map(map) and is_atom(key) and is_atom(mod) do
+ Map.update!(map, key, fn v ->
+ to_struct(v, mod)
+ end)
+ end
+end
diff --git a/test/open_api/decode_test.exs b/test/open_api/decode_test.exs
new file mode 100644
index 0000000..d2d1d0c
--- /dev/null
+++ b/test/open_api/decode_test.exs
@@ -0,0 +1,385 @@
+defmodule OpenApiSpex.OpenApi.DecodeTest do
+ use ExUnit.Case
+ use Plug.Test
+
+ alias OpenApiSpex.OpenApi
+
+ describe "OpenApiSpex.OpenApi.Decode.decode/1" do
+ test "OpenApi" do
+ # NOTE: This test could be split into many smaller tests, that is the goal!
+ # TODO: Move the spec to a setup below, where we could easily try a yaml version also
+ spec =
+ "./test/support/encoded_schema.json"
+ |> File.read!()
+ |> Jason.decode!()
+ |> OpenApiSpex.OpenApi.Decode.decode()
+
+ assert %OpenApi{
+ openapi: openapi,
+ info: info,
+ servers: servers,
+ paths: paths,
+ components: components,
+ security: security,
+ tags: tags,
+ externalDocs: externalDocs,
+ extensions: extensions
+ } = spec
+
+ assert "3.0.0" == openapi
+
+ assert %OpenApiSpex.Info{
+ title: _title,
+ version: _version,
+ description: _description,
+ contact: contact,
+ license: license
+ } = info
+
+ assert %OpenApiSpex.Contact{} = contact
+
+ assert %OpenApiSpex.License{} = license
+
+ assert nil == extensions
+
+ assert %OpenApiSpex.ExternalDocumentation{
+ description: _,
+ url: _
+ } = externalDocs
+
+ assert %OpenApiSpex.Components{
+ callbacks: callbacks,
+ schemas: schemas,
+ responses: responses,
+ examples: examples,
+ links: %{
+ "address" => link
+ },
+ requestBodies: requestBodies,
+ parameters: %{
+ "AcceptEncodingHeader" => components_parameters_parameter
+ },
+ securitySchemes: securitySchemes,
+ headers: %{
+ "api-version" => components_headers_header
+ }
+ } = components
+
+ assert %{
+ "test" => %OpenApiSpex.RequestBody{
+ description: "user to add to the system",
+ content: %{
+ "application/json" => media_type
+ },
+ required: false
+ }
+ } = requestBodies
+
+ assert %OpenApiSpex.MediaType{
+ schema: %OpenApiSpex.Reference{
+ "$ref": "#/components/schemas/User"
+ },
+ examples: %{
+ "user" => %OpenApiSpex.Example{
+ externalValue: "http://foo.bar/examples/user-example.json",
+ summary: "User Example",
+ value: nil,
+ description: nil
+ }
+ },
+ encoding: %{
+ "historyMetadata" => %OpenApiSpex.Encoding{
+ contentType: "application/xml; charset=utf-8",
+ style: :form,
+ explode: false,
+ allowReserved: false,
+ headers: %{
+ "X-Rate-Limit-Limit" => %OpenApiSpex.Header{
+ description: "The number of allowed requests in the current period",
+ schema: %OpenApiSpex.Schema{
+ type: :integer
+ }
+ }
+ }
+ }
+ },
+ example: nil
+ } = media_type
+
+ assert %{
+ "componentCallback" => componentCallback
+ } = callbacks
+
+ assert %{
+ "http://server-b.com?transactionId={$request.body#/id}" => %OpenApiSpex.PathItem{}
+ } = componentCallback
+
+ assert %{
+ "NotFound" => %OpenApiSpex.Response{
+ headers: %{
+ "X-Rate-Limit-Limit" => %OpenApiSpex.Header{
+ description: "The number of allowed requests in the current period",
+ schema: %OpenApiSpex.Schema{
+ type: :integer
+ }
+ }
+ },
+ content: %{
+ "application/json" => %OpenApiSpex.MediaType{
+ schema: %OpenApiSpex.Schema{
+ type: :string,
+ maxLength: 10
+ }
+ }
+ },
+ links: %{
+ "test" => %OpenApiSpex.Link{
+ operationId: "response-link-test"
+ }
+ },
+ description: "Entity not found."
+ }
+ } == responses
+
+ assert %{
+ "foo" => %OpenApiSpex.Example{}
+ } = examples
+
+ assert %OpenApiSpex.Parameter{
+ description: nil,
+ name: :"accept-encoding",
+ in: :header,
+ required: false,
+ allowEmptyValue: true,
+ schema: %OpenApiSpex.Schema{
+ example: "gzip",
+ type: :string
+ }
+ } == components_parameters_parameter
+
+ assert %{"User" => user_schema, "Admin" => admin_schema} = schemas
+
+ assert %OpenApiSpex.Schema{
+ allOf: [
+ %OpenApiSpex.Reference{
+ "$ref": "#/components/schemas/User"
+ },
+ %OpenApiSpex.Reference{
+ "$ref": "#/components/schemas/SpecialUser"
+ }
+ ],
+ discriminator: %OpenApiSpex.Discriminator{
+ propertyName: "userType"
+ }
+ } == admin_schema
+
+ assert %OpenApiSpex.Schema{
+ nullable: false,
+ readOnly: false,
+ writeOnly: false,
+ deprecated: false,
+ example: %{},
+ externalDocs: %OpenApiSpex.ExternalDocumentation{
+ description: "Find more info here",
+ url: "https://example.com"
+ },
+ properties: %{
+ first_name: %OpenApiSpex.Schema{
+ xml: %OpenApiSpex.Xml{
+ namespace: "http://example.com/schema/sample",
+ prefix: "sample"
+ }
+ }
+ }
+ } = user_schema
+
+ assert %OpenApiSpex.Link{
+ description: nil,
+ operationRef: nil,
+ operationId: "test",
+ requestBody: %OpenApiSpex.RequestBody{
+ description: "link payload",
+ content: %{
+ "application/json" => %OpenApiSpex.MediaType{
+ schema: %OpenApiSpex.Schema{}
+ }
+ }
+ },
+ parameters: %{
+ "ContentTypeHeader" => %OpenApiSpex.Reference{
+ "$ref": "#/components/parameters/ContentTypeHeader"
+ }
+ },
+ server: %OpenApiSpex.Server{
+ description: "Development server",
+ url: "https://development.gigantic-server.com/v1",
+ variables: %{}
+ }
+ } == link
+
+ assert %{
+ "api_key" => api_key_security_scheme,
+ "petstore_auth" => petstore_auth_security_scheme
+ } = securitySchemes
+
+ assert %OpenApiSpex.SecurityScheme{
+ flows: oauth_flows
+ } = petstore_auth_security_scheme
+
+ assert %OpenApiSpex.OAuthFlows{
+ implicit: oauth_flow
+ } = oauth_flows
+
+ assert %OpenApiSpex.OAuthFlow{
+ authorizationUrl: "http://example.org/api/oauth/dialog",
+ tokenUrl: nil,
+ refreshUrl: nil,
+ scopes: %{
+ "read:pets" => "read your pets",
+ "write:pets" => "modify pets in your account"
+ }
+ } = oauth_flow
+
+ assert %OpenApiSpex.Header{
+ description: "The version of the api to be used",
+ schema: %OpenApiSpex.Schema{
+ type: :string,
+ enum: ["beta"]
+ }
+ } == components_headers_header
+
+ assert [server] = servers
+
+ assert %OpenApiSpex.Server{
+ description: "Development server",
+ url: "https://development.gigantic-server.com/v1",
+ variables: serverVariables
+ } = server
+
+ assert %{
+ "username" => %OpenApiSpex.ServerVariable{
+ default: "demo",
+ description:
+ "this value is assigned by the service provider, in this example `gigantic-server.com`",
+ enum: nil
+ }
+ } = serverVariables
+
+ assert [tag] = tags
+
+ assert %OpenApiSpex.Tag{
+ description: "Pets operations",
+ externalDocs: %OpenApiSpex.ExternalDocumentation{
+ description: "Find more info here",
+ url: "https://example.com"
+ },
+ name: "pet"
+ } == tag
+
+ assert [
+ %{
+ "petstore_auth" => ["write:pets", "read:pets"]
+ }
+ ] == security
+
+ assert %{
+ "/example" => %OpenApiSpex.PathItem{
+ summary: "/example summary",
+ description: "/example description",
+ servers: [%OpenApiSpex.Server{}],
+ parameters: [
+ %OpenApiSpex.Reference{
+ "$ref": "#/components/parameters/ContentTypeHeader"
+ }
+ ],
+ post: %OpenApiSpex.Operation{
+ parameters: [
+ %OpenApiSpex.Reference{},
+ %OpenApiSpex.Reference{},
+ %OpenApiSpex.Parameter{}
+ ],
+ deprecated: false,
+ operationId: "example-post-test",
+ requestBody: requestBody,
+ callbacks: operationCallbacks,
+ responses: operationResponses,
+ security: operationSecurity,
+ tags: ["test"],
+ summary: "/example post summary",
+ description: "/example post description",
+ externalDocs: %OpenApiSpex.ExternalDocumentation{
+ description: "Find more info here",
+ url: "https://example.com"
+ }
+ }
+ }
+ } = paths
+
+ assert [
+ %{
+ "petstore_auth" => ["write:pets"]
+ }
+ ] == operationSecurity
+
+ assert %{
+ "200" => %OpenApiSpex.Response{}
+ } = operationResponses
+
+ assert %{
+ "operationCallback" => %{
+ "http://server-a.com?transactionId={$request.body#/id}" =>
+ %OpenApiSpex.PathItem{}
+ }
+ } = operationCallbacks
+
+ assert %OpenApiSpex.Schema{
+ properties: properties
+ } =
+ get_in(
+ requestBody,
+ [:content, "application/json", :schema]
+ |> Enum.map(&Access.key/1)
+ )
+
+ passengers =
+ get_in(
+ properties,
+ [:data, :properties, :passengers]
+ |> Enum.map(&Access.key/1)
+ )
+
+ assert %OpenApiSpex.Schema{} = passengers
+
+ assert %OpenApiSpex.Schema{
+ type: :string,
+ enum: ["adult", "child"]
+ } =
+ get_in(
+ passengers,
+ [:items, :properties, :type]
+ |> Enum.map(&Access.key/1)
+ )
+
+ test_conn =
+ conn(:post, "/example?myParam=1", %{
+ "data" => %{
+ "first_name" => "Bob",
+ "given_name" => "Builder",
+ "phone_number" => "+441111111111"
+ }
+ })
+ |> put_req_header("content-type", "application/json")
+ |> put_req_header("accept-encoding", "gzip")
+
+ test_conn = fetch_query_params(test_conn)
+
+ assert {:ok, validation_result} =
+ OpenApiSpex.cast_and_validate(
+ spec,
+ spec.paths["/example"].post,
+ test_conn,
+ "application/json"
+ )
+ end
+ end
+end
diff --git a/test/support/encoded_schema.json b/test/support/encoded_schema.json
new file mode 100644
index 0000000..e73c58f
--- /dev/null
+++ b/test/support/encoded_schema.json
@@ -0,0 +1,485 @@
+{
+ "openapi": "3.0.0",
+ "info": {
+ "contact": {},
+ "description": "test description",
+ "license": {
+ "name": "test"
+ },
+ "title": "Duffel Technology Ltd.",
+ "version": "1.0.0"
+ },
+ "x-extension": {
+ "value": "haha"
+ },
+ "servers": [
+ {
+ "description": "Development server",
+ "url": "https://development.gigantic-server.com/v1",
+ "variables": {
+ "username": {
+ "default": "demo",
+ "description": "this value is assigned by the service provider, in this example `gigantic-server.com`"
+ }
+ }
+ }
+ ],
+ "components": {
+ "parameters": {
+ "ContentTypeHeader": {
+ "name": "content-type",
+ "in": "header",
+ "schema": {
+ "type": "string",
+ "example": "application/json"
+ },
+ "required": false
+ },
+ "AcceptEncodingHeader": {
+ "in": "header",
+ "allowEmptyValue": true,
+ "name": "accept-encoding",
+ "required": false,
+ "schema": {
+ "example": "gzip",
+ "type": "string"
+ }
+ }
+ },
+ "headers": {
+ "api-version": {
+ "description": "The version of the api to be used",
+ "schema": {
+ "type": "string",
+ "enum": [
+ "beta"
+ ]
+ }
+ }
+ },
+ "callbacks": {
+ "componentCallback": {
+ "http://server-b.com?transactionId={$request.body#/id}": {
+ "post": {
+ "requestBody": {
+ "description": "callback payload",
+ "content": {
+ "application/json": {
+ "schema": {
+ "maxLength": 10,
+ "type": "string"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": ""
+ }
+ }
+ }
+ }
+ }
+ },
+ "securitySchemes": {
+ "api_key": {
+ "type": "apiKey",
+ "name": "api_key",
+ "in": "header"
+ },
+ "petstore_auth": {
+ "type": "oauth2",
+ "flows": {
+ "implicit": {
+ "authorizationUrl": "http://example.org/api/oauth/dialog",
+ "scopes": {
+ "write:pets": "modify pets in your account",
+ "read:pets": "read your pets"
+ }
+ },
+ "authorizationCode": {
+ "authorizationUrl": "https://example.com/api/oauth/dialog",
+ "tokenUrl": "https://example.com/api/oauth/token",
+ "scopes": {
+ "write:pets": "modify pets in your account",
+ "read:pets": "read your pets"
+ }
+ },
+ "clientCredentials": {
+ "tokenUrl": "https://example.com/api/oauth/token",
+ "scopes": {
+ "write:pets": "modify pets in your account",
+ "read:pets": "read your pets"
+ }
+ },
+ "password": {
+ "tokenUrl": "https://example.com/api/oauth/token",
+ "scopes": {
+ "write:pets": "modify pets in your account",
+ "read:pets": "read your pets"
+ }
+ }
+ }
+ }
+ },
+ "schemas": {
+ "User": {
+ "nullable": false,
+ "readOnly": false,
+ "writeOnly": false,
+ "deprecated": false,
+ "externalDocs": {
+ "description": "Find more info here",
+ "url": "https://example.com"
+ },
+ "example": {
+ "first_name": "Jane",
+ "id": 42,
+ "last_name": "Doe",
+ "phone_number": null
+ },
+ "properties": {
+ "first_name": {
+ "type": "string",
+ "xml": {
+ "namespace": "http://example.com/schema/sample",
+ "prefix": "sample"
+ }
+ },
+ "id": {
+ "type": "integer"
+ },
+ "last_name": {
+ "type": "string"
+ },
+ "phone_number": {
+ "nullable": true,
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "SpecialUser": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/User"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "admin": {
+ "type": "boolean"
+ }
+ }
+ }
+ ]
+ },
+ "Admin": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/User"
+ },
+ {
+ "$ref": "#/components/schemas/SpecialUser"
+ }
+ ],
+ "discriminator": {
+ "propertyName": "userType"
+ }
+ }
+ },
+ "links": {
+ "address": {
+ "operationId": "test",
+ "parameters": {
+ "ContentTypeHeader": {
+ "$ref": "#/components/parameters/ContentTypeHeader"
+ }
+ },
+ "requestBody": {
+ "description": "link payload",
+ "content": {
+ "application/json": {
+ "schema": {
+ "schema": {
+ "maxLength": 10,
+ "type": "string"
+ }
+ }
+ }
+ }
+ },
+ "server": {
+ "description": "Development server",
+ "url": "https://development.gigantic-server.com/v1"
+ }
+ }
+ },
+ "responses": {
+ "NotFound": {
+ "description": "Entity not found.",
+ "headers": {
+ "X-Rate-Limit-Limit": {
+ "description": "The number of allowed requests in the current period",
+ "schema": {
+ "type": "integer"
+ }
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "maxLength": 10,
+ "type": "string"
+ }
+ }
+ },
+ "links": {
+ "test": {
+ "operationId": "response-link-test"
+ }
+ }
+ }
+ },
+ "examples": {
+ "foo": {
+ "summary": "A foo example",
+ "value": "{\"foo\": \"bar\"}"
+ }
+ },
+ "requestBodies": {
+ "test": {
+ "description": "user to add to the system",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/User"
+ },
+ "examples": {
+ "user": {
+ "summary": "User Example",
+ "externalValue": "http://foo.bar/examples/user-example.json"
+ }
+ },
+ "encoding": {
+ "historyMetadata": {
+ "contentType": "application/xml; charset=utf-8",
+ "allowReserved": false,
+ "explode": false,
+ "style": "form",
+ "headers": {
+ "X-Rate-Limit-Limit": {
+ "description": "The number of allowed requests in the current period",
+ "schema": {
+ "type": "integer"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "required": false
+ }
+ }
+ },
+ "paths": {
+ "/example": {
+ "summary": "/example summary",
+ "description": "/example description",
+ "post": {
+ "operationId": "example-post-test",
+ "callbacks": {
+ "operationCallback": {
+ "http://server-a.com?transactionId={$request.body#/id}": {
+ "post": {
+ "requestBody": {
+ "description": "callback payload",
+ "content": {
+ "application/json": {
+ "schema": {
+ "maxLength": 10,
+ "type": "string"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "test description"
+ }
+ }
+ }
+ }
+ }
+ },
+ "deprecated": false,
+ "parameters": [
+ {
+ "$ref": "#/components/parameters/ContentTypeHeader"
+ },
+ {
+ "$ref": "#/components/parameters/AcceptEncodingHeader"
+ },
+ {
+ "allowEmptyValue": false,
+ "deprecated": false,
+ "description": "My very own parameter",
+ "in": "query",
+ "name": "myParam",
+ "required": true,
+ "schema": {
+ "maxLength": 10,
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "examples": {
+ "user": {
+ "externalValue": "http://foo.bar/examples/user-example.json",
+ "summary": "User Example"
+ }
+ },
+ "schema": {
+ "properties": {
+ "data": {
+ "properties": {
+ "first_name": {
+ "maxLength": 10,
+ "type": "string"
+ },
+ "given_name": {
+ "maxLength": 32,
+ "type": "string"
+ },
+ "passengers": {
+ "description": "The passengers who want to travel",
+ "items": {
+ "properties": {
+ "id": {
+ "description": "A custom identifier for the passenger, unique within this Offer Request. If not specified, Duffel will generate its own ID.",
+ "example": "passenger_0",
+ "type": "string"
+ },
+ "type": {
+ "description": "The type of the passenger",
+ "enum": [
+ "adult",
+ "child"
+ ],
+ "example": "adult",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "phone_number": {
+ "$ref": "#/components/schemas/User/properties/phone_number"
+ },
+ "some_number": {
+ "allOf": [
+ {
+ "maxLength": 10,
+ "type": "string"
+ },
+ {
+ "minLength": 2,
+ "type": "string"
+ }
+ ]
+ }
+ },
+ "required": [
+ "first_name",
+ "given_name"
+ ],
+ "type": "object"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "type": "object"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "example": {
+ "first_name": "John",
+ "id": 678,
+ "last_name": "Doe",
+ "phone_number": null
+ }
+ }
+ },
+ "description": "An example"
+ }
+ },
+ "security": [
+ {
+ "petstore_auth": [
+ "write:pets"
+ ]
+ }
+ ],
+ "tags": [
+ "test"
+ ],
+ "summary": "/example post summary",
+ "description": "/example post description",
+ "externalDocs": {
+ "description": "Find more info here",
+ "url": "https://example.com"
+ }
+ },
+ "servers": [
+ {
+ "description": "Development server",
+ "url": "https://development.gigantic-server.com/v1",
+ "variables": {
+ "username": {
+ "default": "demo",
+ "description": "this value is assigned by the service provider, in this example `gigantic-server.com`"
+ }
+ }
+ }
+ ],
+ "parameters": [
+ {
+ "$ref": "#/components/parameters/ContentTypeHeader"
+ }
+ ]
+ }
+ },
+ "security": [
+ {
+ "petstore_auth": [
+ "write:pets",
+ "read:pets"
+ ]
+ }
+ ],
+ "tags": [
+ {
+ "name": "pet",
+ "description": "Pets operations",
+ "externalDocs": {
+ "description": "Find more info here",
+ "url": "https://example.com"
+ }
+ }
+ ],
+ "externalDocs": {
+ "description": "Find more info here",
+ "url": "https://example.com"
+ }
+}
\ No newline at end of file

File Metadata

Mime Type
text/x-diff
Expires
Mon, Nov 25, 5:56 AM (1 d, 7 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
39649
Default Alt Text
(64 KB)

Event Timeline