Page MenuHomePhorge

No OneTemporary

Size
24 KB
Referenced Files
None
Subscribers
None
diff --git a/README.md b/README.md
index 9cbea50..c04d75a 100644
--- a/README.md
+++ b/README.md
@@ -1,384 +1,384 @@
# 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
```
## 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.Test.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.Test.Assertions` also:
+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/test/schema_test.exs b/test/schema_test.exs
index 8007155..e735eb2 100644
--- a/test/schema_test.exs
+++ b/test/schema_test.exs
@@ -1,474 +1,474 @@
defmodule OpenApiSpex.SchemaTest do
use ExUnit.Case
alias OpenApiSpex.Schema
alias OpenApiSpexTest.{ApiSpec, Schemas}
- import OpenApiSpex.Test.Assertions
+ import OpenApiSpex.TestAssertions
doctest Schema
describe "schema/1" do
test "EntityWithDict Schema example matches schema" do
api_spec = ApiSpec.spec()
assert_schema(Schemas.EntityWithDict.schema().example, "EntityWithDict", api_spec)
end
test "User Schema example matches schema" do
spec = ApiSpec.spec()
assert_schema(Schemas.User.schema().example, "User", spec)
assert_schema(Schemas.UserRequest.schema().example, "UserRequest", spec)
assert_schema(Schemas.UserResponse.schema().example, "UserResponse", spec)
assert_schema(Schemas.UsersResponse.schema().example, "UsersResponse", spec)
end
end
describe "cast/3" do
test "cast request schema" do
api_spec = ApiSpec.spec()
schemas = api_spec.components.schemas
user_request_schema = schemas["UserRequest"]
input = %{
"user" => %{
"id" => 123,
"name" => "asdf",
"email" => "foo@bar.com",
"updated_at" => "2017-09-12T14:44:55Z"
}
}
{:ok, output} = Schema.cast(user_request_schema, input, schemas)
assert output == %OpenApiSpexTest.Schemas.UserRequest{
user: %OpenApiSpexTest.Schemas.User{
id: 123,
name: "asdf",
email: "foo@bar.com",
updated_at: DateTime.from_naive!(~N[2017-09-12T14:44:55], "Etc/UTC")
}
}
end
test "cast request schema with unexpected fields returns error" do
api_spec = ApiSpec.spec()
schemas = api_spec.components.schemas
user_request_schema = schemas["UserRequest"]
input = %{
"user" => %{
"id" => 123,
"name" => "asdf",
"email" => "foo@bar.com",
"updated_at" => "2017-09-12T14:44:55Z",
"unexpected_field" => "unexpected value"
}
}
assert {:error, _} = Schema.cast(user_request_schema, input, schemas)
end
test "Cast Cat from Pet schema" do
api_spec = ApiSpec.spec()
schemas = api_spec.components.schemas
pet_schema = schemas["Pet"]
input = %{
"pet_type" => "Cat",
"meow" => "meow"
}
assert {:ok, %Schemas.Cat{meow: "meow", pet_type: "Cat"}} =
Schema.cast(pet_schema, input, schemas)
end
test "Cast Dog from oneOf [cat, dog] schema" do
api_spec = ApiSpec.spec()
schemas = api_spec.components.schemas
cat_or_dog = Map.fetch!(schemas, "CatOrDog")
input = %{
"pet_type" => "Dog",
"bark" => "bowow"
}
assert {:ok, %Schemas.Dog{bark: "bowow", pet_type: "Dog"}} =
Schema.cast(cat_or_dog, input, schemas)
end
test "Cast Cat from oneOf [cat, dog] schema" do
api_spec = ApiSpec.spec()
schemas = api_spec.components.schemas
cat_or_dog = Map.fetch!(schemas, "CatOrDog")
input = %{
"pet_type" => "Cat",
"meow" => "meow"
}
assert {:ok, %Schemas.Cat{meow: "meow", pet_type: "Cat"}} =
Schema.cast(cat_or_dog, input, schemas)
end
test "Cast number to string or number" do
schema = %Schema{
oneOf: [
%Schema{type: :number},
%Schema{type: :string}
]
}
result = Schema.cast(schema, "123", %{})
assert {:ok, 123.0} = result
end
test "Cast integer to float" do
schema = %Schema{type: :number}
assert Schema.cast(schema, 123, %{}) === {:ok, 123.0}
end
test "Cast string to oneOf number or date-time" do
schema = %Schema{
oneOf: [
%Schema{type: :number},
%Schema{type: :string, format: :"date-time"}
]
}
assert {:ok, %DateTime{}} = Schema.cast(schema, "2018-04-01T12:34:56Z", %{})
end
test "Cast string to anyOf number or date-time" do
schema = %Schema{
oneOf: [
%Schema{type: :number},
%Schema{type: :string, format: :"date-time"}
]
}
assert {:ok, %DateTime{}} = Schema.cast(schema, "2018-04-01T12:34:56Z", %{})
end
end
describe "Integer validation" do
test "Validate schema type integer when value is object" do
schema = %Schema{
type: :integer
}
assert {:error, _} = Schema.validate(schema, %{}, %{})
end
end
describe "Number validation" do
test "Validate schema type number when value is object" do
schema = %Schema{
type: :integer
}
assert {:error, _} = Schema.validate(schema, %{}, %{})
end
test "Validate schema type number when value is exclusive" do
schema = %Schema{
type: :integer,
minimum: -1,
maximum: 1,
exclusiveMinimum: true,
exclusiveMaximum: true
}
assert {:error, _} = Schema.validate(schema, 1, %{})
assert {:error, _} = Schema.validate(schema, -1, %{})
end
end
describe "String validation" do
test "Validate schema type string when value is object" do
schema = %Schema{
type: :string
}
assert {:error, _} = Schema.validate(schema, %{}, %{})
end
test "Validate schema type string when value is DateTime" do
schema = %Schema{
type: :string
}
assert {:error, _} = Schema.validate(schema, DateTime.utc_now(), %{})
end
test "Validate non-empty string with expected value" do
schema = %Schema{type: :string, minLength: 1}
assert :ok = Schema.validate(schema, "BLIP", %{})
end
end
describe "DateTime validation" do
test "Validate schema type string with format date-time when value is DateTime" do
schema = %Schema{
type: :string,
format: :"date-time"
}
assert :ok = Schema.validate(schema, DateTime.utc_now(), %{})
end
end
describe "Date Validation" do
test "Validate schema type string with format date when value is Date" do
schema = %Schema{
type: :string,
format: :date
}
assert :ok = Schema.validate(schema, Date.utc_today(), %{})
end
end
describe "Enum validation" do
test "Validate string enum with unexpected value" do
schema = %Schema{
type: :string,
enum: ["foo", "bar"]
}
assert {:error, _} = Schema.validate(schema, "baz", %{})
end
test "Validate string enum with expected value" do
schema = %Schema{
type: :string,
enum: ["foo", "bar"]
}
assert :ok = Schema.validate(schema, "bar", %{})
end
end
describe "Object validation" do
test "Validate schema type object when value is array" do
schema = %Schema{
type: :object
}
assert {:error, _} = Schema.validate(schema, [], %{})
end
test "Validate schema type object when value is DateTime" do
schema = %Schema{
type: :object
}
assert {:error, _} = Schema.validate(schema, DateTime.utc_now(), %{})
end
end
describe "Array validation" do
test "Validate schema type array when value is object" do
schema = %Schema{
type: :array
}
assert {:error, _} = Schema.validate(schema, %{}, %{})
end
end
describe "Boolean validation" do
test "Validate schema type boolean when value is object" do
schema = %Schema{
type: :boolean
}
assert {:error, _} = Schema.validate(schema, %{}, %{})
end
end
describe "AnyOf validation" do
test "Validate anyOf schema with valid value" do
schema = %Schema{
anyOf: [
%Schema{type: :array},
%Schema{type: :string}
]
}
assert :ok = Schema.validate(schema, "a string", %{})
end
test "Validate anyOf with value matching more than one schema" do
schema = %Schema{
anyOf: [
%Schema{type: :number},
%Schema{type: :integer}
]
}
assert :ok = Schema.validate(schema, 42, %{})
end
test "Validate anyOf schema with invalid value" do
schema = %Schema{
anyOf: [
%Schema{type: :string},
%Schema{type: :array}
]
}
assert {:error, _} = Schema.validate(schema, 3.14159, %{})
end
end
describe "OneOf validation" do
test "Validate oneOf schema with valid value" do
schema = %Schema{
oneOf: [
%Schema{type: :string},
%Schema{type: :array}
]
}
assert :ok = Schema.validate(schema, [1, 2, 3], %{})
end
test "Validate oneOf schema with invalid value" do
schema = %Schema{
oneOf: [
%Schema{type: :string},
%Schema{type: :array}
]
}
assert {:error, _} = Schema.validate(schema, 3.14159, %{})
end
test "Validate oneOf schema when matching multiple schemas" do
schema = %Schema{
oneOf: [
%Schema{type: :object, properties: %{a: %Schema{type: :string}}},
%Schema{type: :object, properties: %{b: %Schema{type: :string}}}
]
}
assert {:error, _} = Schema.validate(schema, %{a: "a", b: "b"}, %{})
end
end
describe "AllOf validation" do
test "Validate allOf schema with valid value" do
schema = %Schema{
allOf: [
%Schema{type: :object, properties: %{a: %Schema{type: :string}}},
%Schema{type: :object, properties: %{b: %Schema{type: :string}}}
]
}
assert :ok = Schema.validate(schema, %{a: "a", b: "b"}, %{})
end
test "Validate allOf schema with invalid value" do
schema = %Schema{
allOf: [
%Schema{type: :object, properties: %{a: %Schema{type: :string}}},
%Schema{type: :object, properties: %{b: %Schema{type: :string}}}
]
}
assert {:error, msg} = Schema.validate(schema, %{a: 1, b: 2}, %{})
assert msg =~ "#/a"
assert msg =~ "#/b"
end
test "Validate allOf with value matching not all schemas" do
schema = %Schema{
allOf: [
%Schema{
type: :integer,
minimum: 5
},
%Schema{
type: :integer,
maximum: 40
}
]
}
assert {:error, _} = Schema.validate(schema, 42, %{})
end
end
describe "Not validation" do
test "Validate not schema with valid value" do
schema = %Schema{
not: %Schema{type: :object}
}
assert :ok = Schema.validate(schema, 1, %{})
end
test "Validate not schema with invalid value" do
schema = %Schema{
not: %Schema{type: :object}
}
assert {:error, _} = Schema.validate(schema, %{a: 1}, %{})
end
test "Verify 'not' validation" do
schema = %Schema{not: %Schema{type: :boolean}}
assert :ok = Schema.validate(schema, 42, %{})
assert :ok = Schema.validate(schema, "42", %{})
assert :ok = Schema.validate(schema, nil, %{})
assert :ok = Schema.validate(schema, 4.2, %{})
assert :ok = Schema.validate(schema, [4], %{})
assert :ok = Schema.validate(schema, %{}, %{})
assert {:error, _} = Schema.validate(schema, true, %{})
assert {:error, _} = Schema.validate(schema, false, %{})
end
end
describe "Nullable validation" do
test "Validate nullable-ified with expected value" do
schema = %Schema{
nullable: true,
type: :string,
minLength: 1
}
assert :ok = Schema.validate(schema, "BLIP", %{})
end
test "Validate nullable with expected value" do
schema = %Schema{type: :string, nullable: true}
assert :ok = Schema.validate(schema, nil, %{})
end
test "Validate nullable with unexpected value" do
schema = %Schema{type: :string, nullable: true}
assert :ok = Schema.validate(schema, "bla", %{})
end
end
describe "Default property value" do
test "Available in structure" do
size = %Schemas.Size{}
assert "cm" == size.unit
assert 100 == size.value
end
test "Available after cast" do
api_spec = ApiSpec.spec()
schemas = api_spec.components.schemas
size = Map.fetch!(schemas, "Size")
assert {:ok, %Schemas.Size{value: 100, unit: "cm"}} ==
Schema.cast(size, %{}, schemas)
assert {:ok, %Schemas.Size{value: 110, unit: "cm"}} ==
Schema.cast(size, %{value: 110}, schemas)
end
end
end

File Metadata

Mime Type
text/x-diff
Expires
Wed, Nov 27, 7:58 PM (1 d, 17 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
40735
Default Alt Text
(24 KB)

Event Timeline