PHPackages                             valga/instagram-rest-api - 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. valga/instagram-rest-api

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

valga/instagram-rest-api
========================

A PHP wrapper for the Instagram REST and Search APIs

0.1.1(9y ago)23361[1 issues](https://github.com/valga/instagram-rest-api/issues)PHPPHP &gt;=5.6

Since Jun 12Pushed 9y ago1 watchersCompare

[ Source](https://github.com/valga/instagram-rest-api)[ Packagist](https://packagist.org/packages/valga/instagram-rest-api)[ RSS](/packages/valga-instagram-rest-api/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (6)Versions (3)Used By (0)

instagram-rest-api
==================

[](#instagram-rest-api)

A PHP wrapper for the Instagram REST and Search APIs.

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

[](#installation)

```
composer require valga/instagram-rest-api
```

Basic Usage
-----------

[](#basic-usage)

To use Instagram API you need to [create an application](https://www.instagram.com/developer/clients/register/) (if you don't have one yet).

```
$apiClient = new \InstagramRestApi\Client([
    'clientId' => 'YOUR_CLIENT_ID',
    'clientSecret' => 'YOUR_CLIENT_SECRET',
    'accessToken' => 'YOUR_ACCESS_TOKEN', // or null, if you don't have it yet
    'enforceSignedRequests' => false, // or true, if you have enabled this feature
]);
```

### Obtaining an access token

[](#obtaining-an-access-token)

```
try {
    $result = $apiClient->getAccessToken();
} catch (\Exception $e) {
    die(sprintf('Failed to obtain access token: %s', $e->getMessage()));
}

if ($result === null) {
    header('Location: '.$apiClient->getLoginUrl());
} else {
    printf('Your access token is: %s', $result->getAccessToken());
}
```

### Changing access token on the fly

[](#changing-access-token-on-the-fly)

```
$apiClient->getAuth()->setAccessToken($newAccessToken);
```

### Obtaining data from API endpoints

[](#obtaining-data-from-api-endpoints)

All endpoint responses have `getData()` method that returns needed data.

```
// Get a username of logged in user.
$user = $apiClient->users->getSelf()->getData();
print_r($user->getUsername());
```

### Available endpoints

[](#available-endpoints)

```
$comments = $apiClient->comments;
$comments->get($mediaId);
$comments->add($mediaId, $text);
$comments->delete($mediaId, $commentId);

$locations = $apiClient->locations;
$locations->get($locationId);
$locations->getRecentMedia($locationId);
$locations->search($lat, $lng);

$likes = $apiClient->likes;
$likes->get($mediaId);
$likes->add($mediaId);
$likes->delete($mediaId);

$media = $apiClient->media;
$media->getById($mediaId);
$media->getByShortcode($mediaShortcode);
$media->search($lat, $lng);

$relationships = $apiClient->relationships;
$relationships->approve($userId);
$relationships->ignore($userId);
$relationships->follow($userId);
$relationships->unfollow($userId);
$relationships->getStatus($userId);
$relationships->getFollowing();
$relationships->getFollowers();
$relationships->getPendingUsers();

$subscriptions = $apiClient->subscriptions;
$subscriptions->get();
$subscriptions->add($object, $aspect, $callbackUrl, $verifyToken);
$subscriptions->deleteById($subscriptionId);
$subscriptions->deleteByObject($object);

$tags = $apiClient->tags;
$tags->get($tag);
$tags->getRecentMedia($tag);
$tags->search($query);

$users = $apiClient->users;
$users->getSelf();
$users->getUser($userId);
$users->getSelfRecentMedia();
$users->getUserRecentMedia($userId);
$users->getSelfLikedMedia();
$users->search($query);
```

### Pagination

[](#pagination)

Just call `getNextPage()` method until it returns `null`.

```
// Get all media of logged in user.
$userMedia = [];
$result = $apiClient->users->getSelfRecentMedia();
do {
    foreach ($result->getData() as $media) {
        $userMedia[] = $media;
    }
} while (($result = $result->getNextPage()) !== null);
print_r($userMedia);
```

Advanced usage
--------------

[](#advanced-usage)

### Obtaining an access token

[](#obtaining-an-access-token-1)

```
$scopes = ['public_content'];
$requestData = $_GET;
$redirectUrl = 'YOUR_CUSTOM_REDIRECT_URL';
$csrfToken = 'YOUR_CSRF_TOKEN';

try {
    $result = $apiClient->getAccessToken($request, $csrfToken, $redirectUrl);
} catch (\Exception $e) {
    die(sprintf('Failed to obtain access token: %s', $e->getMessage()));
}

if ($result === null) {
    header('Location: '.$apiClient->getLoginUrl($scopes, $csrfToken, $redirectUrl));
    die();
} else {
    printf('Your access token is: %s', $result->getAccessToken());
}
```

### Exceptions system

[](#exceptions-system)

All high-level exceptions thrown by this library are inherited from `\InstagramRestApi\Exception\RequestException`.

```
RequestException
|- NetworkException - There was some error on network level.
|- InvalidResponseException - Response body is not a valid JSON object.
|- EndpointException
   |- OAuthException
      |- RateLimitException - You have exceeded rate limit.
      |- MissingPermissionException - You don't have required scope.
      |- InvalidSignatureException - Signature is missing or invalid.
      |- InvalidTokenException - Invalid or expired token.
   |- InvalidParametersException
   |- NotFoundException - Requested object does not exist.
   |- SubscriptionException

```

### Rate limits

[](#rate-limits)

```
$result = $apiClient->users->getSelfRecentMedia();
printf('%d/%d', $result->getRateLimitRemaining(), $result->getRateLimit());
```

### Logging and proxy

[](#logging-and-proxy)

We use `info` level to log all successful requests with their responses, and `error` level for failed requests (with their responses, if available).

```
$logger = new Monolog\Logger('instagram');
$logger->pushHandler(new Monolog\Handler\StreamHandler(__DIR__.'/logs/info.log', Monolog\Logger::INFO, false));
$logger->pushHandler(new Monolog\Handler\StreamHandler(__DIR__.'/logs/error.log', Monolog\Logger::ERROR, false));

$guzzleClient = new GuzzleHttp\Client([
    'connect_timeout' => 10.0,
    'timeout'         => 60.0,
    // Use proxy.
    'proxy'           => 'username:password@127.0.0.1:3128',
    // Disable SSL certificate validation.
    'verify'          => false,
]);

$apiClient = new \InstagramRestApi\Client($config, $logger, $guzzleClient);
```

###  Health Score

23

—

LowBetter than 26% of packages

Maintenance10

Infrequent updates — may be unmaintained

Popularity16

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

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 ~4 days

Total

2

Last Release

3300d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/26eed1a8ba782687f197fcbc91496308a77d0ace6eee6ef368c8df881dc60b97?d=identicon)[valga](/maintainers/valga)

---

Top Contributors

[![valga](https://avatars.githubusercontent.com/u/23472603?v=4)](https://github.com/valga "valga (9 commits)")

---

Tags

apiinstagramlibraryphpphpapirestinstagram

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/valga-instagram-rest-api/health.svg)

```
[![Health](https://phpackages.com/badges/valga-instagram-rest-api/health.svg)](https://phpackages.com/packages/valga-instagram-rest-api)
```

###  Alternatives

[xeroapi/xero-php-oauth2

Xero official PHP SDK for oAuth2 generated with OpenAPI spec 3

1054.6M18](/packages/xeroapi-xero-php-oauth2)[api-platform/metadata

API Resource-oriented metadata attributes and factories

244.5M182](/packages/api-platform-metadata)[bitrix24/b24phpsdk

An official PHP library for the Bitrix24 REST API

10139.4k5](/packages/bitrix24-b24phpsdk)[onesignal/onesignal-php-api

A powerful way to send personalized messages at scale and build effective customer engagement strategies. Learn more at onesignal.com

34199.5k2](/packages/onesignal-onesignal-php-api)[zenditplatform/zendit-php-sdk

PHP client for Zendit API

1194.4k](/packages/zenditplatform-zendit-php-sdk)[huaweicloud/huaweicloud-sdk-php

Huawei Cloud SDK for PHP

1830.2k2](/packages/huaweicloud-huaweicloud-sdk-php)

PHPackages © 2026

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