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
Please enter at least three characters to search
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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

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

Related

  • Hello Woo. Writing Your First Script Using the Woocommerce API
  • A Multilingual Prestashop Online Store Using ChatGPT
  • Source-Driven Development in Salesforce: Managing Metadata and API Versions
  • How to Introduce a New API Quickly Using Micronaut

Trending

  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • The Evolution of Scalable and Resilient Container Infrastructure
  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • Building a Real-Time Audio Transcription System With OpenAI’s Realtime API
  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
  • Source-Driven Development in Salesforce: Managing Metadata and API Versions
  • How to Introduce a New API Quickly Using Micronaut

Partner Resources

×

Comments
Oops! Something Went Wrong

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
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!