Veronica  Roob

Veronica Roob


Awesome PHP: Libraries for Accessing Third Party APIs

Third Party APIs

Libraries for accessing third party APIs.

  • Amazon Web Service SDK - The official PHP AWS SDK library.
  • AsyncAWS - An unofficial asynchronous PHP AWS SDK.
  • Campaign Monitor - The official Campaign Monitor PHP library.
  • Github - A library to interface with the Github API.
  • Mailgun The official Mailgun PHP API.
  • Square - The official Square PHP SDK for payments and other Square APIs.
  • Stripe - The official Stripe PHP library.
  • Twilio - The official Twilio PHP REST API.

Author: ziadoz
Source Code:
License: WTFPL License

#php #api 

What is GEEK

Buddha Community

Awesome PHP: Libraries for Accessing Third Party APIs

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response ='' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys

6 Popular PHP Libraries for Accessing Third Party APIs

In today's post we will learn about 6 Popular PHP Libraries for accessing third party APIs.

What is Accessing Third Party APIs?

Third party APIs are APIs provided by third parties - generally companies such as Facebook, Twitter, or Google - to allow you to access their functionality via JavaScript and use it on your site. One of the most obvious examples is using mapping APIs to display custom maps on your pages.

Table of contents:

  • Amazon Web Service SDK - The official PHP AWS SDK library.
  • Github - A library to interface with the Github API.
  • Mailgun - The official Mailgun PHP API.
  • Square - The official Square PHP SDK for payments and other Square APIs.
  • Stripe - The official Stripe PHP library.
  • Twilio - The official Twilio PHP REST API.

1 - Amazon Web Service SDK:

The official PHP AWS SDK library.

The AWS SDK for PHP makes it easy for developers to access Amazon Web Services in their PHP code, and build robust applications and software using services like Amazon S3, Amazon DynamoDB, Amazon Glacier, etc. You can get started in minutes by installing the SDK through Composer or by downloading a single zip or phar file from our latest release.

Getting Started

  1. Sign up for AWS – Before you begin, you need to sign up for an AWS account and retrieve your AWS credentials.
  2. Minimum requirements – To run the SDK, your system will need to meet the minimum requirements, including having PHP >= 5.5. We highly recommend having it compiled with the cURL extension and cURL 7.16.2+ compiled with a TLS backend (e.g., NSS or OpenSSL).
  3. Install the SDK – Using Composer is the recommended way to install the AWS SDK for PHP. The SDK is available via Packagist under the aws/aws-sdk-php package. If Composer is installed globally on your system, you can run the following in the base directory of your project to add the SDK as a dependency:
composer require aws/aws-sdk-php
  1. Please see the Installation section of the User Guide for more detailed information about installing the SDK through Composer and other means.
  2. Using the SDK – The best way to become familiar with how to use the SDK is to read the User Guide. The Getting Started Guide will help you become familiar with the basic concepts.
  3. Beta: Removing unused services — To date, there are over 300 AWS services available for use with this SDK. You will likely not need them all. If you use Composer and would like to learn more about this feature, please read the linked documentation.

Quick Examples

Create an Amazon S3 client

// Require the Composer autoloader.
require 'vendor/autoload.php';

use Aws\S3\S3Client;

