Giter Club home page Giter Club logo

apical's Introduction

Apical

test status

Elixir Routers from OpenAPI schemas

Installation

This package can be installed by adding apical to your list of dependencies in mix.exs:

Exonerate is a compile-time dependency. If you don't include this in your Mix.exs, there will be unwanted compiler warnings.

def deps do
  [
     {:apical, "~> 0.2.1"},
     {:exonerate, "~> 1.1.2", runtime: Mix.env() != :prod}
  ]
end

If you think you might need to recompile your router in production, remove the runtime option on Exonerate.

Basic use

For the following router module:

defmodule MyProjectWeb.ApiRouter do
    require Apical

    Apical.router_from_string(
      """
      openapi: 3.1.0
      info:
        title: My API
        version: 1.0.0
      paths:
        "/":
          get:
            operationId: getOperation
            responses:
              "200":
                description: OK
      """,
      controller: MyProjectWeb.ApiController,
      encoding: "application/yaml"
    )
end

You would connect this to your endpoint as follows:

defmodule MyProjectWeb.ApiEndpoint do
  use Phoenix.Endpoint, otp_app: :my_project

  plug(MyProjectWeb.ApiRouter)
end

And compose a controller as follows:

defmodule MyProjectWeb.ApiController do
  use Phoenix.Controller

  alias Plug.Conn

  # NOTE THE CASING BELOW:
  def getOperation(conn, _params) do
    Conn.send_resp(conn, 200, "OK")
  end
end

From file:

You may also generate a router from a file:

defmodule MyProjectWeb.ApiRouter do
    require Apical

    Apical.router_from_file("priv/assets/api/openapi.v1.yaml",
      controller: MyProjectWeb.ApiController
    )
end

Embedding inside of an existing router

You may also embed apical inside of an existing phoenix router:

scope "/api", MyProjectWeb.Api do
  require Apical

  Apical.router_from_file("priv/assets/api/openapi.v1.yaml",
    controller: MyProjectWeb.ApiController)
end

If you are embedding Apical in an existing router, be sure to delete the following lines from the phoenix endpoint:

plug Plug.Parsers,
  parsers: [:urlencoded, :multipart, :json],
  pass: ["*/*"],
  json_decoder: Phoenix.json_library()

As Apical will do its own parsing.

Using it in tests:

If you're using OpenAPI as a client, you can use Apical to test that your request wrapper conforms to the client schema:

https://hexdocs.pm/apical/apical-for-testing.html

Advanced usage

For more advanced usage, consult the tests in the test directory. Guides will be provided in the next version of apical

Documentation

Documentation can be found at https://hexdocs.pm/apical.

apical's People

Contributors

ityonemo avatar sleipnir avatar kianmeng avatar

Stargazers

 avatar Tres DuBiel avatar Enrique Fernández avatar Clay avatar  avatar Stibbs avatar Andrew Combs avatar ali avatar Uzo avatar Matt Lambie avatar kmylo avatar Niranjan Anandkumar avatar Jean Moggee avatar  avatar Marcus Hays avatar Matthew Pope avatar Jason Axelson avatar Vivian Meneses avatar Tom Zellman avatar Josh Price avatar Frederik Schönfeldt avatar Nicholas Moen avatar Ernesto Malave avatar Daniel Bonfim avatar Vincent Bach avatar Sebastian Henao avatar Camilo avatar Bogdan Mircea avatar marcos ferreira avatar  avatar Grant McLendon avatar Oleg Blyednov avatar Weslei Juan Novaes Pereira avatar Bruno Antunes avatar Zack avatar David McKeone avatar Sebastian Fey avatar Franklin Rakotomalala avatar Felipe Menegazzi avatar Camelo avatar Ievgen Pyrogov avatar DJ Carpenter avatar Ethan Sherbondy avatar peter madsen-mygdal avatar Mathew Garland avatar Christopher Keele avatar Kramer Hampton avatar Gonçalo Mendes Cabrita avatar Patrick Smith avatar  avatar Jeremy Brayton avatar  avatar Paulo Daniel Gonzalez avatar Henning Dahlheim avatar Rory Fahy avatar Dmitriy Pertsev avatar  avatar Maarten van Vliet avatar Paulo Renato avatar Dima Doronin avatar Noah Betzen avatar John Barker avatar Alban avatar

Watchers

John Barker avatar Vincent Bach avatar  avatar Rory Fahy avatar  avatar

apical's Issues

No phoenix dependency

Hi. Nice library.

I would really like to be able to use something like what this library provides without the direct need for Phoenix.
Some services are too simple for Phoenix features and could depend only on Plug, without direct dependency on Phoenix.

Option to generate routes across multiple controllers

Question

Asking since this wasn't immediately clear from the documentation, but how does one use the single .json/.yaml schema to generate routes to actions across multiple controllers?

Based on the current example from the docs, it looks like the app would have to have a single controller only?

Apical.router_from_file(
  "path/to/openapi.yaml",
  controller: MyProjectWeb.ApiController
)

Or alternatively, split the OpenAPI schema file into multiple files, then invoke Apical.router_from_file/2 multiple times referring to different file and each time a different controller.

Instead, would it not be more convenient to have an option to generate routes for many controllers/actions from the schema - for example, to improve code organisation: one could have a single .json/.yaml schema, and multiple controller files. I believe having multiple controller files is somewhat a de-facto standard approach of code organisation, for example, in projects using Phoenix framework.

For example, imaging OpenAPI Schema describes two families of routes: posts and comments:

GET /posts
POST /posts
PUT /posts/:id
GET /posts/:id
DELETE /posts/:id
GET /posts/:post_id/comments
POST /posts/:post_id/comments
PUT /comments/:id
GET /comments/:id
DELETE /comments/:id

It would be nice to have Apical generate routes to actions from two controllers:

GET /posts                    -> PostController#index
POST /posts                   -> PostController#create
PUT /posts/:id                -> PostController#update
GET /posts/:id                -> PostController#show
DELETE /posts/:id             -> PostController#destroy
GET /posts/:post_id/comments  -> CommentController#index
POST /posts/:post_id/comments -> CommentController#craete
PUT /comments/:id             -> CommentController#update
GET /comments/:id             -> CommentController#show
DELETE /comments/:id          -> CommentController#destroy

Proposed solution

I think one way to achieve this could be for Apical to derive the names of controller and action from based on some conventional information of the operation.

For example, it could be convenient to use operationId to store the a value of PostController#index string. Then, Apical would use this string to build a route to the said controller:

openapi: 3.1.0
  info:
    title: My API
    version: 1.0.0
  paths:
    "/posts":
      post:
        operationId: "PostController#create"
        responses:
          "200":
            description: OK
# ...

One problem with this approach could be that, at the compilation time, all controller modules must already exist.

path parameters

  • compile error on not required
  • deprecated
  • style: matrix
  • style: label
  • explode: matrix
  • explode: label
  • schema

query parameter testing:

make sure that malformed query parameters can give useful information as to what went wrong.

  • 299 warning when extra unspecified parameters are a thing
  • objects with non-even number of things
  • illegal characters

query parameter

  • required
  • deprecated
  • allowEmptyValue
  • style
    • form
    • spaceDelimited
    • pipeDelimited
    • deepObject
    • x-
  • explode
  • allowReserved
  • schema
    • deep schema interpretation

refactor the Paths module

desired attributes:

  • generation of operation information should probably punt to separate modules (if possible).
  • generation of code should be flexible, not tied to phoenix, and allow for a plug-based strategy

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.