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

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

How are you handling the data revolution? We want your take on what's real, what's hype, and what's next in the world of data engineering.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Hello Woo. Writing Your First Script Using the Woocommerce API
  • A Multilingual Prestashop Online Store Using ChatGPT
  • Stop Prompt Hacking: How I Connected My AI Agent to Any API With MCP
  • How Developers Are Driving Supply Chain Innovation With Modern Tech

Trending

  • gRPC and Its Role in Microservices Communication
  • Misunderstanding Agile: Bridging The Gap With A Kaizen Mindset
  • Article Moderation: Your Questions, Answered
  • Driving Streaming Intelligence On-Premises: Real-Time ML With Apache Kafka and Flink
  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
19.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
  • Stop Prompt Hacking: How I Connected My AI Agent to Any API With MCP
  • How Developers Are Driving Supply Chain Innovation With Modern Tech

Partner Resources

×

Comments

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: