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

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
subsaharancoder
I’ve followed the Phoenix LiveView file upload code here Uploads — Phoenix LiveView v1.0.0-rc.7 and so far everything works just fine wit...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
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
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews