Getting started overview

This guide outlines the essential steps to initiate development with the Wallhaven API. Wallhaven provides access to its extensive wallpaper database through a RESTful API, primarily for fetching wallpaper metadata and image URLs. Integration requires obtaining an API key for authenticated requests, which offers higher rate limits and access to user-specific features like favorites. The API is designed for developers seeking to build applications that consume or display high-quality digital art and wallpapers.

Quick Reference Steps

The following table provides a high-level overview of the Wallhaven API getting started process:

Step What to do Where
1. Create Account Register for a free Wallhaven user account. Wallhaven registration page
2. Generate API Key Access your user settings to generate your personal API key. Wallhaven API settings
3. Construct Request Formulate an HTTP GET request to a Wallhaven API endpoint, including your API key. Developer's local environment or IDE
4. Execute Request Send the HTTP request using a tool or programming language. Terminal (cURL), Postman, or custom code
5. Process Response Parse the JSON response to extract relevant data. Developer's application logic

Create an account and get keys

Access to the full capabilities of the Wallhaven API, including higher rate limits and personalized content, necessitates an API key. This key is linked to a Wallhaven user account. If you do not already have an account, the initial step is to register one.

  1. Register a Wallhaven account: Navigate to the Wallhaven registration page. Provide a username, email address, and password to create your account. You will typically need to verify your email address to complete the registration process.
  2. Log in to your account: After successful registration and email verification, log in to your newly created Wallhaven account.
  3. Access API settings: Once logged in, go to your Wallhaven API settings page. This page is specifically designed for managing your API key.
  4. Generate API key: On the API settings page, locate the option to generate or view your API key. Wallhaven provides a unique alphanumeric string that serves as your authentication credential. Copy this key immediately and store it securely, as it grants access to your account's API capabilities. Wallhaven's API documentation notes that the API key should be kept confidential to prevent unauthorized access to your account's rate limits and features.

The Wallhaven API key functions as a query parameter in your HTTP requests. For instance, when making a request, you would append ?apikey=YOUR_API_KEY to the endpoint URL. This method of authentication is common for public APIs where the primary concern is identifying the requester for rate limiting and basic access control, as described in general API security practices by Microsoft's API Gateway documentation.

Your first request

With your API key obtained, you can now make your first authenticated request to the Wallhaven API. This example demonstrates fetching the latest wallpapers using the /search endpoint.

API Base URL

The base URL for all Wallhaven API v1 endpoints is https://wallhaven.cc/api/v1/.

Example: Fetching the latest wallpapers

To retrieve a list of the latest wallpapers, you will use the /search endpoint. The API key must be included as a query parameter.

Request details

  • Endpoint: /search
  • Method: GET
  • Query Parameters:
    • apikey: Your Wallhaven API key (required for authenticated requests).
    • sorting: toplist (optional, to get popular wallpapers).
    • purity: sfw (optional, to filter for Safe For Work content).

cURL example

Replace YOUR_API_KEY with the actual API key you generated.

curl -X GET "https://wallhaven.cc/api/v1/search?sorting=toplist&purity=sfw&apikey=YOUR_API_KEY"

Expected JSON response structure

A successful request will return a JSON object containing an array of wallpaper data. Each wallpaper object includes details such as ID, URL, dimensions, and various tags.

{
  "data": [
    {
      "id": "#id#",
      "url": "https://wallhaven.cc/w/#id#",
      "short_url": "https://whvn.cc/#id#",
      "views": #views#,
      "favorites": #favorites#,
      "source": "",
      "purity": "sfw",
      "category": "general",
      "dimension_x": #width#,
      "dimension_y": #height#,
      "resolution": "#width#x#height#",
      "ratio": "#ratio#",
      "file_size": #size#,
      "file_type": "image/jpeg",
      "created_at": "#date#",
      "colors": [
        "#660000",
        "#000000",
        "#424242",
        "#999999",
        "#cccccc"
      ],
      "path": "https://w.wallhaven.cc/full/#id_2#/wallhaven-#id#.jpg",
      "thumbs": {
        "small": "https://th.wallhaven.cc/small/#id_2#/th-#id#.jpg",
        "large": "https://th.wallhaven.cc/large/#id_2#/th-#id#.jpg",
        "original": "https://th.wallhaven.cc/original/#id_2#/th-#id#.jpg"
      }
    }
    // ... more wallpaper objects
  ],
  "meta": {
    "current_page": 1,
    "last_page": 500,
    "per_page": 24,
    "total": 12000
  }
}

This response structure provides metadata about the retrieved wallpapers, including their unique IDs, direct image paths (path), and thumbnail URLs (thumbs). The meta object contains pagination details, which are crucial for navigating through large result sets.

Common next steps

After successfully making your first request, consider these common next steps to further integrate with the Wallhaven API:

  • Explore search parameters: The /search endpoint offers numerous parameters for filtering and sorting wallpapers, such as q (query), categories, colors, resolutions, and more. Experiment with these to refine your wallpaper searches and retrieve specific content relevant to your application. Consult the Wallhaven API documentation for a complete list of available parameters and their usage.
  • Implement pagination: For applications requiring access to a large volume of wallpapers, implement pagination using the page query parameter. The meta object in the API response provides current_page, last_page, and total fields, which are essential for iterating through result sets efficiently.
  • Handle image downloads: The API provides direct URLs to full-resolution images (path field) and various thumbnail sizes (thumbs object). Implement logic to download these images responsibly, considering file sizes and user bandwidth. Ensure compliance with Wallhaven's terms of service regarding image usage.
  • Error handling: Implement robust error handling in your application. The Wallhaven API typically returns standard HTTP status codes (e.g., 400 Bad Request, 401 Unauthorized, 404 Not Found) and descriptive JSON error messages. Proper error handling improves the resilience and user experience of your integration.
  • Monitor rate limits: Pay attention to the HTTP headers returned by the API, which include rate limit information (e.g., X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset). Implement a mechanism to respect these limits to avoid temporary bans or service interruptions. Unauthenticated requests are limited to 30 requests per minute, while authenticated requests allow 100 requests per minute. Understanding and adhering to rate limits is a standard practice in API consumption, as highlighted by Cloudflare's API rate limiting guide.

Troubleshooting the first call

Encountering issues during your initial API call is common. Here are some troubleshooting steps for typical problems:

  • Invalid API Key (HTTP 401 Unauthorized):
    • Verify key accuracy: Double-check that you have copied your API key correctly from your Wallhaven API settings. Typos are a frequent cause of authentication failures.
    • Ensure key inclusion: Confirm that the apikey query parameter is correctly appended to your request URL, precisely as ?apikey=YOUR_API_KEY.
    • Check account status: Ensure your Wallhaven account is active and not suspended.
  • Missing or Incorrect Parameters (HTTP 400 Bad Request):
    • Consult documentation: Refer to the Wallhaven API documentation for the specific endpoint you are calling. Verify that all required parameters are present and that their values conform to the expected types and formats (e.g., valid sorting options, correct purity filters).
    • URL encoding: Ensure that any special characters in query parameters (e.g., spaces in search queries) are properly URL-encoded.
  • Rate Limit Exceeded (HTTP 429 Too Many Requests):
    • Check headers: Examine the X-RateLimit-Remaining and X-RateLimit-Reset HTTP response headers to understand your current rate limit status and when it will reset.
    • Wait and retry: If you have exceeded the limit, wait until the X-RateLimit-Reset time has passed before making further requests.
    • Implement exponential backoff: For automated retries, implement an exponential backoff strategy to prevent continuously hitting the rate limit.
    • Authenticate: If you are making unauthenticated requests, obtaining and using an API key will increase your rate limit from 30 to 100 requests per minute.
  • Network Issues:
    • Check connectivity: Ensure your development environment has a stable internet connection and is not blocked by a firewall.
    • DNS resolution: Verify that wallhaven.cc resolves correctly using tools like ping or nslookup.
  • Unexpected JSON Response:
    • Validate JSON: Use an online JSON validator or your IDE's built-in tools to confirm the response is well-formed JSON.
    • Inspect fields: Compare the received JSON structure against the expected structure in the Wallhaven API documentation. Discrepancies might indicate an incorrect endpoint or version.