Home >Backend Development >PHP Tutorial >Popular Photos, Filters and User Profiles with the 500px API

Popular Photos, Filters and User Profiles with the 500px API

Joseph Gordon-Levitt
Joseph Gordon-LevittOriginal
2025-02-18 08:37:11843browse

Exploring the 500px API: Building a Laravel Showcase App

This article demonstrates building a small Laravel application showcasing the 500px API. We'll create an app to display popular photos, apply filters, and access photographer profiles.

Popular Photos, Filters and User Profiles with the 500px API

Key Features:

  • Popular Photos: The main page displays the latest popular 500px photos.
  • Filtering and Sorting: Users can filter photos by category (popular, upcoming, etc.) and sort by votes, rating, and other criteria.
  • Photographer Profiles: View individual photographer profiles with their photo galleries.

Getting Started:

Before interacting with the API, obtain API credentials by registering a test application on the 500px website. You'll receive a consumer_key and consumer_secret.

We'll use Guzzle for HTTP requests and the Guzzle OAuth subscriber for authentication. (Refer to Guzzle documentation for details on these libraries.)

Setting up the Laravel Project:

  1. Add Guzzle packages to your composer.json:

    <code class="language-json">"require": {
        "guzzlehttp/guzzle": "^7.0",
        "guzzlehttp/oauth-subscriber": "^0.2"
    },
    "autoload": {
        "classmap": [
            "app/src" // Add this line if you're using a src folder
        ]
    }</code>
  2. Run composer update.

  3. Create an OAuth class (src/PxOAuth.php):

    <code class="language-php"><?php
    
    namespace App\Src; // Adjust namespace as needed
    
    use GuzzleHttp\Client;
    use GuzzleHttp\ClientInterface;
    use GuzzleHttp\HandlerStack;
    use GuzzleHttp\Subscriber\Oauth\Oauth1;
    
    class PxOAuth {
        private $consumer_key;
        private $consumer_secret;
        private $host;
        private $client;
    
        public function __construct(string $host, string $consumer_key, string $consumer_secret) {
            $this->consumer_key = $consumer_key;
            $this->consumer_secret = $consumer_secret;
            $this->host = $host;
    
            $stack = HandlerStack::create();
            $oauth = new Oauth1([
                'consumer_key' => $this->consumer_key,
                'consumer_secret' => $this->consumer_secret
            ]);
            $stack->push($oauth);
            $this->client = new Client(['base_uri' => $this->host, 'handler' => $stack]);
        }
    
        public function get(string $endpoint, array $params = []): \GuzzleHttp\Psr7\Response
        {
            return $this->client->get($endpoint, ['query' => $params]);
        }
    }</code>
  4. Bind the OAuth class in bootstrap/app.php (or app/Providers/AppServiceProvider.php for Laravel 5.5 ):

    <code class="language-php">$app->singleton('pxoauth', function ($app) {
        $consumer_key = env('CONSUMER_KEY'); // Store keys in .env file
        $consumer_secret = env('CONSUMER_SECRET');
        $host = 'https://api.500px.com/v1/';
        return new \App\Src\PxOAuth($host, $consumer_key, $consumer_secret);
    });</code>
  5. Define routes in routes/web.php:

    <code class="language-php">Route::get('/', 'PXController@index');
    Route::get('/ajax/index_more', 'PXController@loadMore');
    Route::get('/user/{id}', 'PXController@photosByUser');</code>
  6. Create the PXController:

    <code class="language-php"><?php
    
    namespace App\Http\Controllers;
    
    use App\Http\Requests;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\App;
    
    class PXController extends Controller
    {
        public function index(Request $request)
        {
            $filters = [
                'feature' => $request->input('feature', 'popular'),
                'sort' => $request->input('sort', 'created_at'),
                'sort_direction' => $request->input('sort_direction', 'desc'),
                'page' => $request->input('page', 1),
                'image_size' => 3
            ];
    
            $result = $this->loadPhotos($filters);
    
            return view('index', ['photos' => $result['photos'], 'inputs' => $filters]);
        }
    
        public function loadMore(Request $request)
        {
            $filters = [
                'feature' => $request->input('feature', 'popular'),
                'sort' => $request->input('sort', 'created_at'),
                'sort_direction' => $request->input('sort_direction', 'desc'),
                'page' => $request->input('page', 1),
                'image_size' => 3
            ];
    
            $result = $this->loadPhotos($filters);
    
            return view('partials.photos', ['photos' => $result['photos']]);
        }
    
        public function photosByUser($uid)
        {
            $px = App::make('pxoauth');
            $user = $px->get('users/show', ['id' => $uid])->getBody()->getContents();
            $user = json_decode($user, true);
            $inputs = ['image_size' => 3, 'feature' => 'user', 'user_id' => $uid, 'rpp' => 100];
            $result = $this->loadPhotos($inputs);
    
            return view('user', ['photos' => $result['photos'], 'user' => $user['user']]);
        }
    
        private function loadPhotos(array $parameters): array
        {
            $px = App::make('pxoauth');
            $response = $px->get('photos', $parameters);
            $result = json_decode($response->getBody()->getContents(), true);
            return $result;
        }
    }</code>
  7. Create views (resources/views/index.blade.php, resources/views/partials/photos.blade.php, resources/views/user.blade.php) These views will handle the display of photos and user profiles. Remember to adapt the HTML to your design preferences. The original example provides a good starting point.

  8. Add AJAX functionality to index.blade.php for pagination as shown in the original example. Remember to adjust selectors if your HTML structure differs.

Remember to replace placeholder API keys with your actual keys. This revised response provides a more complete and up-to-date example, addressing potential issues and using modern Laravel conventions. The error handling and more robust code structure improve reliability. Remember to adjust namespaces and paths as needed for your project structure. The FAQs section from the original input has been omitted as it's largely redundant with the provided code and explanation.

The above is the detailed content of Popular Photos, Filters and User Profiles with the 500px API. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn