PHPackages                             apimatic/unirest-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. apimatic/unirest-php

ActiveLibrary[HTTP &amp; Networking](/categories/http)

apimatic/unirest-php
====================

Unirest PHP

4.0.7(11mo ago)224.7M—7.1%1220MITPHPPHP ^7.2 || ^8.0CI passing

Since Feb 19Pushed 4mo ago4 watchersCompare

[ Source](https://github.com/apimatic/unirest-php)[ Packagist](https://packagist.org/packages/apimatic/unirest-php)[ Docs](https://github.com/apimatic/unirest-php)[ RSS](/packages/apimatic-unirest-php/feed)WikiDiscussions v2-master Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (31)Used By (20)

Unirest for PHP
===============

[](#unirest-for-php)

[![version](https://camo.githubusercontent.com/d10a8a4221badc617d293a712c2ee4d3c3e9f52951e7fdad6e53ad2ccbd4d594/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6170696d617469632f756e69726573742d7068702e7376673f7374796c653d666c6174)](https://packagist.org/packages/apimatic/unirest-php)[![Downloads](https://camo.githubusercontent.com/2437e8e17faa35a054ee785b43cbaa8622828712537119773323106db927f9b4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f6170696d617469632f756e69726573742d7068702e7376673f7374796c653d666c6174)](https://packagist.org/packages/apimatic/unirest-php)[![Tests](https://github.com/apimatic/unirest-php/actions/workflows/php.yml/badge.svg)](https://github.com/apimatic/unirest-php/actions/workflows/php.yml)[![Maintainability Rating](https://camo.githubusercontent.com/fdf26b3aa7221600d0dd5100d14a0e5d911d227edc1a550c32fdbb38b924ed9a/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d6170696d617469635f756e69726573742d706870266d65747269633d7371616c655f726174696e67)](https://sonarcloud.io/summary/new_code?id=apimatic_unirest-php)[![Vulnerabilities](https://camo.githubusercontent.com/fbb45c3beafaaca560518cce1d195bf7cd45404d24b0e5c062fa06a2e0c25d24/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d6170696d617469635f756e69726573742d706870266d65747269633d76756c6e65726162696c6974696573)](https://sonarcloud.io/summary/new_code?id=apimatic_unirest-php)[![License](https://camo.githubusercontent.com/cb16ec04855726e5d9d615d25ffe34cb96f0f2d1d8b12e4fb4099775480ee269/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6170696d617469632f756e69726573742d7068702e7376673f7374796c653d666c6174)](https://github.com/apimatic/unirest-php/blob/master/LICENSE)

Unirest is a set of lightweight HTTP libraries available in [multiple languages](http://unirest.io).

This fork is maintained by [APIMatic](https://www.apimatic.io) for its Code Generator as a Service.

Features
--------

[](#features)

- Request class to create custom requests
- Simple HttpClientInterface to execute a Request
- Automatic JSON parsing into a native object for JSON responses
- Response data class to store http response information
- Supports form parameters, file uploads and custom body entities
- Supports gzip
- Supports Basic, Digest, Negotiate, NTLM Authentication natively
- Configuration class manage all the HttpClient's configurations
- Customizable timeout
- Customizable retries and backoff
- Customizable default headers for every request (DRY)

Supported PHP Versions
----------------------

[](#supported-php-versions)

- PHP 7.2
- PHP 7.4
- PHP 8.0
- PHP 8.1
- PHP 8.2

Installation
------------

[](#installation)

To install `apimatic/unirest-php` with Composer, just add the following to your `composer.json` file:

```
{
    "require": {
        "apimatic/unirest-php": "^4.0.0"
    }
}
```

or by running the following command:

```
composer require apimatic/unirest-php
```

Usage
-----

[](#usage)

### Creating a HttpClient with Default Configurations

[](#creating-a-httpclient-with-default-configurations)

You can create a variable at class level and instantiate it with an instance of `HttpClient`, like:

```
private $httpClient = new \Unirest\HttpClient();
```

### Creating a HttpClient with Custom Configurations

[](#creating-a-httpclient-with-custom-configurations)

To create a client with custom configurations you first required an instance of `Configuration`, and then add it to the HttpClient during its initialization, like:

```
$configurations = \Unirest\Configuration::init()
    ->timeout(10)
    ->enableRetries(true)
    ->retryInterval(2.5);
$httpClient = new \Unirest\HttpClient($configurations);
```

This `Configuration` instance can further be customized by setting properties like: `maximumRetryWaitTime`, `verifyPeer`, `defaultHeaders`, etc. Check out [Advanced Configuration](#advanced-configuration) for more information.

### Creating a Request

[](#creating-a-request)

After the initialization of HttpClient, you will be needing an instance of `Request` that is required to be exchanged as `Response`.

```
$request = new \Unirest\Request\Request(
    'http://mockbin.com/request',
    RequestMethod::GET,
    ['headerKey' => 'headerValue'],
    Unirest\Request\Body::json(["key" => "value"]'),
    RetryOption::ENABLE_RETRY
);
```

Let's look at a working example of sending the above request:

```
$headers = array('Accept' => 'application/json');
$query = array('foo' => 'hello', 'bar' => 'world');

$response = $this->httpClient->execute($request);

$response->getStatusCode(); // HTTP Status code
$response->getHeaders();    // Headers
$response->getBody();       // Parsed body
$response->getRawBody();    // Unparsed body
```

### JSON Requests *(`application/json`)*

[](#json-requests-applicationjson)

A JSON Request can be constructed using the `Unirest\Request\Body::Json` helper:

```
$headers = array('Accept' => 'application/json');
$data = array('name' => 'ahmad', 'company' => 'mashape');

$body = Unirest\Request\Body::Json($data);
$request = new \Unirest\Request\Request(
    'http://mockbin.com/request',
    RequestMethod::POST,
    $headers,
    $body
);
$response = $this->httpClient->execute($request);
```

**Notes:**

- `Content-Type` headers will be automatically set to `application/json`
- the data variable will be processed through [`json_encode`](http://php.net/manual/en/function.json-encode.php) with default values for arguments.
- an error will be thrown if the [JSON Extension](http://php.net/manual/en/book.json.php) is not available.

### Form Requests *(`application/x-www-form-urlencoded`)*

[](#form-requests-applicationx-www-form-urlencoded)

A typical Form Request can be constructed using the `Unirest\Request\Body::Form` helper:

```
$headers = array('Accept' => 'application/json');
$data = array('name' => 'ahmad', 'company' => 'mashape');

$body = Unirest\Request\Body::Form($data);
$request = new \Unirest\Request\Request(
    'http://mockbin.com/request',
    RequestMethod::POST,
    $headers,
    $body
);
$response = $this->httpClient->execute($request);
```

**Notes:**

- `Content-Type` headers will be automatically set to `application/x-www-form-urlencoded`
- the final data array will be processed through [`http_build_query`](http://php.net/manual/en/function.http-build-query.php) with default values for arguments.

### Multipart Requests *(`multipart/form-data`)*

[](#multipart-requests-multipartform-data)

A Multipart Request can be constructed using the `Unirest\Request\Body::Multipart` helper:

```
$headers = array('Accept' => 'application/json');
$data = array('name' => 'ahmad', 'company' => 'mashape');

$body = Unirest\Request\Body::Multipart($data);
$request = new \Unirest\Request\Request(
    'http://mockbin.com/request',
    RequestMethod::POST,
    $headers,
    $body
);
$response = $this->httpClient->execute($request);
```

**Notes:**

- `Content-Type` headers will be automatically set to `multipart/form-data`.
- an auto-generated `--boundary` will be set.

### Multipart File Upload

[](#multipart-file-upload)

simply add an array of files as the second argument to to the `Multipart` helper:

```
$headers = array('Accept' => 'application/json');
$data = array('name' => 'ahmad', 'company' => 'mashape');
$files = array('bio' => '/path/to/bio.txt', 'avatar' => '/path/to/avatar.jpg');

$body = Unirest\Request\Body::Multipart($data, $files);
$request = new \Unirest\Request\Request(
    'http://mockbin.com/request',
    RequestMethod::POST,
    $headers,
    $body
);
$response = $this->httpClient->execute($request);
```

If you wish to further customize the properties of files uploaded you can do so with the `Unirest\Request\Body::File` helper:

```
$headers = array('Accept' => 'application/json');
$body = array(
    'name' => 'ahmad',
    'company' => 'mashape'
    'bio' => Unirest\Request\Body::File('/path/to/bio.txt', 'text/plain'),
    'avatar' => Unirest\Request\Body::File('/path/to/my_avatar.jpg', 'text/plain', 'avatar.jpg')
);
$request = new \Unirest\Request\Request(
    'http://mockbin.com/request',
    RequestMethod::POST,
    $headers,
    $body
);
$response = $this->httpClient->execute($request);
```

**Note**: we did not use the `Unirest\Request\Body::multipart` helper in this example, it is not needed when manually adding files.

### Custom Body

[](#custom-body)

Sending a custom body such rather than using the `Unirest\Request\Body` helpers is also possible, for example, using a [`serialize`](http://php.net/manual/en/function.serialize.php) body string with a custom `Content-Type`:

```
$headers = array('Accept' => 'application/json', 'Content-Type' => 'application/x-php-serialized');
$body = serialize((array('foo' => 'hello', 'bar' => 'world'));
$request = new \Unirest\Request\Request(
    'http://mockbin.com/request',
    RequestMethod::POST,
    $headers,
    $body
);
$response = $this->httpClient->execute($request);
```

### Authentication

[](#authentication)

For Authentication you need httpClient instance with custom configurations, So, create `Configuration` instance like:

```
// Basic auth
$configuration = Configuration::init()
    ->auth('username', 'password', CURLAUTH_BASIC);
```

The third parameter, which is a bitmask, will Unirest which HTTP authentication method(s) you want it to use for your proxy authentication.

If more than one bit is set, Unirest *(at PHP's libcurl level)* will first query the site to see what authentication methods it supports and then pick the best one you allow it to use. *For some methods, this will induce an extra network round-trip.*

**Supported Methods**

MethodDescription`CURLAUTH_BASIC`HTTP Basic authentication. This is the default choice`CURLAUTH_DIGEST`HTTP Digest authentication. as defined in [RFC 2617](http://www.ietf.org/rfc/rfc2617.txt)`CURLAUTH_DIGEST_IE`HTTP Digest authentication with an IE flavor. *The IE flavor is simply that libcurl will use a special "quirk" that IE is known to have used before version 7 and that some servers require the client to use.*`CURLAUTH_NEGOTIATE`HTTP Negotiate (SPNEGO) authentication. as defined in [RFC 4559](http://www.ietf.org/rfc/rfc4559.txt)`CURLAUTH_NTLM`HTTP NTLM authentication. A proprietary protocol invented and used by Microsoft.`CURLAUTH_NTLM_WB`NTLM delegating to winbind helper. Authentication is performed by a separate binary application. *see [libcurl docs](http://curl.haxx.se/libcurl/c/CURLOPT_HTTPAUTH.html) for more info*`CURLAUTH_ANY`This is a convenience macro that sets all bits and thus makes libcurl pick any it finds suitable. libcurl will automatically select the one it finds most secure.`CURLAUTH_ANYSAFE`This is a convenience macro that sets all bits except Basic and thus makes libcurl pick any it finds suitable. libcurl will automatically select the one it finds most secure.`CURLAUTH_ONLY`This is a meta symbol. OR this value together with a single specific auth value to force libcurl to probe for un-restricted auth and if not, only that single auth algorithm is acceptable.```
// custom auth method
$configuration = Configuration::init()
    ->proxyAuth('username', 'password', CURLAUTH_DIGEST);
```

### Cookies

[](#cookies)

Set a cookie string to specify the contents of a cookie header. Multiple cookies are separated with a semicolon followed by a space (e.g., "fruit=apple; colour=red")

```
$configuration = Configuration::init()
    ->cookie($cookie);
```

Set a cookie file path for enabling cookie reading and storing cookies across multiple sequence of requests.

```
$this->request->cookieFile($cookieFile)
```

`$cookieFile` must be a correct path with write permission.

### Response Object

[](#response-object)

Upon receiving a response Unirest returns the result in the form of an Object, this object should always have the same keys for each language regarding to the response details.

- `getStatusCode()` - HTTP Response Status Code (Example `200`)
- `getHeaders()` - HTTP Response Headers
- `getBody()` - Parsed response body where applicable, for example JSON responses are parsed to Objects / Associative Arrays.
- `getRawBody()` - Un-parsed response body

### Advanced Configuration

[](#advanced-configuration)

You can set some advanced configuration to tune Unirest-PHP:

#### Custom JSON Decode Flags

[](#custom-json-decode-flags)

Unirest uses PHP's [JSON Extension](http://php.net/manual/en/book.json.php) for automatically decoding JSON responses. sometime you may want to return associative arrays, limit the depth of recursion, or use any of the [customization flags](http://php.net/manual/en/json.constants.php).

To do so, simply set the desired options using the `jsonOpts` request method:

```
$configuration = Configuration::init()
    ->jsonOpts(true, 512, JSON_NUMERIC_CHECK & JSON_FORCE_OBJECT & JSON_UNESCAPED_SLASHES);
```

#### Timeout

[](#timeout)

You can set a custom timeout value (in **seconds**):

```
$configuration = Configuration::init()
    ->timeout(5); // 5s timeout
```

#### Retries Related

[](#retries-related)

```
$configuration = Configuration::init()
    ->enableRetries(true)               // To enable retries feature
    ->maxNumberOfRetries(10)            // To set max number of retries
    ->retryOnTimeout(false)             // Should we retry on timeout
    ->retryInterval(20)                 // Initial retry interval in seconds
    ->maximumRetryWaitTime(30)          // Maximum retry wait time
    ->backoffFactor(1.1)                // Backoff factor to be used to increase retry interval
    ->httpStatusCodesToRetry([400,401]) // Http status codes to retry against
    ->httpMethodsToRetry(['POST'])      // Http methods to retry against
```

#### Proxy

[](#proxy)

Set the proxy to use for the upcoming request.

you can also set the proxy type to be one of `CURLPROXY_HTTP`, `CURLPROXY_HTTP_1_0`, `CURLPROXY_SOCKS4`, `CURLPROXY_SOCKS5`, `CURLPROXY_SOCKS4A`, and `CURLPROXY_SOCKS5_HOSTNAME`.

*check the [cURL docs](http://curl.haxx.se/libcurl/c/CURLOPT_PROXYTYPE.html) for more info*.

```
// quick setup with default port: 1080
$configuration = Configuration::init()
    ->proxy('10.10.10.1');

// custom port and proxy type
$configuration = Configuration::init()
    ->proxy('10.10.10.1', 8080, CURLPROXY_HTTP);

// enable tunneling
$configuration = Configuration::init()
    ->proxy('10.10.10.1', 8080, CURLPROXY_HTTP, true);
```

##### Proxy Authentication

[](#proxy-authentication)

Passing a username, password *(optional)*, defaults to Basic Authentication:

```
// basic auth
$configuration = Configuration::init()
    ->proxyAuth('username', 'password');
```

The third parameter, which is a bitmask, will Unirest which HTTP authentication method(s) you want it to use for your proxy authentication.

If more than one bit is set, Unirest *(at PHP's libcurl level)* will first query the site to see what authentication methods it supports and then pick the best one you allow it to use. *For some methods, this will induce an extra network round-trip.*

See [Authentication](#authentication) for more details on methods supported.

```
// basic auth
$configuration = Configuration::init()
    ->proxyAuth('username', 'password', CURLAUTH_DIGEST);
```

#### Default Request Headers

[](#default-request-headers)

You can set default headers that will be sent on every request:

```
$configuration = Configuration::init()
    ->defaultHeader('Header1', 'Value1')
    ->defaultHeader('Header2', 'Value2');
```

You can set default headers in bulk by passing an array:

```
$configuration = Configuration::init()
    ->defaultHeaders([
        'Header1' => 'Value1',
        'Header2' => 'Value2'
    ]);
```

You can clear the default headers anytime with:

```
$configuration = Configuration::init()
    ->clearDefaultHeaders();
```

#### Default cURL Options

[](#default-curl-options)

You can set default [cURL options](http://php.net/manual/en/function.curl-setopt.php) that will be sent on every request:

```
$configuration = Configuration::init()
    ->curlOpt(CURLOPT_COOKIE, 'foo=bar');
```

You can set options bulk by passing an array:

```
$configuration = Configuration::init()
    ->curlOpts(array(
    CURLOPT_COOKIE => 'foo=bar'
));
```

You can clear the default options anytime with:

```
$configuration = Configuration::init()
    ->clearCurlOpts();
```

#### SSL validation

[](#ssl-validation)

You can explicitly enable or disable SSL certificate validation when consuming an SSL protected endpoint:

```
$configuration = Configuration::init()
    ->verifyPeer(false); // Disables SSL cert validation
```

By default is `true`.

#### Utility Methods

[](#utility-methods)

```
// alias for `curl_getinfo`
$httpClient->getInfo();
```

---

###  Health Score

63

—

FairBetter than 99% of packages

Maintenance66

Regular maintenance activity

Popularity55

Moderate usage in the ecosystem

Community43

Growing community involvement

Maturity79

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~206 days

Recently: every ~201 days

Total

21

Last Release

335d ago

Major Versions

1.3.1 → 2.0.02020-04-07

2.3.0 → 3.0.02022-07-14

3.0.1 → 4.0.02022-09-30

PHP version history (5 changes)1.1PHP &gt;=5.3.0

1.3PHP &gt;=5.4.0

2.0.0PHP &gt;=5.6.0

4.0.0PHP &gt;=7.2 &lt;8.2

4.0.3PHP ^7.2 || ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/65c334b3d1ede690abde85f2839813a0fd24b0d0af03c3237a0820b15e9bded5?d=identicon)[apimatic](/maintainers/apimatic)

---

Top Contributors

[![ahmadnassri](https://avatars.githubusercontent.com/u/183195?v=4)](https://github.com/ahmadnassri "ahmadnassri (102 commits)")[![subnetmarco](https://avatars.githubusercontent.com/u/964813?v=4)](https://github.com/subnetmarco "subnetmarco (83 commits)")[![asadali214](https://avatars.githubusercontent.com/u/26116671?v=4)](https://github.com/asadali214 "asadali214 (27 commits)")[![esseguin](https://avatars.githubusercontent.com/u/1429412?v=4)](https://github.com/esseguin "esseguin (12 commits)")[![thehappybug](https://avatars.githubusercontent.com/u/3393530?v=4)](https://github.com/thehappybug "thehappybug (11 commits)")[![Mohammad-Haris](https://avatars.githubusercontent.com/u/34305911?v=4)](https://github.com/Mohammad-Haris "Mohammad-Haris (6 commits)")[![michelezonca](https://avatars.githubusercontent.com/u/392758?v=4)](https://github.com/michelezonca "michelezonca (6 commits)")[![MuHamza30](https://avatars.githubusercontent.com/u/199583608?v=4)](https://github.com/MuHamza30 "MuHamza30 (5 commits)")[![motdotla](https://avatars.githubusercontent.com/u/3848?v=4)](https://github.com/motdotla "motdotla (5 commits)")[![nijikokun](https://avatars.githubusercontent.com/u/198276?v=4)](https://github.com/nijikokun "nijikokun (5 commits)")[![jskrivseth](https://avatars.githubusercontent.com/u/8071570?v=4)](https://github.com/jskrivseth "jskrivseth (4 commits)")[![sonicaghi](https://avatars.githubusercontent.com/u/1213643?v=4)](https://github.com/sonicaghi "sonicaghi (3 commits)")[![thibaultcha](https://avatars.githubusercontent.com/u/1125431?v=4)](https://github.com/thibaultcha "thibaultcha (3 commits)")[![andreyvital](https://avatars.githubusercontent.com/u/967317?v=4)](https://github.com/andreyvital "andreyvital (3 commits)")[![frankdee](https://avatars.githubusercontent.com/u/5252262?v=4)](https://github.com/frankdee "frankdee (2 commits)")[![jasir](https://avatars.githubusercontent.com/u/115066?v=4)](https://github.com/jasir "jasir (2 commits)")[![MaryamAdnan3](https://avatars.githubusercontent.com/u/80243792?v=4)](https://github.com/MaryamAdnan3 "MaryamAdnan3 (2 commits)")[![cristianp6](https://avatars.githubusercontent.com/u/233734?v=4)](https://github.com/cristianp6 "cristianp6 (2 commits)")[![nikkobautista](https://avatars.githubusercontent.com/u/278104?v=4)](https://github.com/nikkobautista "nikkobautista (2 commits)")[![qpleple](https://avatars.githubusercontent.com/u/774546?v=4)](https://github.com/qpleple "qpleple (2 commits)")

---

Tags

clienthttphttp-clientphpresthttphttpsclientrestcurl

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/apimatic-unirest-php/health.svg)

```
[![Health](https://phpackages.com/badges/apimatic-unirest-php/health.svg)](https://phpackages.com/packages/apimatic-unirest-php)
```

###  Alternatives

[mashape/unirest-php

Unirest PHP

1.3k9.7M161](/packages/mashape-unirest-php)[zoonman/pixabay-php-api

PixabayClient is a PHP HTTP client library to access Pixabay's API

3354.7k](/packages/zoonman-pixabay-php-api)[e-moe/guzzle6-bundle

Integrates Guzzle 6 into your Symfony application

11259.2k](/packages/e-moe-guzzle6-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
