DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Hello Woo. Writing Your First Script Using the Woocommerce API
  • A Multilingual Prestashop Online Store Using ChatGPT
  • Beyond Manual Annotation: Engineering Self-Correcting Pseudo-Labeling Pipelines
  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch

Trending

  • Optimizing Databricks Spark Pipelines Using Declarative Patterns
  • A Comprehensive Guide to Prompt Engineering
  • AI-Driven Integration in Large-Scale Agile Environments
  • Architecting an Embedded Efficiency Layer: A Platform Deep Dive into Day-Two Operational Tuning
  1. DZone
  2. Data Engineering
  3. Databases
  4. Building A Simple API Proxy Server with PHP

Building A Simple API Proxy Server with PHP

By 
Gonzalo Ayuso user avatar
Gonzalo Ayuso
·
Sep. 02, 12 · Interview
Likes (0)
Comment
Save
Tweet
Share
20.2K Views

Join the DZone community and get the full member experience.

Join For Free
these days i’m playing with backbone and using public api as a source. the web browser has one horrible feature: it don’t allow you  to fetch any external resource to our host due to the cross-origin restriction. for example if we have a server at localhost we cannot perform one ajax request to another host different than localhost. nowadays there is a header to allow it: access-control-allow-origin . the problem is that the remote server must set up this header. for example i was playing with github’s api and github doesn’t have this header. if the server is my server, is pretty straightforward to put this header but obviously i’m not the sysadmin of github, so i cannot do it. what the solution? one possible solution is, for example, create a proxy server at localhost with php. with php we can use any remote api with curl (i wrote about it here and here for example). it’s not difficult, but i asked myself: can we create a dummy proxy server with php to handle any request to localhost and redirects to the real server, instead of create one proxy for each request?. let’s start. problably there is one open source solution (tell me if you know it) but i’m on holidays and i want to code a little bit (i now, it looks insane but that’s me :) ).

the idea is:

...
$proxy->register('github', 'https://api.github.com');
...

and when i type:

http://localhost/github/users/gonzalo123

and create a proxy to :

https://api.github.com/users/gonzalo123

the request method is also important. if we create a post request to localhost we want a post request to github too.

this time we’re not going to reinvent the wheel, so we will use symfony componets so we will use composer to start our project:

we create a conposer.json file with the dependencies:

{
    "require": {
        "symfony/class-loader":"dev-master",
        "symfony/http-foundation":"dev-master"
    }
}

now

php composer.phar install

and we can start coding. the script will look like this:

register('github', 'https://api.github.com');
$proxy->run();

foreach($proxy->getheaders() as $header) {
    header($header);
}
echo $proxy->getcontent();

as we can see we can register as many servers as we want. in this example we only register github. the application only has two classes:
restproxy , who extracts the information from the request object and calls to the real server through curlwrapper .

<?php
namespace restproxy;

class restproxy
{
    private $request;
    private $curl;
    private $map;

    private $content;
    private $headers;

    public function __construct(\symfony\component\httpfoundation\request $request, curlwrapper $curl)
    {
        $this->request  = $request;
        $this->curl = $curl;
    }

    public function register($name, $url)
    {
        $this->map[$name] = $url;
    }

    public function run()
    {
        foreach ($this->map as $name => $mapurl) {
            return $this->dispatch($name, $mapurl);
        }
    }

    private function dispatch($name, $mapurl)
    {
        $url = $this->request->getpathinfo();
        if (strpos($url, $name) == 1) {
            $url         = $mapurl . str_replace("/{$name}", null, $url);
            $querystring = $this->request->getquerystring();

            switch ($this->request->getmethod()) {
                case 'get':
                    $this->content = $this->curl->doget($url, $querystring);
                    break;
                case 'post':
                    $this->content = $this->curl->dopost($url, $querystring);
                    break;
                case 'delete':
                    $this->content = $this->curl->dodelete($url, $querystring);
                    break;
                case 'put':
                    $this->content = $this->curl->doput($url, $querystring);
                    break;
            }
            $this->headers = $this->curl->getheaders();
        }
    }

    public function getheaders()
    {
        return $this->headers;
    }

    public function getcontent()
    {
        return $this->content;
    }
}

the restproxy receive two instances in the constructor via dependency injection (curlwrapper and request). this architecture helps a lot in the tests , because we can mock both instances. very helpfully when building restproxy.

the restproxy is registerd within packaist so we can install it using composer installer:

first install componser

curl -s https://getcomposer.org/installer | php

and create a new project:

php composer.phar create-project gonzalo123/rest-proxy proxy

if we are using php5.4 (if not, what are you waiting for?) we can run the build-in server

cd proxy
php -s localhost:8888 -t www/

now we only need to open a web browser and type:

    http://localhost:8888/github/users/gonzalo123

the library is very minimal (it’s enough for my experiment) and it does’t allow authorization.

of course full code is available in github .

PHP API

Opinions expressed by DZone contributors are their own.

Related

  • Hello Woo. Writing Your First Script Using the Woocommerce API
  • A Multilingual Prestashop Online Store Using ChatGPT
  • Beyond Manual Annotation: Engineering Self-Correcting Pseudo-Labeling Pipelines
  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook