• Stars
    star
    120
  • Rank 295,983 (Top 6 %)
  • Language
    Erlang
  • License
    Apache License 2.0
  • Created over 9 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Swagger integration for Cowboy (built on trails)

cowboy-swagger

Swagger integration for Cowboy (built on trails).

build

Contact Us

If you find any bugs or have a problem while using this library, please open an issue in this repo (or a pull request :)).

Requirements

Cowboy Swagger requires Erlang 18+ after 0.1.0 version

Why Cowboy Swagger?

Simple, because there isn't a tool in Erlang to document Cowboy RESTful APIs easy and fast, and to improve development productivity.

With cowboy_swagger is possible to integrate Swagger to your Erlang projects that use Cowboy as a web server. It is extremely easy to use, and with just a few steps you'll have a nice Web documentation for your RESTful APIs.

To learn a bit more about Swagger, please check this blog post.

How to Use it?

This is the best part. It is extremely easy.

1. Document each Cowboy Handler

Because cowboy_swagger runs on top of trails, the first thing that you have to do is document all about your handler within the trails metadata. Keep in mind that all fields defined within each method into the metadata must be compliant with the Swagger specification.

For example, suppose that you have example_echo_handler, so it must implement the trails/0 callback from trails_handler behaviour:

trails() ->
  Metadata =
    #{get =>
      #{tags => ["echo"],
        description => "Gets echo var from the server",
        produces => ["text/plain"]
      },
      put =>
      #{tags => ["echo"],
        description => "Sets echo var in the server",
        produces => ["text/plain"],
        parameters => [
          #{name => <<"echo">>,
            description => <<"Echo message">>,
            in => <<"path">>,
            required => false,
            type => <<"string">>}
        ]
      }
    },
  [trails:trail("/message/[:echo]", example_echo_handler, [], Metadata)].

To get a better idea of how your handler should look like, please check here.

2. Include cowboy_swagger in your app

First, you need to include cowboy_swagger_handler module in your list of trails to be compiled.

% Include cowboy_swagger_handler in the trails list
Trails = trails:trails([example_echo_handler,
                        example_description_handler,
                        cowboy_swagger_handler]),
% store them
trails:store(Trails),
% and then compile them
Dispatch = trails:single_host_compile(Trails),

The snippet of code above is usually placed when you start cowboy. Check it here.

Then add cowboy_swagger to the list of apps to be loaded in your *.app.src file.

{application, example,
 [
  {description, "Cowboy Swagger Basic Example."},
  {vsn, "0.1"},
  {applications,
   [kernel,
    stdlib,
    jsx,
    cowboy,
    trails,
    cowboy_swagger
   ]},
  {modules, []},
  {mod, {example, []}},
  {registered, []},
  {start_phases, [{start_trails_http, []}]}
 ]
}.

And that's it, you got it. Now start your application and then you will have access to the API docs under the path /api-docs. Supposing that you're running the app on localhost:8080, that will be http://localhost:8080/api-docs.

Configuration

Additionally, cowboy_swagger can be configured/customized from a *.config file:

app.config

[
 %% Other apps ...

 %% cowboy_swagger config
 {cowboy_swagger,
  [
   %% `static_files`: Static content directory. This is where Swagger-UI
   %% is located. Default: `priv/swagger`.
   %% Remember that Swagger-UI is embedded into `cowboy-swagger` project,
   %% within `priv/swagger` folder. BUT you have to reference that path,
   %% and depending on how you're using `cowboy-swagger` it will be different.
   %% For example, assuming that you want to run your app which has
   %% `cowboy-swagger` as dependency from the console, `static_files` will be:
   {static_files, "./deps/cowboy_swagger/priv/swagger"},

   %% `global_spec`: Global fields for Swagger specification.
   %% If these fields are not set, `cowboy_swagger` will set default values.
   {global_spec,
    #{swagger => "2.0",
      info => #{title => "Example API"},
      basePath => "/api-docs"
     }
   }
  ]
 }
].

Definitions

Definitions can be used for describing parameters, responses and security schemas.

For adding definitions to your app, you have 2 choices:

  1. Add a definitions key to your cowboy_swagger global_spec map.
  2. Add them by calling cowboy_swagger:add_definition/2 and send the definition's name and properties.

Let's say you want to describe a POST call to a newspapers endpoint that requires name and description fields only, you can do it like this:

Option 1:

[ ... % other configurations
, { cowboy_swagger
  , [ { global_spec
      , #{ swagger => "2.0"
         , info => #{title => "My app API"}
         , definitions => #{
             "RequestBody" =>
               #{ "name" =>
                   #{ "type" => "string"
                    , "description" => "Newspaper name"
                    }
                , "description" =>
                    #{ "type" => "string"
                     , "description" => "Newspaper description"
                     }
                }
           }
         }
      }
    ]
  }
]

Option 2:

For the second choice, you can do it for example in one or several start_phases, directly in your handler or any other place you want.

-spec trails() -> trails:trails().
trails() ->
  DefinitionName = <<"RequestBody">>,
  DefinitionProperties =
    #{ <<"name">> =>
         #{ type => <<"string">>
          , description => <<"Newspaper name">>
          }
     , <<"description">> =>
         #{ type => <<"string">>
          , description => <<"Newspaper description">>
          }
     },
  % Add the definition
  ok = cowboy_swagger:add_definition(DefinitionName, DefinitionProperties),
  ...

Now in your handler's trails callback function you can use it:

...
  RequestBody =
    #{ name => <<"request body">>
     , in => body
     , description => <<"request body (as json)">>
     , required => true
       % Use the previously created `RequestBody' definition
     , schema => cowboy_swagger:schema(<<"RequestBody">>)
     },
  Metadata =
    #{ get =>
       #{ tags => ["newspapers"]
        , description => "Returns the list of newspapers"
        , produces => ["application/json"]
        }
     , post =>
       # { tags => ["newspapers"]
         , description => "Creates a new newspaper"
         , consumes => ["application/json"]
         , produces => ["application/json"]
         , parameters => [RequestBody] % and then use that parameter here
         }
     },
  Path = "/newspapers",
  Options = #{path => Path},
  [trails:trail(Path, newspapers_handler, Options, Metadata)].

What this does for you is add a nice response, parameter or security model in swagger-ui, so client developers will know exactly what parameters the API expects for every endpoint.

Example

For more information about cowboy_swagger and how to use it, please check this Example.

More Repositories

1

erlang_guidelines

Inaka's Erlang Coding Guidelines
Erlang
619
star
2

EventSource

A simple Swift client library for the Server Sent Events (SSE)
Swift
483
star
3

galgo

When you want your logs to be displayed on screen
Java
427
star
4

elvis

Erlang Style Reviewer
Erlang
424
star
5

apns4erl

Apple Push Notification Server for Erlang
Erlang
369
star
6

TinyTask

A Tiny Task Library
Java
324
star
7

worker_pool

Erlang worker pool
Erlang
274
star
8

sumo_db

Erlang Persistency Framework
Erlang
173
star
9

shotgun

For the times you need more than just a gun.
Erlang
166
star
10

Dayron

A repository `similar` to Ecto.Repo that maps to an underlying http client, sending requests to an external rest api instead of a database
Elixir
159
star
11

gold_fever

A Treasure Hunt for Erlangers
Erlang
86
star
12

Jayme

Abstraction layer that eases RESTful interconnections in Swift
Swift
81
star
13

guidelines

General Inaka Guidelines
75
star
14

cowboy-trails

A couple of improvements over Cowboy Routes
Erlang
71
star
15

jem.js

Just Erlang Maps for Javascript
JavaScript
69
star
16

sheldon

Very Simple Erlang Spell Checker
Erlang
62
star
17

elvis_core

The core of an Erlang linter
Erlang
61
star
18

niffy

Inline C code in Erlang modules to build NIFs
Erlang
60
star
19

sumo_rest

Generic cowboy handlers to work with Sumo
Erlang
59
star
20

serpents

Multi-Player Game on top of HDP protocol
Erlang
56
star
21

xref_runner

Erlang Xref Runner (inspired in rebar xref)
Erlang
50
star
22

erlang-github

Github API client
Erlang
46
star
23

lasse

SSE handler for Cowboy
Erlang
45
star
24

beam_olympics

Let's find the fastest beamer!
Erlang
39
star
25

fiar

Four in a Row - A game to learn Erlang
Erlang
36
star
26

zipper

Generic Zipper implementation in Erlang
Erlang
34
star
27

ios-xmpp-sample

Blog post sample project.
Swift
33
star
28

kotlillon

Android Kotlin Examples
Kotlin
33
star
29

katana-test

Meta Testing Utilities for common_test
Erlang
32
star
30

match_stream

A sample project to show in our scale blog post
JavaScript
30
star
31

phoenix_passwordless_login

Phoenix Passwordless Login
Elixir
29
star
32

KillerTask

Android AsyncTask wrapper library, written in Kotlin
Kotlin
26
star
33

canillita

Simple Paperboy-themed PubSub
Erlang
26
star
34

lewis

Rock your Android
Java
22
star
35

tirerl

Erlang interface to Elastic Search
Erlang
19
star
36

itweet

Twitter Stream API on ibrowse
Erlang
18
star
37

katana-code

Code Utilities for Erlang
Erlang
17
star
38

pusherman

queuing system for push notifications
Erlang
17
star
39

galgo-ios

When you want your logs to be displayed on screen
Objective-C
16
star
40

lsl

NIM in Erlang
Erlang
15
star
41

credo_server

Credo Server
Elixir
15
star
42

FadeButton

Fading effects for UIButtons made simple
Swift
15
star
43

Jolly

Jolly Chimp that keeps track of our Github Repos
Swift
12
star
44

rpsls

Rock Paper Scissors Lizzard Spock World Championship in Erlang
Erlang
12
star
45

ikbot

An elixir based customizable hipchat bot
Elixir
12
star
46

nconf

Nested Configuration Manager for Erlang Applications
Erlang
12
star
47

pushito

APNS over HTTP/2
Elixir
11
star
48

rest_guidelines

REST API Design Guidelines
11
star
49

fetjaba

From Erlang To Java and Back Again
Erlang
9
star
50

sumo_db_pgsql

PostgreSQL adapter for sumo_db.
Erlang
9
star
51

jinterface_stdlib

Erlang stdlib implementation on Java, based on JInterface
Java
9
star
52

IKCapture

Snapchat-Like Image Capture Library
Objective-C
8
star
53

MediaPickerController

Neat API for presenting the classical action sheet for picking an image or video from the device or camera.
Swift
8
star
54

PictureViewMaster

Interactive image projector.
Swift
8
star
55

toy_kv

A simple and reduced Key-Value Store written in Erlang
Erlang
7
star
56

ColorPicker

Color Picker for Swift
Swift
7
star
57

swift_guidelines

Inaka's Swift Coding Guidelines
7
star
58

spellingci

Spelling CI Server
Erlang
7
star
59

talks

Sources and pdfs of our talks and speeches
TeX
6
star
60

bookmarks

A collection of bookmarks for Inakos
6
star
61

IKJayma

RESTful API abstraction for Server Interconnection
Objective-C
6
star
62

hexer

Hex.pm integration in escript format.
Erlang
6
star
63

hexer.mk

erlang.mk plugin for hexer
Makefile
5
star
64

android_guidelines

Inaka's Android Development Guidelines
5
star
65

elvis.mk

3rd party erlang.mk plug-in for Elvis
Shell
5
star
66

plixir

Poker + Elixir + Phoenix
CSS
5
star
67

ios_guidelines

Inaka's iOS Coding Guidelines
Objective-C
4
star
68

sumo_db_elasticsearch

ElasticSearch adapter for sumo_db
Erlang
4
star
69

tele_sign

Node.js library to send messages through http://www.telesign.com/
JavaScript
4
star
70

inaka.github.io

Inaka's Open Source Projects
HTML
3
star
71

sumo_db_riak

Riak adapter for sumo_db
Erlang
3
star
72

android-excercises

Quick test for Android candidates
3
star
73

sumo_db_mongo

MongoDB adapter for sumo_db
Erlang
2
star
74

Otec

A swift app to showcase our best open-source libraries
Swift
2
star
75

gold_fever-solver

A solver for the http://github.com/inaka/gold_fever game
Erlang
2
star
76

inaka.mk

erlang.mk extras that we generally use in all of our projects
Makefile
2
star
77

g2x

Graffle to XCode
Objective-C
2
star
78

beam_olympics-extended

Internal repo to keep secret beam_olympics tasks from the public view
Erlang
2
star
79

beam_olympics-solver

Solutions for beam_olympics
Elixir
2
star
80

emarkdown

Based on https://github.com/devinus/markdown - but for Erlang :)
C
2
star
81

sumo_db_mysql

MySQL adapter for sumo_db
Erlang
2
star
82

ruby_guidelines

Our own guidelines when it comes to ruby development
1
star
83

pokedex

Dumb repo to prove what we can do with sumo{_db|rest_}
Erlang
1
star
84

homebrew-formulas

Homebrew formulas for some of our tools
Ruby
1
star
85

updike

Run, rabbit, run
1
star
86

ios-scripts

Helper scripts that you can use in your iOS apps
Shell
1
star
87

INSocketListener

SSE Socket Listener for Objective-C
Objective-C
1
star