SendGrid's PHP HTTP Client for calling APIs

Overview

SendGrid Logo

Tests Latest Version on Packagist Twitter Follow GitHub contributors MIT licensed

Quickly and easily access any RESTful or RESTful-like API.

If you are looking for the SendGrid API client library, please see this repo.

Announcements

The default branch name for this repository has been changed to main as of 07/27/2020.

All updates to this library are documented in our CHANGELOG.

Table of Contents

Installation

Prerequisites

  • PHP version 5.6, 7.0, 7.1, 7.2, 7.3, or 7.4

Install with Composer

Add php-http-client to your composer.json file. If you are not using Composer, you should be. It's an excellent way to manage dependencies in your PHP application.

{
  "require": {
    "sendgrid/php-http-client": "^3.14.4"
  }
}

Then at the top of your PHP script require the autoloader:

require __DIR__ . '/vendor/autoload.php';

Then from the command line:

composer install

Install without Composer

You should create a lib directory in the directory of your application and clone to lib repositories php-http-client and sendgrid-php:

$ cd /path/to/your/app
$ mkdir lib
$ cd lib
$ git clone https://github.com/sendgrid/php-http-client.git

In the next step you should create loader.php:

$ cd /path/to/your/app
$ touch loader.php

And add the code below to the loader.php:



require_once __DIR__ . '/lib/php-http-client/lib/Client.php';
require_once __DIR__ . '/lib/php-http-client/lib/Response.php';

After it you can use the php-http-client library in your project:



include __DIR__ . '/loader.php';

$client = new SendGrid\Client();

Quick Start

Here is a quick example:

GET /your/api/{param}/call

// include __DIR__ . '/loader.php';
require 'vendor/autoload.php';
$apiKey = YOUR_SENDGRID_API_KEY;
$authHeaders = [
    'Authorization: Bearer ' . $apiKey
];
$client = new SendGrid\Client('https://api.sendgrid.com', $authHeaders);
$param = 'foo';
$response = $client->your()->api()->_($param)->call()->get();

var_dump(
    $response->statusCode(),
    $response->headers(),
    $response->body()
);

POST /your/api/{param}/call with headers, query parameters and a request body with versioning.

// include __DIR__ . '/loader.php';
require 'vendor/autoload.php';
$apiKey = YOUR_SENDGRID_API_KEY;
$authHeaders = [
    'Authorization: Bearer ' . $apiKey
];
$client = new SendGrid\Client('https://api.sendgrid.com', $authHeaders);
$queryParams = [
    'hello' => 0, 'world' => 1
];
$requestHeaders = [
    'X-Test' => 'test'
];
$data = [
    'some' => 1, 'awesome' => 2, 'data' => 3
];
$param = 'bar';
$response = $client->your()->api()->_($param)->call()->post($data, $queryParams, $requestHeaders);

var_dump(
    $response->statusCode(),
    $response->headers(),
    $response->body()
);

If there is an issues with the request, such as misconfigured CURL SSL options, an InvalidRequest will be thrown with message from CURL on why the request failed. Use the message as a hit to troubleshooting steps of your environment.

Usage

Environment Variables

You can do the following to create a .env file:

cp .env_example .env

Then, just add your API Key into your .env file.

How to Contribute

We encourage contribution to our libraries, please see our CONTRIBUTING guide for details.

Quick links:

Thanks

We were inspired by the work done on birdy and universalclient.

About

php-http-client is maintained and funded by Twilio SendGrid, Inc. The names and logos for php-http-client are trademarks of Twilio SendGrid, Inc.

If you need help installing or using the library, please check the Twilio SendGrid Support Help Center.

If you've instead found a bug in the library or would like new features added, go ahead and open issues or pull requests against this repo!

License

The MIT License (MIT)

