Code Monkey home page Code Monkey logo

lswapicallerbundle's Introduction

LswApiCallerBundle

screenshot

The LswApiCallerBundle adds a CURL API caller to your Symfony2 application. It is easy to use from the code and is aimed to have full debugging capabilities.

Read the LeaseWebLabs blog about LswApiCallerBundle

Requirements

  • PHP 5.3 with curl support
  • Symfony >= 2.1

Installation

Installation is broken down in the following steps:

  1. Download LswApiCallerBundle using composer
  2. Enable the Bundle
  3. Make sure the cURL module in PHP is enabled

Step 1: Download LswApiCallerBundle using composer

Add LswApiCallerBundle in your composer.json:

{
    "require": {
        "leaseweb/api-caller-bundle": "*",
        ...
    }
}

Now tell composer to download the bundle by running the command:

$ php composer.phar update leaseweb/api-caller-bundle

Composer will install the bundle to your project's vendor/leaseweb directory.

Step 2: Enable the bundle

Enable the bundle in the kernel:

<?php
// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new Lsw\ApiCallerBundle\LswApiCallerBundle(),
    );
}

Step 3: Make sure the cURL module in PHP is enabled

On a Debian based distribution (like Ubuntu) the package is called "php5-curl" and can be installed using the following commands:

$ sudo apt-get install php5-curl
$ sudo service apache2 restart

On a RedHat based distribution (like CentOS) the package is called "php-curl" and can be installed using the following commands:

$ sudo yum install php-curl
$ sudo service httpd restart

To check this create and run a PHP file with the following contents:

<?php phpinfo() ?>

It should display that the option "cURL support" is set to "enabled".

This package should work on a Windows installation as well provided the CURL support is enabled in PHP.

Usage

You can use the caller by getting the service "api_caller" and using the "call" function with one of the available call types:

  • HttpGetJson
  • HttpPostJson
  • HttpPostJsonBody (the body will be json_encode)
  • HttpPutJson
  • HttpDeleteJson
  • HttpGetHtml

Example of usage with the "HttpGetJson" call type:

use Symfony\Bundle\FrameworkBundle\Controller\Controller
use Lsw\ApiCallerBundle\Call\HttpGetJson;

class SomeController extends Controller
{
    public function someAction()
    {
        ...
        $output = $this->get('api_caller')->call(new HttpGetJson($url, $parameters));
        ...
    }
}

Example of usage with the "HttpPostJsonBody" call type:

use Symfony\Bundle\FrameworkBundle\Controller\Controller
use Lsw\ApiCallerBundle\Call\HttpPostJsonBody;

class SomeController extends Controller
{
    public function someAction()
    {
        ...
        $arrayToPost = array(
            'ip_address' => array(
                'name' => 'IpName',
                'hostname' => 'HostName',
                'ip' => '192.168.0.1',
                'throttling_template' => array(
                    'name' => 'Throttling Template'
                )
            )
        ); // this will be json_encode. If you don't want to json_encode, use HttpPostJson instead of HttpPostJsonBody
        $output = $this->get('api_caller')->call(new HttpPostJsonBody($url, $arrayToPost, true, $parameters)); // true to have an associative array as answer
        ...
    }
}

Configuration

By default it uses these cURL options:

parameters:
    api_caller.options:
        timeout: 10  # maximum transport + execution duration of the call in sec.
        ssl_verifypeer: false  # to stop cURL from verifying the peer's certificate.
        useragent: "LeaseWeb API Caller"  # contents of the "User-Agent: " header.
        followlocation: true  # to follow any "Location: " header that the server sends.
        sslversion: 3  # set to 3 to avoid any bugs that relate to automatic version selection.
        fresh_connect: false  # set to true to force full reconnect every call.

License

This bundle is under the MIT license.

