Getting started overview

Integrating the Unsplash API involves a sequence of steps designed to provide developers with access to its photo library. The process typically begins with account creation, followed by the registration of an application to receive API credentials. These credentials, primarily an access key, facilitate authenticated requests to the Unsplash API endpoints. The API supports rate limits for free usage and offers a straightforward method for fetching image data.

Unsplash's API is designed for various use cases, including embedding images in blogs, powering search functionalities in applications, or creating custom photo displays. The API provides access to public photos and, with OAuth, allows for user-specific actions like liking photos or managing collections. This guide focuses on the initial steps to make a public data request.

Here's a quick reference table outlining the initial steps:

Step What to Do Where
1. Create Account Register for a free Unsplash account. Unsplash Sign Up Page
2. Register Application Create a new application to generate API keys. Unsplash Developer Applications
3. Retrieve Keys Locate and copy your Access Key. Your application's details page
4. Make First Request Construct a simple API call using your Access Key. Any HTTP client (e.g., curl, browser)

Create an account and get keys

Before making any requests to the Unsplash API, you need to create an Unsplash account and register an application. This process grants you the necessary API keys for authentication.

  1. Sign up for an Unsplash account: Navigate to the Unsplash registration page and complete the sign-up process. You can use an email address or sign up with Google or Facebook.

  2. Access the Developer / API section: Once logged in, go to the Unsplash Developers page. This section provides an overview of the API and links to documentation.

  3. Register a new application: Click on the "Your apps" or "New Application" button. You will be prompted to agree to the Unsplash API Guidelines. Read these terms carefully, as they outline usage policies, including attribution requirements and rate limits.

  4. Fill out application details: Provide a name for your application, a description, and a website/callback URL. For initial testing, a placeholder URL like http://localhost can often be used, though a valid URL is recommended for production. The callback URL is particularly important if you plan to implement OAuth for user authentication, as it's where users will be redirected after granting permissions to your application.

  5. Retrieve your Access Key: After registering your application, you will be redirected to its details page. Here, you will find your "Access Key" and "Secret Key." For most public data requests, the Access Key is sufficient. The Secret Key is used in conjunction with OAuth for more secure, server-side interactions and user authentication flows. Keep your Secret Key confidential.

Your first request

With your Access Key ready, you can now make your first request to the Unsplash API. This example demonstrates how to fetch a list of public photos.

Using curl (Command Line)

The curl command-line tool is a common way to test API endpoints. Replace YOUR_ACCESS_KEY with the actual Access Key you obtained.

curl -X GET "https://api.unsplash.com/photos?client_id=YOUR_ACCESS_KEY"

This command sends a GET request to the /photos endpoint, which returns a paginated list of the latest photos on Unsplash. The client_id parameter is used to authenticate your request with your Access Key.

Using JavaScript (Browser or Node.js)

For web applications, you can use the Fetch API. This example retrieves a list of photos and logs them to the console.

fetch('https://api.unsplash.com/photos?client_id=YOUR_ACCESS_KEY')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Error fetching photos:', error);
  });

Remember to replace YOUR_ACCESS_KEY with your assigned key.

Using Python

Python developers can use the requests library to interact with the API.

import requests

access_key = "YOUR_ACCESS_KEY"
url = f"https://api.unsplash.com/photos?client_id={access_key}"

response = requests.get(url)

if response.status_code == 200:
    data = response.json()
    print(data)
else:
    print(f"Error: {response.status_code}")
    print(response.text)

Install the requests library if you haven't already: pip install requests.

Common next steps

After successfully making your first API call, consider these common next steps to further integrate Unsplash:

  • Explore additional endpoints: The Unsplash API offers various endpoints beyond /photos, such as searching photos (/search/photos), retrieving user profiles (/users/{username}), and accessing collections (/collections). Consult the Unsplash API Reference for a complete list and their parameters.

  • Handle pagination: Most list endpoints return a limited number of results per page. Implement pagination using the page and per_page parameters to fetch more data. For example, to get the second page with 20 items per page: https://api.unsplash.com/photos?client_id=YOUR_ACCESS_KEY&page=2&per_page=20.

  • Implement proper attribution: Unsplash requires attribution for all images used through its API. This typically includes linking back to the Unsplash photo page and the photographer's profile. Review the Unsplash attribution requirements in their documentation.

  • Manage rate limits: The free tier of the Unsplash API is limited to 50 requests per hour. Monitor the X-RateLimit-Limit and X-RateLimit-Remaining headers in API responses to track your usage and avoid exceeding limits. For higher volumes, consider Unsplash Custom API plans.

  • Implement OAuth for user-specific actions: If your application requires users to perform actions like liking photos or creating collections, you will need to implement OAuth authentication. This involves redirecting users to Unsplash to authorize your application and then exchanging an authorization code for an access token.

  • Secure your API keys: While the Access Key for public data requests can be exposed in client-side code, it's generally good practice to proxy API requests through your own backend server to hide your Access Key and manage rate limits more effectively. For the Secret Key, always store it securely and never expose it in client-side code, as outlined in general API key security best practices.

Troubleshooting the first call

When making your initial API calls, you might encounter common issues. Here are some troubleshooting tips:

  • 401 Unauthorized: This usually means your client_id (Access Key) is missing or incorrect. Double-check that you've included it as a query parameter (?client_id=YOUR_ACCESS_KEY) and that the key itself is copied accurately from your Unsplash application settings.

  • 403 Forbidden: If you receive a 403 error, it might indicate that your application has not been approved, or there's an issue with your compliance with the Unsplash API Guidelines. Ensure your application details are complete and accurate.

  • 404 Not Found: Verify the API endpoint URL. Ensure there are no typos in https://api.unsplash.com/photos or other endpoints you are trying to access. The Unsplash API documentation provides the correct paths for all available endpoints.

  • 429 Too Many Requests: This error indicates you have exceeded the rate limit (50 requests per hour for the free tier). Wait a short period, typically an hour, before making further requests, or consider implementing exponential backoff in your code. You can check the X-RateLimit-Remaining header in the response to see how many requests you have left in the current hour.

  • CORS issues (Cross-Origin Resource Sharing): If you're making requests from a web browser and encounter CORS errors, ensure that your client-side application's domain is correctly listed in the "Redirect URI" or "Website URL" field of your Unsplash application. While basic public endpoints often tolerate simple browser requests, more complex interactions or specific browser environments might require correct CORS configuration.

  • Invalid JSON response: Ensure your code correctly parses the JSON response. If the response is not valid JSON, it might indicate an API error with a non-JSON body. Always check the Content-Type header of the response.