Coder Social home page Coder Social logo

php-apidoc's Introduction

php-apidoc

Generate documentation for php API based application. No dependency. No framework required.

Requirements

PHP >= 5.3.2

Installation

The recommended installation is via composer. Just add the following line to your composer.json:

{
    ...
    "require": {
        ...
        "crada/php-apidoc": "@dev"
    }
}
$ php composer.phar update

Usage

<?php

namespace Some\Namespace;

class User
{
    /**
     * @ApiDescription(section="User", description="Get information about user")
     * @ApiMethod(type="get")
     * @ApiRoute(name="/user/get/{id}")
     * @ApiParams(name="id", type="integer", nullable=false, description="User id")
     * @ApiParams(name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}")
     * @ApiReturnHeaders(sample="HTTP 200 OK")
     * @ApiReturn(type="object", sample="{
     *  'transaction_id':'int',
     *  'transaction_status':'string'
     * }")
     */
    public function get()
    {

    }

    /**
     * @ApiDescription(section="User", description="Create's a new user")
     * @ApiMethod(type="post")
     * @ApiRoute(name="/user/create")
     * @ApiParams(name="username", type="string", nullable=false, description="Username")
     * @ApiParams(name="email", type="string", nullable=false, description="Email")
     * @ApiParams(name="password", type="string", nullable=false, description="Password")
     * @ApiParams(name="age", type="integer", nullable=true, description="Age")
     */
    public function create()
    {

    }
}

Create an apidoc.php file in your project root folder as follow:

# apidoc.php
<?php

use Crada\Apidoc\Builder;
use Crada\Apidoc\Exception;

$classes = array(
    'Some\Namespace\User',
    'Some\Namespace\OtherClass',
);

$output_dir  = __DIR__.'/apidocs';
$output_file = 'api.html'; // defaults to index.html

try {
    $builder = new Builder($classes, $output_dir, 'Api Title', $output_file);
    $builder->generate();
} catch (Exception $e) {
    echo 'There was an error generating the documentation: ', $e->getMessage();
}

Then, execute it via CLI

$ php apidoc.php

Available Methods

Here is the list of methods available so far :

  • @ApiDescription(section="...", description="...")
  • @ApiMethod(type="(get|post|put|delete|patch")
  • @ApiRoute(name="...")
  • @ApiParams(name="...", type="...", nullable=..., description="...", [sample=".."])
  • @ApiHeaders(name="...", type="...", nullable=..., description="...")
  • @ApiReturnHeaders(sample="...")
  • @ApiReturn(type="...", sample="...")
  • @ApiBody(sample="...")

Preview

You can see a dummy generated documentation on http://calinrada.github.io/php-apidoc/

Tips

To generate complex object sample input, use the ApiParam "type=(object|array(object)|array)":

* @ApiParams(name="data", type="object", sample="{'user_id':'int','profile':{'email':'string','age':'integer'}}")

Known issues

I don't know any, but please tell me if you find something. PS: I have tested it only in Chrome !

TODO

  • Implement options for JSONP
  • Implement "add fields" option

php-apidoc's People

Contributors

calinrada avatar cameron-fgx avatar dacobah avatar gnuget avatar kbsali avatar lahaxearnaud avatar matissjanis avatar mchurichi avatar pvullioud avatar ruifil avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-apidoc's Issues

not found

Fatal error: Uncaught Error: Class 'Crada\Apidoc\Builder' not found in C:\OpenServer\domains\vskidke\apidoc.php:16
Stack trace:
#0 {main}

thrown in C:\OpenServer\domains\vskidke\apidoc.php on line 16

apidoc.php

generate(); } catch (Exception $e) { echo 'There was an error generating the documentation: ', $e->getMessage(); }

Basic Auth and raw body

Hi! Great work.
Could it be possible to add a Basic Auth feature when testing in sand box?
Also, some api calls need a body (POST, PUT) For example, a login call could need a JSON body in order to work:
POST /login
Body :
{
"username" : "string",
"password" : "password"
}
Could it be possible to add a way to edit this in Sandbox ?

Sandbox and optional parameters

I've a ressource like /aaa/{id}/{code}/{key} where code and key are optional parameters.
Sandbox send /aaa/myvalue/{code}/{key} in this case

This can be corrected by :

if(matchedParamsInRoute) {
   for (index = 0; index < matchedParamsInRoute.length; ++index) {
         try {
               key = matchedParamsInRoute[index];
               value = serializedData[key];
               if (typeof value == "undefined") value ="";    
               url = url.replace("{" + key + "}", value);
               delete serializedData[key];
          } catch (err) {
               console.log(err);
          }
    }
}

Empty parameters for sandbox

Sometime empty parameters create problem with API
this is a way to remove them.

   var st_headers = {};
            st_headers[$('#apikey_key').val()] = $('#apikey_value').val();
            serializedData = $(form).serialize().replace(/&?[^=&]+=(&|$)/g,'');
            $.ajax({
                url: $('#apiUrl').val() + $(form).attr('action'),
                data: serializedData,
                type: '' + $(form).attr('method') + '',
                dataType: 'json',
                headers: st_headers
            }).done(function(data) 

@ApiHeader Problem

if i put @ApiHeaders before @apiroute
when i use two parameters (Though i know it should be 4 parameters) it works just fine

/**
     * @ApiDescription(section="Comment", description="comment api")
     * @ApiMethod(type="post")
     * @ApiHeaders(name="header_key", type="string")
     * @ApiRoute(name="/comment/create")
     */

when put the 3rd nullable parameter, there will be a php notice : Undefined index: ApiRoute

/**
     * @ApiDescription(section="Comment", description="comment api")
     * @ApiMethod(type="post")
     * @ApiHeaders(name="header_key", type="string", nullable=true)
     * @ApiRoute(name="/comment/create")
     */

even when i use full parameters but different order still get the same notice

/**
     * @ApiDescription(section="Comment", description="comment api")
     * @ApiMethod(type="post")
     * @ApiHeaders(name="header_key", type="string", description="text", nullable=true)
     * @ApiRoute(name="/comment/create")
     */

maybe there should be some exception telling not annotate in this way?

quoting and escaping problems in field's value specification

When i try to return an sample @ApiReturn, its not possible to use double quotes within the string (the value so to say) and just using single quotes outside to specify the value. Its also not possible to escape the double quotes.

E.g.:
@ApiReturn(type="object", sample='{
* "transaction_id":"int",
* "transaction_status":"string"
* }')
=> results that the sample data will be lost in the generated html doc.

If I try to escape the value like this:

@ApiReturn(type="object", sample="{
* "transaction_id":"int",
* "transaction_status":"string"
* }")
=> will fail with a parsing exception:
There was an error generating the documentation:
Parse Error: missing comma separator near: ...le="{"transaction_id":"<--

You should fix it or add this to the "Known issues".

Don't display 'Body', 'Header' and 'Parameters' pane if empty

Header and Body Panes are hard-coded and shouldn't be displayed if there is no content for them.

<div class="tab-pane active" id="info{{ elt_id }}">
    <div class="well">
    {{ description }}
    </div>
    <div class="panel panel-default">
      <div class="panel-heading"><strong>Headers</strong></div>
      <div class="panel-body">
        {{ headers }}
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading"><strong>Parameters</strong></div>
      <div class="panel-body">
        {{ parameters }}
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading"><strong>Body</strong></div>
      <div class="panel-body">
        {{ body }}
      </div>
    </div>
</div><!-- #info -->

No way to access {{ body }} pane

The {{ body }} tag within the Tab pane cannot be accessed.

<div class="panel panel-default">
    <div class="panel-heading"><strong>Body</strong></div>
    <div class="panel-body">
        {{ body }}
    </div>
</div>

CodeIgniter Integration

I love this solution!
I'm using CI framework, but I can't figure out how to get it working.
Any idea? Thanks!

Response section not updated when there is no content

In the sandbox, when you do a request and the response has no content (eg HTTP 204 No Content), the response section is not updated, showing the previous response, if there is one.

Repro steps:

  1. Make a request that returns some content
  2. Using the same method, make a request that don't returns any content

Header and Footer div unwanted

Unwanted Headers and Body divs rendering

apidoc

Class code parsed

class App extends Controller
{
    /**
     * Log a user to the app
     *
     * @param Request $request
     *
     * @ApiDescription(section="App", description="Log the user to the app using Facebook token")
     * @ApiMethod(type="post")
     * @ApiRoute(name="/app/login")
     * @ApiParams(name="user", type="object", description="User object with the followings attributes", sample="{
     *     'ID': 'string',
     *     'accessToken': 'string'
     * }")
     * @ApiReturnHeaders(sample="HTTP 200 OK")
     * @ApiReturn(type="object", sample="{
     *     'success': 'bool',
     *     'message': 'string',
     *     'newUser': 'bool',
     *     'user': {
     *          'id': 'int',
     *          'email': 'string',
     *          'name': 'string',
     *          'first_name': 'string',
     *          'last_name': 'string',
     *          'cover': 'string',
     *          'picture': 'string',
     *          'facebook_token': 'string',
     *          'facebook_id': 'int',
     *          'facebook_token_expiration': 'int'
     *     }
     * }")
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        // ...
    }
}

Special character at 2nd line of index.html

I am getting unexpected characted error at line two

<html lang="en">

I tried showing hidden characters on my IDE but nothing found but both chrome and firefox are giving this error

chrome error : Uncaught SyntaxError: Unexpected token b

firefox error : SyntaxError: JSON.parse: unexpected character at line 2 column 14 of the JSON data

Route params are not properly replaced in sandbox

FormData object values can be accessed through FormData.get() method, instead of using serializedData[key] like you would with an array.

            var serializedData = new FormData(); 

            // ...

            if(matchedParamsInRoute) {
                for (index = 0; index < matchedParamsInRoute.length; ++index) {
                    try {
                        key = matchedParamsInRoute[index];
                        value = serializedData[key];
                        if (typeof value == "undefined") value ="";
                        url = url.replace("{" + key + "}", value);
                        delete serializedData[key];
                    } catch (err) {
                        console.log(err);
                    }
                }
            }

Currently value will always return "undefined". Try this instead:

value = serializedData.get(key);

Also FormData.delete() can be used further to remove the element from the object.

Undefined Index laravel ?

Undefined index: sample in D:\Work\Workspace\htdocs\teraception-application-dashboard-web\vendor\crada\php-apidoc\Crada\Apidoc\Builder.php on line 320
PHP Notice: Undefined index: sample in D:\Work\Workspace\htdocs\teraception-application-dashboard-web\vendor\crada\php-apidoc\Crada\Apidoc\Builder.php on line
320

Sample param not being pulled on page

The sample parameter does not get pulled/displayed on the output page

@ApiParams(name="...", type="...", nullable=..., description="...", [sample=".."])

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.