The "wall-socket" icon in the web debug toolbar is part of the Picas icon set (official website: http://www.picasicons.com). The icon is licensed and may only be used to identifying the LswApiCallerBundle in the Symfony2 web debug toolbar. All ownership and copyright of this icon remain the property of Rok Benedik.

lswapicallerbundle's People

Contributors

camille-hdl avatar cbougher avatar comstar avatar dtdigio avatar fancyweb avatar gabrielanca avatar iisisrael avatar istaveren avatar jpillias avatar marcobuschini avatar mblkita avatar mevdschee avatar minras avatar pguso avatar qtsd avatar rolphh avatar sebastianstorz avatar spoelwijk avatar tnajanssen avatar zakharovvi 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

Watchers

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

lswapicallerbundle's Issues

How use bundle?

Hello. Sorry, but can you write few strings how use this bundle to send POST data

Composer dependency

If i try to use to library outside a symfony environment like this:

{
    "require": {
        "leaseweb/api-caller-bundle": "1.2.6"
    }
}

and using the code:

<?php
require_once 'vendor/autoload.php';

use Lsw\ApiCallerBundle\Caller\LoggingApiCaller;
use Lsw\ApiCallerBundle\Call\HttpPostJson;

$caller = new LoggingApiCaller([]);
$curlCall = new HttpPostJson(
    'http://myurl.com',
    ['foo' => 'bar']
);

var_dump(array(
    'body' => $caller->call($curlCall),
    'status' => $caller->getLastStatus()
));

I end up with the following dependency error:

Error: Class 'Doctrine\Common\Util\Inflector' not found in [mypath]/vendor/leaseweb/api-caller-bundle/Lsw/ApiCallerBundle/Helper/Curl.php on line 38

Unfortunately, it is tied to Utils, not separate Inflector lib.

The fix is simple, just include "doctrine/common" in the library composer requirements.
Should I make a PR.

New tag

Hello,

Can you tag master as a new version please? As it fix an issue on Inflector it would be great to set a tag and not master in composer.

Thank you,

Louis

HttpGetJson wrong cURL method

Hey,

I'm trying to send a HttpGetJson to my API. However, my API answers with a 405 (Method not allowed):

$baseUrl = $this->serviceContainer->getParameter('api_base_url');
$me = $this->apiCaller->call(new HttpGetJson($baseUrl.'/user/me', array(
    'access_token' => $token->getAccessToken()
))); // results in a 405 (method not allowed, but my API allows GET requests for this endpoint)
     // No route found for "POST /user/me" --> but I'm sending a GET
     // The request I was sending before, was a POST

If I'm using DHC by Restlet and sending a GET to /user/me, the API is answering correctly:

{
    "customer":{
        "id": 1,
        "email": "[email protected]",
        "roles_unserialized":[
            "ROLE_FOO_ADMIN"
        ],
        "created_at": "2016-05-06 23:33:29"
    }
}

Do you know, what could be the problem?

Best,
Christian

dhc

POST json format

Hi,

Is it possible to POST as JSON. Tried to add the 'Content-type: application/json' header, but can't post a json string :(
Using HttpPostJson always need add an array, and encode all elements of this array with an url_encode.

Any solution?

Thank you.

Get rid of annoying IDE warnings

Hey,

thank you for this awesome bundle! You happen to know how to get rid of this annoying message from phpstorm?

image

Best,
Christian

Can't call to HTTPS

HTTPS://api.lifx.com:443/v1beta1/lights.json and https://api.lifx.com/v1beta1/lights.json wont work
no request will be send. (Connection failed)
image

HTTP://api.lifx.com:443/v1beta1/lights.json returns 400 Bad Request (which is good)
image

controller

        $url = "https://api.lifx.com:443/v1beta1/lights.json";
        $result = $this->get('api_caller')->call(new HttpGetJson($url, array()));

HttpGetJson

class HttpGetJson extends CurlCall implements ApiCallInterface
{
    /**
    * {@inheritdoc}
    */
    public function generateRequestData()
    {
        $this->requestData = http_build_query($this->requestObject);
    }

    /**
     * {@inheritdoc}
     */
    public function parseResponseData()
    {
        $this->responseObject = json_decode($this->responseData, $this->asAssociativeArray);
    }

    /**
     * {@inheritdoc}
     */
    public function makeRequest($curl, $options)
    {
        $curl->setopt(CURLOPT_URL, $this->url.'?'.$this->requestData);
        $curl->setopt(CURLOPT_HTTPHEADER, array('Content-type: application/json'));
        $curl->setoptArray($options);
        $this->responseData = $curl->exec();
    }

}

When i use the direct way it will work just fine (returns a 401 error cause we're not sending our api key along)

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.lifx.com:443/v1beta1/lights.json');
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
        curl_setopt($ch, CURLOPT_GET, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $result = curl_exec($ch);

Token auth

I try to implement an API call with this bundle, and got problem with the token auth required by the API.

Here is a sample of the calls:

        // get token url
        $tokenUrl = '/api/auth/gettoken';
        $parameters = array(
            'user' => 'user',
            'password' => 'password',
            );

        // api call
        $output = $this->get('api_caller')->call(new HttpGetJson($baseUrl.$tokenUrl.$postUrl, $parameters));
        $token = $output->token;

        // schedule
        $parameters = array(
            'token' => $token,
            'start' => time(),
            'duration' => 24,
            );

        $progUrl = '/api/get/schedule';

        // api call
        $output = $this->get('api_caller')->call(new HttpGetJson($baseUrl.$progUrl.$postUrl, $parameters));

The 1st call get me a valid token, but the 2nd call fails because of an "Authentification failed".

Have I missed something?
Thanks.

Upload files is not supported

Using your bundle I have some problems.
Your Bundle is not support uploading files.
Method "generateRequestData()" always generate QueryString but when I need to upload file I need to put array to CURLOPT_POSTFIELDS. I'm ready to fix this problem.

I'm propose remove method "generateRequestData()". And transform data in method "makeRequest()".
Variable $requestData use only "Logger". Maybe we not need to log long requests (when post request so big).

Currently I'm solve this problem:

$result = $this->getContainer()->get('api_caller')->call(
            new HttpPost($url, [], false, [
                'POSTFIELDS' => $post
            ])
        );

Why your bundle concat "CURLOPT_" prefix?? Maybe you need to use class constants???

100 - Continue

I am having issues sending a POST request with JSON Body (HttpPostJsonBody) to a node express server. The call appears to be processed correctly on the server but the response received is a 100 - Continue rather than the returned JSON.

I have seen various posts advising to add 'Except:' to the HTTP_HEADER but that resulted in the call failing.

Do you have any advice as to how I might resolve this problem ?

Thank you.

Require Symfony ~2.0 in composer.json

Hey,

Documentation says:
Requirements
Symfony 2.1 (works under Symfony 2.0 as well)

Is it possible to require Symfony 2.0 instead of 2.1 in this case. I'm trying to integrate this to our application that is about 4 years old and is based on Symfony 2.0.

Thanks,

Debug tool bar on SF4

Hello,

Issue with debug bar on SF4

Resources/views/Collector/api.html.twig

-{% extends '@WebProfiler/Profiler/layout.html.twig' %}
+{% extends '@WebProfiler/Profiler/toolbar_item.html.twig' %}

I can push the modification if you allow me to contribute

Send a x-wsse header

I want to sent a x-wsse header, how does this works?

I tried this:

api_caller.options:
    timeout: 10  # maximum transport + execution duration of the call in sec.
    ssl_verifypeer: false  # to stop cURL from verifying the peer's certificate.
    useragent: "LeaseWeb API Caller"  # contents of the "User-Agent: " header.
    followlocation: true  # to follow any "Location: " header that the server sends.
    sslversion: 3  # set to 3 to avoid any bugs that relate to automatic version selection.
    fresh_connect: false  # set to true to force full reconnect every call.
    HTTPHEADER:
        x-wsse: test

[Suggestion] Call classes dynamic options

Hello,
I'm currently using this bundle for api calls, but I needed to extend the Call requests to fit more flexible env. My suggestion is this:

    public function __construct($url, $requestObject, $asAssociativeArray = false, array $ymlOptions = array())
    {
        parent::__construct($url, $requestObject, $asAssociativeArray);
        $this->ymlOptions = $ymlOptions;
    }

    public function makeRequest($curl, $options)
    {
        // merge the options from the API Caller bundle with other set of options
        // override the options with the provided from the Yml
        foreach($this->ymlOptions as $const => $value)
        {
            $options[constant($const)] = $value;
        }
        // call the parent MakeRequest, this way we don't have to copy all it's logic
        parent::makeRequest($curl, $options);
    }

My extension is to dynamically put options on the Request. In my case I pass options about the credentials because the Live and Test credentials are different.

Regards,
Lachezar Lechev

Should not force sslversion.

SSLv3 is deprecated, and actually removed in Ubuntu 16.04 LTS+PHP 7. We shouldn't force cURL in using any particular version.

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.