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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. Building A Simple API Proxy Server with PHP

Building A Simple API Proxy Server with PHP

Gonzalo Ayuso user avatar by
Gonzalo Ayuso
·
Sep. 02, 12 · Interview
Like (0)
Save
Tweet
Share
17.42K 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.

Popular on DZone

  • Agile Transformation With ChatGPT or McBoston?
  • What Was the Question Again, ChatGPT?
  • Utilize OpenAI API to Extract Information From PDF Files
  • Continuous Development: Building the Thing Right, to Build the Right Thing

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: