earthtrip

earthtrip

Hi all -

I’m getting back into Phoenix/Elixir after a few year hiatus and have started work on an OpenAPI based application that I would like to have schema request validation support for.
A caveat is that the schema is in YAML and due to restrictions in workflow I can’t just write it in line into the code like the OpenApiSpex README examples show. But there is support for reading the schema in from YAML at runtime which I have working.

The problem I’m running into is the docs don’t clearly describe how to leverage the OpenApiSpex struct that gets generated as if it was hand coded into the Elixir controllers/modules as it is in the documentation.

In order to rule out a potential issues the particular schema I’m using I took the venerable PetStore schema from the OpenAPI repo as a sample and created a phoenix project that uses that and reads it in and tries to use ControllerSpecs to validate it automatically.

From the documentation I created this module

defmodule PetstoreApiWeb.ApiSpec do
  @moduledoc false

  alias OpenApiSpex.{Components, Info, OpenApi, Paths, Server}
  alias PetstoreApiWeb.{Endpoint, Router}
  @behaviour OpenApi

  @impl OpenApi
  def spec do
    open_api_spec_from_yaml =
      "openapi/petstore.yaml"
      |> YamlElixir.read_all_from_file!()
      |> List.first()
      |> OpenApiSpex.OpenApi.Decode.decode()

    # open_api_spec_from_yaml
    # Discover request/response schemas from path specs
    open_api_spec_from_yaml |> OpenApiSpex.resolve_schema_modules()
  end
end

and then in my controller I have this stubbed in

defmodule PetstoreApiWeb.PetsController do
  use PetstoreApiWeb, :controller
  use OpenApiSpex.ControllerSpecs

  alias PetstoreApiWeb.Schemas.{
    Pet
  }

  plug(OpenApiSpex.Plug.CastAndValidate,
    json_render_error_v2: true
  )

  operation(:create, PetstoreApiWeb.ApiSpec.spec().paths["/pets"].post)

  def create(conn, _params) do
      text(conn, "GOT HERE")
  end

But when I run mix phx.server it fails to compile with this error

== Compilation error in file lib/petstore_api_web/controllers/pets_controller.ex ==
** (Protocol.UndefinedError) protocol Enumerable not implemented for %OpenApiSpex.Operation{tags: ["pets"], summary: "Create a pet", description: nil, externalDocs: nil, operationId: "createPets", parameters: [], requestBody: %OpenApiSpex.RequestBody{description: nil, content: %{"application/json" => %OpenApiSpex.MediaType{schema: %OpenApiSpex.Reference{"$ref": "#/components/schemas/Pet"}, example: nil, examples: nil, encoding: nil, extensions: nil}}, extensions: nil, required: true}, responses: %{"201" => %OpenApiSpex.Response{description: "Null response", headers: nil, content: nil, links: nil, extensions: nil}, "default" => %OpenApiSpex.Response{description: "unexpected error", headers: nil, content: %{"application/json" => %OpenApiSpex.MediaType{schema: %OpenApiSpex.Reference{"$ref": "#/components/schemas/Error"}, example: nil, examples: nil, encoding: nil, extensions: nil}}, links: nil, extensions: nil}}, callbacks: %{}, deprecated: false, security: nil, servers: nil, extensions: nil} of type OpenApiSpex.Operation (a struct)
    (elixir 1.15.7) lib/enum.ex:1: Enumerable.impl_for!/1
    (elixir 1.15.7) lib/enum.ex:166: Enumerable.reduce/3
    (elixir 1.15.7) lib/enum.ex:4387: Enum.reverse/1
    (elixir 1.15.7) lib/enum.ex:3702: Enum.to_list/1
    (elixir 1.15.7) lib/map.ex:224: Map.new_from_enum/1
    (open_api_spex 3.18.0) lib/open_api_spex/controller_specs.ex:378: OpenApiSpex.ControllerSpecs.operation_spec/3
    lib/petstore_api_web/controllers/pets_controller.ex:13: (module)

Which is the same error I get when I try and attempt with my API schema.

This is my router.ex as well and I’m able to successfully render the swagger docs if I remove the OpenApiSpex components from my Pets controller.

defmodule PetstoreApiWeb.Router do
  use PetstoreApiWeb, :router

  pipeline :browser do
    plug(:accepts, ["html"])
  end

  pipeline :api do
    plug(:accepts, ["json"])
    plug(OpenApiSpex.Plug.PutApiSpec, module: PetstoreApiWeb.ApiSpec)
  end

  scope "/" do
    # Use the default browser stack
    pipe_through(:browser)
    get("/swaggerui", OpenApiSpex.Plug.SwaggerUI, path: "/api/openapi")
  end

  scope "/api" do
    pipe_through(:api)
    get("/openapi", OpenApiSpex.Plug.RenderSpec, [])
    post("/pets", PetstoreApiWeb.PetsController, :create)
  end
end

If anyone can possibly steer me out of this I’d appreciate it. My use case requires that I have some form of schema validation and I just want to make sure this will work by parsing the YAML into the OpenApiSpex struct otherwise I’m going to have to go a different route. Comparing the output of the OpenApiSpex struct to what is written in the code examples I can’t see anything obviously different either so it seems like it “should work”.

Thanks for any help!

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews