Getting started overview

Integrating with the Unsplash API involves a structured process to ensure proper authentication and usage. This guide outlines the steps from creating an account and registering an application to making a first authenticated API call. The Unsplash API is a RESTful service that provides access to its extensive photo library, user data, and collection management features through HTTP requests and JSON responses Unsplash API documentation. Authentication is managed via OAuth 2.0, requiring developers to obtain a client ID and, for certain operations, a client secret.

Before making any requests, it is necessary to register an application within the Unsplash developer portal. This registration process generates the necessary credentials. The API's rate limits are enforced per application, with a free tier offering 50 requests per hour. For increased request volumes, Unsplash offers a Developer Pro plan Unsplash API Developer Pro details.

Here's a quick overview of the essential steps:

  1. Sign up for an Unsplash developer account.
  2. Register a new application to obtain API keys.
  3. Understand rate limits and authentication methods.
  4. Construct and execute a basic API request.
  5. Handle responses and common errors.

Create an account and get keys

Accessing the Unsplash API requires a developer account and registered application. Follow these steps to set up your environment:

  1. Create an Unsplash Account: Navigate to the Unsplash signup page and create a user account if you do not already have one. This account will be linked to your developer applications.
  2. Access the Developer Portal: Once logged in, go to the Unsplash developer portal. This is the central hub for managing your applications and API usage.
  3. Register a New Application:
    • Click on "Your apps" or a similar link to view your applications.
    • Select "New Application" or "Register an application."
    • Read and agree to the Unsplash API Terms of Use. It is crucial to understand these terms, especially regarding attribution requirements and usage limitations Unsplash Terms of Service.
    • Provide details for your application, including its name, a brief description, and a redirect URI if you plan to implement OAuth 2.0 for user authentication (e.g., if users will log into Unsplash through your application). For simple public API access, a placeholder redirect URI like urn:ietf:wg:oauth:2.0:oob or http://localhost can sometimes be used initially, though a valid URL is preferred for production applications. More information on OAuth 2.0 flows can be found in the OAuth 2.0 specification.
    • After submission, Unsplash will provide you with an Access Key (also known as Client ID) and, for certain application types, a Secret Key (Client Secret). The Access Key is essential for all public API requests. The Secret Key is used in server-side applications for secure operations and should be kept confidential.
  4. Store Your Keys Securely: Your Access Key is public, but your Secret Key must be protected. Do not embed it directly in client-side code or commit it to version control systems like Git. Use environment variables or a secure configuration management system.

Your first request

With your Access Key ready, you can now make your first API call to retrieve public data, such as a list of photos. This example demonstrates fetching a list of photos without any specific search query.

Authentication Method

For most public API calls, Unsplash uses token-based authentication where your Access Key is included as a query parameter or an Authorization header. For the first request, using the query parameter is often the simplest approach.

Example: Fetching a List of Photos

The endpoint for listing photos is https://api.unsplash.com/photos.

Using cURL (Command Line)


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

Replace YOUR_ACCESS_KEY with the Access Key obtained from your registered application.

Using JavaScript (Fetch API)

This example demonstrates how to make the request in a web browser or Node.js environment using the Fetch API.


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);
  });

Again, ensure you replace YOUR_ACCESS_KEY with your actual key.

Expected Response

A successful response will return a JSON array of photo objects. Each object contains metadata about a photo, including its ID, description, URLs for different sizes, and user information. For example:


[
  {
    "id": "some-photo-id",
    "created_at": "2023-01-01T12:00:00Z",
    "width": 4000,
    "height": 6000,
    "description": "A beautiful landscape",
    "alt_description": "green trees and mountains under blue sky",
    "urls": {
      "raw": "https://images.unsplash.com/photo-1...
      "full": "https://images.unsplash.com/photo-1...
      "regular": "https://images.unsplash.com/photo-1...
      "small": "https://images.unsplash.com/photo-1...
      "thumb": "https://images.unsplash.com/photo-1...
    },
    "user": {
      "id": "some-user-id",
      "username": "johndoe",
      "name": "John Doe",
      "portfolio_url": "https://johndoe.com",
      // ... other user details
    },
    // ... more photo details
  },
  // ... other photo objects
]

The exact content of the photo objects can be found in the Unsplash API list photos endpoint documentation.

Common next steps

After successfully making your first request, consider these common next steps to further integrate the Unsplash API into your application:

  1. Explore Other Endpoints: The Unsplash API offers various endpoints beyond simply listing photos. You can search for photos by keyword (/search/photos), retrieve specific photos by ID (/photos/:id), access user profiles (/users/:username), manage collections (/collections), and more Unsplash API reference.
  2. Implement Search Functionality: One of the most common uses of the Unsplash API is to provide image search. Use the /search/photos endpoint with a query parameter to fetch relevant images based on user input.
  3. Handle Pagination: API responses are often paginated to manage the amount of data returned. Most endpoints accept page and per_page parameters to control which results are returned and how many per request. Implement pagination logic to fetch more results as needed.
  4. Implement OAuth 2.0 for User-Specific Actions: If your application requires users to perform actions on their Unsplash account (e.g., liking photos, creating collections, uploading photos), you will need to implement the full OAuth 2.0 authorization code flow. This involves redirecting users to Unsplash for authorization and then exchanging an authorization code for an access token and refresh token OAuth 2.0 Authorization Code Grant. The Unsplash API authentication guide provides specific instructions.
  5. Attribution: Adhere to the Unsplash API's attribution requirements. This typically involves displaying the photographer's name and a link back to their Unsplash profile, as well as a link to Unsplash itself, whenever an image is displayed Unsplash API attribution requirements. Failure to properly attribute can lead to API access revocation.
  6. Error Handling: Implement robust error handling to gracefully manage API responses that indicate issues (e.g., rate limit exceeded, invalid parameters, authentication failures). The API returns standard HTTP status codes and JSON error messages.
  7. Rate Limit Management: Keep track of your remaining requests using the X-RateLimit-Limit and X-RateLimit-Remaining headers in API responses. Implement a strategy to pause requests or notify users if your application approaches the rate limit to avoid being temporarily blocked.

Troubleshooting the first call

Encountering issues during your first API call is common. Here's a table of common problems and their solutions:

Problem What to do Where to check
401 Unauthorized or Invalid Client ID Ensure your client_id (Access Key) is correct and included in the request.
403 Forbidden or Rate Limit Exceeded You have exceeded the allowed number of requests (50/hour for the free tier). Wait an hour or consider upgrading.
  • Check the X-RateLimit-Remaining HTTP header in the API response.
  • Review your application's usage in the developer dashboard.
404 Not Found The endpoint URL is incorrect or the resource you are requesting does not exist.
500 Internal Server Error This indicates an issue on Unsplash's server. It's usually temporary.
Empty array [] or no results Your search query might not match any photos, or parameters are too restrictive.
CORS errors in browser Cross-Origin Resource Sharing (CORS) issues often occur when making API requests from a browser-based application to a different domain without proper server-side configuration.
  • Ensure your application's redirect URI is correctly configured in your Unsplash developer application settings, even for public read-only access.
  • For client-side applications, ensure the API endpoint supports CORS, which Unsplash generally does for public read access. If you encounter issues, consider proxying requests through your own backend server.

For more specific error codes and messages, consult the Unsplash API error documentation.