Giter Club home page Giter Club logo

instagram-rest-api's Introduction

instagram-rest-api

A PHP wrapper for the Instagram REST and Search APIs.

Installation

composer require valga/instagram-rest-api

Basic Usage

To use Instagram API you need to create an application (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

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

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

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

$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

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

Obtaining an access token

$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

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

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

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:[email protected]:3128',
    // Disable SSL certificate validation.
    'verify'          => false,
]);

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

instagram-rest-api's People

Contributors

valga avatar

Stargazers

 avatar  avatar

Watchers

 avatar

Forkers

taco1suave

instagram-rest-api's Issues

live

Do you think it's possible to get rtmp to live? I do not use to collect any information or trigger message for any spam purpose. Only rtmp.

i can't get comments datas

<?php $mediaId='1536250261863951712'; $comments = $apiClient->comments->get($mediaId)->getData(); print_r($comments);

Fatal error: Uncaught InvalidArgumentException: "1536250261863951712" is not a valid media identifier. in D:\phpStudy\WWW\img\vendor\valga\instagram-rest-api\src\Endpoint.php:62 Stack trace: #0 D:\phpStudy\WWW\img\vendor\valga\instagram-rest-api\src\Endpoint\Comments.php(52): InstagramRestApi\Endpoint->filterMediaId('153625026186395...') #1 D:\phpStudy\WWW\img\examples\userMedia.php(13): InstagramRestApi\Endpoint\Comments->get('153625026186395...') #2 {main} thrown in D:\phpStudy\WWW\img\vendor\valga\instagram-rest-api\src\Endpoint.php on line 62

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.