Comments
  • Exception Handling

    Exception Handling

    Closes: https://github.com/sendgrid/sendgrid-php/issues/753

    Checklist

    • [x] have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] have read the [Contribution Guide] and my PR follows them.
    • [x] updated my branch with the development branch.
    • [x] have added necessary documentation about the functionality in the appropriate .md file
    • [x] have added in line documentation to the code I modified

    Short description of what this PR does:

    By default SendGrid client doesn't care about 4xx & 5xx HTTP status codes. For easy handling you can force to throw exception in that cases or even set error code for that cases.

    		$sendgrid = new SendGrid(<<API_KEY>>);
    		$sendgrid->client->setThrowException(true);
    
    		try {
    			$response = $sendgrid->send($email);
    		}
    		catch(ClientException $e) {
    			dump($e);
    			exit;
    		}
    

    image

    Without try catch error message will be well formated

    image

    ClientException class extends Exception and has some additional functions:

    1. getErrors - will return array of Errors
    2. getHttpStatus - HTTP status code
    3. getShortTrace - pointing where $sendgrid->send($email); was invoked
    4. getFullTrace - standart trace

    If you have questions, please send an email to [email protected], or file a Github Issue in this repository.

    status: code review request 
    opened by Falseclock 12
  • implements sending concurrent requests with curl multi

    implements sending concurrent requests with curl multi

    #hacktoberfest

    This is an improvement as a partial answer to https://github.com/sendgrid/sendgrid-php/issues/259

    Allow requests to be sent concurrently.

    Works exactly like the single request, but use curl_multi_ family.

    status: code review request difficulty: hard 
    opened by lightbringer1991 12
  • feat: Throw an InvalidRequest whenever a curl request fails

    feat: Throw an InvalidRequest whenever a curl request fails

    Fixes #90

    This is one of three possible solutions to #90. #104 is similar but doesn't use catchable exceptions, and #105 is more about avoiding the issue than notifying the user.

    Checklist

    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the [Contribution Guide] and my PR follows them.
    • [x] I updated my branch with the master branch.
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [x] I have added necessary documentation about the functionality in the appropriate .md file
    • [x] I have added in line documentation to the code I modified

    Short description of what this PR does:

    • An exception will be thrown if a curl request fails due to something like SSL verification (BC break)
    • Uses composer/ca-bundle (if installed) to locate the system's CA bundle or fall back to Mozilla's (#105)
    status: code review request difficulty: medium 
    opened by colinodell 10
  • Create USAGE.md

    Create USAGE.md

    Fixes https://github.com/sendgrid/php-http-client/issues/50

    Checklist

    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the [Contribution Guide] and my PR follows them.
    • [x] I updated my branch with the master branch.
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [x] I have added necessary documentation about the functionality in the appropriate .md file
    • [x] I have added in line documentation to the code I modified

    Short description of what this PR does:

    If you have questions, please send an email to Sendgrid, or file a Github Issue in this repository.

    status: code review request 
    opened by nvzard 8
  • Throw InvalidRequest exception on invalid CURL request

    Throw InvalidRequest exception on invalid CURL request

    Fixes

    #90

    Checklist

    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the [Contribution Guide] and my PR follows them.
    • [x] I updated my branch with the master branch.
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [x] I have added necessary documentation about the functionality in the appropriate .md file
    • [x] I have added in line documentation to the code I modified

    Short description of what this PR does:

    • Currently, if there are any issues with requests, the library exists silently with response code 0. This creates confusion about whether the problem was detected at SendGrid server or locally, what should be done next. This PR introduces an exception thrown with message from CURL about why actually request fails.
    • Not doing a specific exception as outlined in #90 because
      1. there are many reasons why request (SSL or not) could fail, and that was just a single example. No point replicating every possible CURL error into an exception.
      2. Difficult to unit test full working connection to replicate network conditions.
    type: community enhancement difficulty: medium status: ready for deploy 
    opened by alextech 7
  • feat: Add docker compose file for a containerized development environment

    feat: Add docker compose file for a containerized development environment

    Fixes #49

    Checklist

    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the [Contribution Guide] and my PR follows them.
    • [x] I updated my branch with the master branch.
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [x] I have added necessary documentation about the functionality in the appropriate .md file
    • [x] I have added in line documentation to the code I modified

    Short description of what this PR does:

    This PR adds a docker compose file for a containerized development environment.

    type: community enhancement status: waiting for feedback 
    opened by michaeljdennis 7
  • feat: Build URL with multiple instances of the same param

    feat: Build URL with multiple instances of the same param

    Checklist

    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the [Contribution Guide] and my PR follows them.
    • [x] I updated my branch with the master branch.
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [x] I have added necessary documentation about the functionality in the appropriate .md file
    • [x] I have added in line documentation to the code I modified

    Short description of what this PR does:

    A number of APIs accept what is documented as "array of string". In practice, it's a number of instances of identical URL arguments with different values.

    For example from retrieving subuser reputations:

    https://api.sendgrid.com/v3/subusers/reputations?usernames=myfirstsubuser&usernames=mysecondsubuser&usernames=mythirdsubuser
    

    I updated the buildUrl() function to accept nested arrays so that you could form the above URL with the query:

    $queryParams = [
      'usernames' => [
        'myfirstsubuser',
        'mysecondsubuser',
        'mythirdsubuser',
      ],
    ];
    

    If you have questions, please send an email to Sendgrid, or file a Github Issue in this repository.

    status: code review request 
    opened by agh1 6
  • feat: automatic code style checking

    feat: automatic code style checking

    Fixes

    Closes #108

    Checklist

    • [ ] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the [Contribution Guide] and my PR follows them.
    • [x] I updated my branch with the master branch.
    • [ ] I have added tests that prove my fix is effective or that my feature works
    • [ ] I have added necessary documentation about the functionality in the appropriate .md file
    • [ ] I have added in line documentation to the code I modified

    Short description of what this PR does:

    • Run code style authomatic checking (PSR-1, PSR-2) on TravisCI build
    • Make it possible to run unit tests and CS check with Composer commands
    • Some fixes in TravisCI project configuration
    status: code review request difficulty: medium type: twilio enhancement 
    opened by misantron 6
  • __call method refactoring

    __call method refactoring

    Partially reducing the magic method as a code smell. This version still compatible with old versions, but there will be necessary to change Client class signature to increase code readability. PS: Sorry for the last PR failed tests

    opened by vitya1 6
  • docs: Add first-timers.md for newcomers

    docs: Add first-timers.md for newcomers

    Closes #112

    Fixes

    Checklist

    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the [Contribution Guide] and my PR follows them.
    • [x] I updated my branch with the master branch.
    • [ ] I have added tests that prove my fix is effective or that my feature works
    • [x] I have added necessary documentation about the functionality in the appropriate .md file
    • [ ] I have added in line documentation to the code I modified

    Short description of what this PR does:

    This PR adds a First Timers.MD with a guideline for newcomers

    status: code review request difficulty: medium 
    opened by daniloff200 5
  • Only mention the lowest required PHP version in README

    Only mention the lowest required PHP version in README

    Checklist

    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the [Contribution Guide] and my PR follows them.
    • [x] I updated my branch with the master branch.
    • [ ] ~I have added tests that prove my fix is effective or that my feature works~
    • [ ] ~I have added necessary documentation about the functionality in the appropriate .md file~
    • [ ] ~I have added in line documentation to the code I modified~

    Short description of what this PR does:

    This PR makes sure the README mirrors what is actually required in the code. As per the composer.json, this library requires PHP 5.6 or higher. Let's not confuse users by only mentioning PHP 5.6 and 7.0 in the README.

    difficulty: easy type: docs update status: ready for deploy 
    opened by svenluijten 5
  • chore: Add missing method annotation `validations`

    chore: Add missing method annotation `validations`

    Hi @rakatyal, @childish-sambino, @JenniferMah

    Fixes

    When using the validation/email endpoint, the php code is the following one:

    $sg->client->validations()->email()->post($request_body);
    

    cf the doc https://docs.sendgrid.com/api-reference/e-mail-address-validation/validate-an-email

    But there is no autocompletion because of a missing @method annotation. @method email() was already added, but not @method validations ; This PR fix this.

    Same for method related to the following chapter https://docs.sendgrid.com/api-reference/contacts-api-recipients/add-recipients

    Checklist

    • [x] I acknowledge that all my contributions will be made under the project's license
    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the Contribution Guidelines and my PR follows them
    • [x] I have titled the PR appropriately
    • [x] I have updated my branch with the main branch
    • [ ] I have added tests that prove my fix is effective or that my feature works
    • [ ] I have added the necessary documentation about the functionality in the appropriate .md file
    • [ ] I have added inline documentation to the code I modified

    If you have questions, please file a support ticket.

    opened by VincentLanglet 0
  • chore: adding domains related method documentation

    chore: adding domains related method documentation

    Fixes

    Small PR for adding domains related method documentation, to help our IDE with these endpoints (https://docs.sendgrid.com/api-reference/domain-authentication/list-all-authenticated-domains for example). No code changes, just PHPDoc.

    Checklist

    • [x] I acknowledge that all my contributions will be made under the project's license
    • [x] I have made a material change to the repo (functionality, testing, spelling, grammar)
    • [x] I have read the Contribution Guidelines and my PR follows them
    • [x] I have titled the PR appropriately
    • [x] I have updated my branch with the main branch
    • [ ] I have added tests that prove my fix is effective or that my feature works
    • [ ] I have added the necessary documentation about the functionality in the appropriate .md file
    • [ ] I have added inline documentation to the code I modified
    opened by Gregory-Gerard 0
Releases(4.0.0)
Owner
Twilio SendGrid
Official open source libraries - send emails and integrate with our APIs fast.
Twilio SendGrid
json-rpc client base on http

laravel JSON-RPC客户端(Http协议) 本项目是基于JSON-RPC的服务端端实现的rpc客户端 server端见:https://sajya.github.io/ 初始化 发布 php artisan vendor:publish --provider="Ze\JsonRpcCli

Zeee 2 Nov 19, 2021
json-rpc client base on http

laravel JSON-RPC客户端(Http协议) 本项目是基于JSON-RPC的服务端端实现的rpc客户端 server端见:https://sajya.github.io/ 初始化 1.发布 php artisan vendor:publish --provider="Ze\JsonRPCC

null 2 Nov 19, 2021
HTTP Requestor: Package for a client request that supports you to make an external service request easily and with fast usage.

HttpRequestor from Patienceman HTTP Requestor: Package for a client request that supports you to make an external service request easily and with fast

Manirabona Patience 2 Aug 26, 2022
Use rmccue/requests as a PSR-18 HTTP client

WordPress/Requests PSR-18 Adapter Use WordPress/Requests as a PSR-18 HTTP client adapter. Requires PHP 7.1+ Why? Requests is a HTTP library written in

Artur Weigandt 5 Dec 15, 2022
PHP JSON-RPC 2.0 Server/Client Implementation with Automatic Client Class Generation via SMD

PHP JSON-RPC 2.0 Server/Client Implementation with Automatic Client Class Generation via SMD

Sergey Bykov 63 Feb 14, 2022
OpenAI API Client is a component-oriented, extensible client library for the OpenAI API. It's designed to be faster and more memory efficient than traditional PHP libraries.

OpenAI API Client in PHP (community-maintained) This library is a component-oriented, extensible client library for the OpenAI API. It's designed to b

Mounir R'Quiba 6 Jun 14, 2023
OVHcloud APIs lightweight PHP wrapper

Lightweight PHP wrapper for OVHcloud APIs - The easiest way to use OVHcloud APIs in your PHP applications - Compatible with PHP 7.4, 8.0, 8.1 - Not affiliated with OVHcloud

Germain Carré 3 Sep 10, 2022
Laravel Package for 1APP. Learn how to integrate our APIs to build a web or mobile integration to send and accept payments for your application and businesses.

1APP Laravel Library Learn how to integrate our APIs to build a web or mobile integration to accept payments, make payment of Bills and as well custom

O'Bounce Technologies 4 Jul 25, 2022
⚡️ Web3 PHP is a supercharged PHP API client that allows you to interact with a generic Ethereum RPC.

Web3 PHP is a supercharged PHP API client that allows you to interact with a generic Ethereum RPC. This project is a work-in-progress. Code and docume

Web3 PHP 665 Dec 23, 2022
A simple PHP GitHub API client, Object Oriented, tested and documented.

PHP GitHub API A simple Object Oriented wrapper for GitHub API, written with PHP. Uses GitHub API v3 & supports GitHub API v4. The object API (v3) is

KNP Labs 2k Jan 7, 2023
A simple Object Oriented PHP Client for Termii SMS API

Termii Client A simple Object Oriented PHP Client for Termii SMS API. Uses Termii API. Requirements PHP >= 7.2 Guzzlehttp ~6|~7 Installation Via Compo

Ilesanmi Olawale Adedotun 5 Feb 24, 2022
Xendit REST API Client for PHP - Card, Virtual Account, Invoice, Disbursement, Recurring Payments, Payout, EWallet, Balance, Retail Outlets Services

Xendit REST API Client for PHP - Card, Virtual Account, Invoice, Disbursement, Recurring Payments, Payout, EWallet, Balance, Retail Outlets Services

Xendit 96 Jan 6, 2023
PHP client for Kafka

A library to allow people to communicate to Kafka using plain PHP, compatible with Kafka v0.11+ (due to the way the protocol works).

Luís Cobucci 52 Dec 23, 2022
php 8 client for the lemon.markets api

lemon.markets php client This repository contains a php 8+ compatible client for the https://lemon.markets API. The documentation of the API can be fo

Daniel Freudenberger 4 Nov 17, 2022
PHP client for Microsoft Azure Face API.

Microsoft Azure Face API PHP client A PHP library that utilizes Azure Face REST API. Requirements PHP >= 7.4 Installation composer require darmen/php-

Darmen Amanbayev 6 Sep 14, 2022
Google PHP API Client Services

Google PHP API Client Services

Google APIs 1.1k Dec 22, 2022
AltiriaSmsPhpClient, the official PHP client of Altiria

Altiria, cliente SMS PHP Altiria SMS PHP es un cliente que simplifica al máximo la integración de nuestro API para PHP. Por el momento, esta librería

Altiria 3 Dec 22, 2022
PHP Client for the GoFlink API

GoFlink PHP API Client This project is an unofficial library to communicate with the GoFlink API from your PHP project. Documentation about the API is

Rico Hageman 4 Oct 3, 2022
A PHP client for the official Kizeo Forms API V3+. 📌

Kizeo Forms API V3+ - PHP This is a Swagger generated doc for Kizeo REST API 3. You can find additionnal documentation here : Online documentation. Th

siapepfrance 1 Oct 26, 2021