// Instantiate an Amazon S3 client.
$s3 = new S3Client([
    'version' => 'latest',
    'region'  => 'us-west-2'

Upload a file to Amazon S3

// Upload a publicly accessible file. The file size and type are determined by the SDK.
try {
        'Bucket' => 'my-bucket',
        'Key'    => 'my-object',
        'Body'   => fopen('/path/to/file', 'r'),
        'ACL'    => 'public-read',
} catch (Aws\S3\Exception\S3Exception $e) {
    echo "There was an error uploading the file.\n";


View on Github

2 - Github:

A library to interface with the Github API.

Uses GitHub API v3 & supports GitHub API v4. The object API (v3) is very similar to the RESTful API.


  • Light and fast thanks to lazy loading of API classes
  • Extensively tested and documented


Quick install

Via Composer.

This command will get you up and running quickly with a Guzzle HTTP client.

composer require knplabs/github-api:^3.0 guzzlehttp/guzzle:^7.0.1 http-interop/http-factory-guzzle:^1.0

Advanced install

We are decoupled from any HTTP messaging client with help by HTTPlug.

Using a different http client

composer require knplabs/github-api:^3.0 symfony/http-client nyholm/psr7

To set up the Github client with this HTTP client

use Github\Client;
use Symfony\Component\HttpClient\HttplugClient;

$client = Client::createWithHttpClient(new HttplugClient());

Read more about using different clients in our docs.

Framework integrations


To integrate this library in laravel Graham Campbell created graham-campbell/github. See the installation instructions to get started in laravel.

Basic usage of php-github-api client


// This file is generated by Composer
require_once __DIR__ . '/vendor/autoload.php';

$client = new \Github\Client();
$repositories = $client->api('user')->repositories('ornicar');

From $client object, you have access to all available GitHub api endpoints.

View on Github

3 - Mailgun:

The official Mailgun PHP API.

This is the Mailgun PHP SDK. This SDK contains methods for easily interacting with the Mailgun API. Below are examples to get you started.


To install the SDK, you will need to be using Composer in your project. If you aren't using Composer yet, it's really simple! Here's how to install composer:

curl -sS | php

The Mailgun API Client is not hard coupled to Guzzle, Buzz or any other library that sends HTTP messages. Instead, it uses the PSR-18 client abstraction. This will give you the flexibility to choose what PSR-7 implementation and HTTP client you want to use.

If you just want to get started quickly you should run the following command:

composer require mailgun/mailgun-php symfony/http-client nyholm/psr7


You should always use Composer autoloader in your application to automatically load your dependencies. All the examples below assume you've already included this in your file:

require 'vendor/autoload.php';
use Mailgun\Mailgun;

Here's how to send a message using the SDK:

// First, instantiate the SDK with your API credentials
$mg = Mailgun::create('key-example'); // For US servers
$mg = Mailgun::create('key-example', ''); // For EU servers

// Now, compose and send your message.
// $mg->messages()->send($domain, $params);
$mg->messages()->send('', [
  'from'    => '',
  'to'      => '',
  'subject' => 'The PHP SDK is awesome!',
  'text'    => 'It is so simple to send a message.'

Attention: $domain must match to the domain you have configured on

Usage of new method for updating web scheme

# Include the Autoloader (see "Libraries" for install instructions)
require 'vendor/autoload.php';
use Mailgun\Mailgun;

# Instantiate the client.
$mgClient = Mailgun::create('KEY', 'FULL_DOMAIN_URL');
$domain = "DOMAIN";

# Issue the call to the client.
$result = $mgClient->domains()->updateWebScheme($domain, 'https');


Custom http request to the API

# Include the Autoloader (see "Libraries" for install instructions)
require 'vendor/autoload.php';
use Mailgun\Mailgun;

# Instantiate the client.
$mgClient = Mailgun::create('KEY', 'ENDPOINT');
$domain = "DOMAIN";

$path = 'some path';
$params = [];

# Issue the call to the client.
$resultPost = $mgClient->httpClient()->httpPost($path, $params);

$resultGet = $mgClient->httpClient()->httpGet($path, $params);

$resultPut = $mgClient->httpClient()->httpPut($path, $params);

$resultDelete = $mgClient->httpClient()->httpDelete($path, $params);

View on Github

4 - Square:

The official Square PHP SDK for payments and other Square APIs.

The Square Connect PHP SDK is retired (EOL) as of 2020-06-10 and will no longer receive bug fixes or product updates. To continue receiving API and SDK improvements, please follow the instructions below to migrate to the new Square PHP SDK.

The old Connect SDK documentation is available under the /docs folder.

Migrate to the Square PHP SDK

Follow the instructions below to migrate your apps from the deprecated square/connect sdk to the new library.

You need to update your app to use the Square PHP SDK instead of the Connect PHP SDK The Square PHP SDK uses the square/square identifier.

On the command line, run:

$ php composer.phar require square/square


Update your composer.json:

"require": {
    "square/square": "^5.0.0",

Update your code

  1. Change all instances of use SquareConnect\... to use Square\....
  2. Replace SquareConnect models with the new Square equivalents
  3. Update client instantiation to follow the method outlined below.
  4. Update code for accessing response data to follow the method outlined below.
  5. Check $apiResponse->isSuccess() or $apiResponse->isError() to determine if the call was a success.

To simplify your code, we also recommend that you use method chaining to access APIs instead of explicitly instantiating multiple clients.

Client instantiation

Connect SDK

require 'vendor/autoload.php';

use SquareConnect\Configuration;
use SquareConnect\ApiClient;

$access_token = 'YOUR_ACCESS_TOKEN';
# setup authorization
$api_config = new Configuration();
$api_client = new ApiClient($api_config);

Square SDK

require 'vendor/autoload.php';

use Square\SquareClient;
use Square\Environment;

// Initialize the Square client.
$api_client = new SquareClient([
  'accessToken' => "YOUR_ACCESS_TOKEN",
  'environment' => Environment::SANDBOX
]); // In production, the environment arg is 'production'

View on Github

5 - Stripe:

The official Stripe PHP library.

The Stripe PHP library provides convenient access to the Stripe API from applications written in the PHP language. It includes a pre-defined set of classes for API resources that initialize themselves dynamically from API responses which makes it compatible with a wide range of versions of the Stripe API.


PHP 5.6.0 and later.


You can install the bindings via Composer. Run the following command:

composer require stripe/stripe-php

To use the bindings, use Composer's autoload:


Manual Installation

If you do not wish to use Composer, you can download the latest release. Then, to use the bindings, include the init.php file.



The bindings require the following extensions in order to work properly:

  • curl, although you can use your own non-cURL client if you prefer
  • json
  • mbstring (Multibyte String)

If you use Composer, these dependencies should be handled automatically. If you install manually, you'll want to make sure that these extensions are available.

Getting Started

Simple usage looks like:

$stripe = new \Stripe\StripeClient('sk_test_BQokikJOvBiI2HlWgH4olfQ2');
$customer = $stripe->customers->create([
    'description' => 'example customer',
    'email' => '',
    'payment_method' => 'pm_card_visa',
echo $customer;

Client/service patterns vs legacy patterns

You can continue to use the legacy integration patterns used prior to version 7.33.0. Review the migration guide for the backwards-compatible client/services pattern changes.

Custom Request Timeouts

Note We do not recommend decreasing the timeout for non-read-only calls (e.g. charge creation), since even if you locally timeout, the request on Stripe's side can still complete. If you are decreasing timeouts on these calls, make sure to use idempotency tokens to avoid executing the same transaction twice as a result of timeout retry logic.

To modify request timeouts (connect or total, in seconds) you'll need to tell the API client to use a CurlClient other than its default. You'll set the timeouts in that CurlClient.

// set up your tweaked Curl client
$curl = new \Stripe\HttpClient\CurlClient();
$curl->setTimeout(10); // default is \Stripe\HttpClient\CurlClient::DEFAULT_TIMEOUT
$curl->setConnectTimeout(5); // default is \Stripe\HttpClient\CurlClient::DEFAULT_CONNECT_TIMEOUT

echo $curl->getTimeout(); // 10
echo $curl->getConnectTimeout(); // 5

// tell Stripe to use the tweaked client

// use the Stripe API client as you normally would

View on Github

6 - Twilio:

The official Twilio PHP REST API.


twilio-php uses a modified version of Semantic Versioning for all changes. See this document for details.


You can install twilio-php via composer or by downloading the source.

Via Composer:

twilio-php is available on Packagist as the twilio/sdk package:

composer require twilio/sdk


Send an SMS

// Send an SMS using Twilio's REST API and PHP
$sid = "ACXXXXXX"; // Your Account SID from
$token = "YYYYYY"; // Your Auth Token from

$client = new Twilio\Rest\Client($sid, $token);
$message = $client->messages->create(
  '8881231234', // Text this number
    'from' => '9991231234', // From a valid Twilio number
    'body' => 'Hello from Twilio!'

print $message->sid;

Make a Call

$sid = "ACXXXXXX"; // Your Account SID from
$token = "YYYYYY"; // Your Auth Token from

$client = new Twilio\Rest\Client($sid, $token);

// Read TwiML at this URL when a call connects (hold music)
$call = $client->calls->create(
  '8881231234', // Call this number
  '9991231234', // From a valid Twilio number
      'url' => ''

Specify Region and/or Edge

To take advantage of Twilio's Global Infrastructure, specify the target Region and/or Edge for the client:

$sid = "ACXXXXXX"; // Your Account SID from
$token = "YYYYYY"; // Your Auth Token from

$client = new Twilio\Rest\Client($sid, $token, null, 'au1');

A Client constructor without these parameters will also look for TWILIO_REGION and TWILIO_EDGE variables inside the current environment.

This will result in the hostname transforming from to

Enable Debug Logging

There are two ways to enable debug logging in the default HTTP client. You can create an environment variable called TWILIO_LOG_LEVEL and set it to debug or you can set the log level to debug:

$sid = "ACXXXXXX"; // Your Account SID from
$token = "YYYYYY"; // Your Auth Token from

$client = new Twilio\Rest\Client($sid, $token);

View on Github

Thank you for following this article.

Related videos:

Working with 3rd party APIs in Laravel

#php #accessing #third #apis 

Autumn  Blick

Autumn Blick


Public ASX100 APIs: The Essential List

We’ve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.


The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:

  1. Whether the company had a public API: this was found by googling “[company name] API” and “[company name] API developer” and “[company name] developer portal”. Sometimes the company’s website was navigated or searched.
  2. Some data points about the API were noted, such as the URL of the portal/documentation and the method they used to publish the API (portal, documentation, web page).
  3. Observations were recorded that piqued the interest of the researchers (you will find these below).
  4. Other notes were made to support future research.
  5. You will find a summary of the data in the infographic below.


With regards to how the APIs are shared:

#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway

An API-First Approach For Designing Restful APIs | Hacker Noon

I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.

So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.

First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.

Preparing the ground

Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.


If you desire to reproduce the examples that will be shown here, you will need some of those items below.

  • NodeJS
  • OpenAPI Specification
  • Text Editor (I’ll use VSCode)
  • Command Line

Use Case

To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.

#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api

Marcelle  Smith

Marcelle Smith


What Are Good Traits That Make Great API Product Managers

As more companies realize the benefits of an API-first mindset and treating their APIs as products, there is a growing need for good API product management practices to make a company’s API strategy a reality. However, API product management is a relatively new field with little established knowledge on what is API product management and what a PM should be doing to ensure their API platform is successful.

Many of the current practices of API product management have carried over from other products and platforms like web and mobile, but API products have their own unique set of challenges due to the way they are marketed and used by customers. While it would be rare for a consumer mobile app to have detailed developer docs and a developer relations team, you’ll find these items common among API product-focused companies. A second unique challenge is that APIs are very developer-centric and many times API PMs are engineers themselves. Yet, this can cause an API or developer program to lose empathy for what their customers actually want if good processes are not in place. Just because you’re an engineer, don’t assume your customers will want the same features and use cases that you want.

This guide lays out what is API product management and some of the things you should be doing to be a good product manager.

#api #analytics #apis #product management #api best practices #api platform #api adoption #product managers #api product #api metrics