Getting started overview

Integrating with the Ganjoor API involves a series of steps designed to provide access to its extensive collection of classical Persian poetry. This guide focuses on the initial setup, from account creation to executing a foundational API call. The process requires obtaining API credentials and understanding the basic request structure, which is consistent with RESTful API principles for data retrieval.

The Ganjoor API serves as a programmatic interface to the Ganjoor project's digital library, which originated in 2006 to preserve and make accessible Persian literary works (about Ganjoor project). It is categorized under 'books and literature' and specifically 'Persian poetry API'. Developers can use it for various applications, including educational tools, literary analysis platforms, or embedding poetic content into websites.

Here's a quick reference for the initial setup:

Step What to do Where
1. Sign up Create a user account. Ganjoor registration page
2. Get API Key Locate and copy your unique API key. Ganjoor user profile
3. Review Docs Understand API endpoints and parameters. Ganjoor API documentation
4. Make Request Execute a GET request with your API key. Your preferred development environment
5. Process Response Parse the JSON response. Your application logic

Create an account and get keys

Access to the Ganjoor API requires an active user account and an associated API key. This key authenticates your requests and links them to your usage plan, which includes a free tier and paid options starting at $5 per month for 5,000 requests.

Account Creation

  1. Navigate to the official Ganjoor registration page.
  2. Provide the required information, typically including a username, email address, and password.
  3. Complete any necessary email verification steps to activate your account.

Obtaining Your API Key

Once your account is active, your API key will be accessible through your user profile:

  1. Log in to your Ganjoor account on the Ganjoor homepage.
  2. Access your user profile or dashboard. The exact path may vary, but it's typically found under a 'Profile', 'Settings', or 'API Access' section.
  3. Locate the API key. It is a unique alphanumeric string that you will include in the headers of your API requests. Copy this key securely, as it acts as your credential for accessing the API.

The API key is a form of token-based authentication, a common strategy for securing web APIs as described by the OAuth 2.0 Token Types specification, even if Ganjoor's implementation is a simpler API key mechanism.

Your first request

After obtaining your API key, you can make your first API call. This example demonstrates fetching a list of poets using the Python requests library, one of the supported SDKs in Ganjoor's documentation.

API Endpoint

The base URL for the Ganjoor API is https://api.ganjoor.net/api/. A common starting endpoint is to retrieve a list of poets, for example: https://api.ganjoor.net/api/poets.

Python Example

Install the requests library if you haven't already:

pip install requests

Then, execute the following Python code, replacing YOUR_API_KEY with your actual key:


import requests
import json

# Replace with your actual API key
API_KEY = "YOUR_API_KEY"

# Define the API endpoint
url = "https://api.ganjoor.net/api/poets"

# Set the headers, including the Authorization key
headers = {
    "Authorization": f"Token {API_KEY}"
}

try:
    # Make the GET request
    response = requests.get(url, headers=headers)
    response.raise_for_status()  # Raise an exception for HTTP errors (4xx or 5xx)

    # Parse the JSON response
    data = response.json()

    # Print some of the retrieved data
    print("Successfully fetched poets:")
    for poet in data['items'][:5]:  # Print first 5 poets
        print(f"- {poet['name']} (ID: {poet['id']})")

except requests.exceptions.HTTPError as http_err:
    print(f"HTTP error occurred: {http_err} - {response.text}")
except requests.exceptions.ConnectionError as conn_err:
    print(f"Connection error occurred: {conn_err}")
except requests.exceptions.Timeout as timeout_err:
    print(f"Timeout error occurred: {timeout_err}")
except requests.exceptions.RequestException as req_err:
    print(f"An unexpected error occurred: {req_err}")
except json.JSONDecodeError:
    print(f"Error decoding JSON: {response.text}")

Expected Output

A successful response will return a JSON object containing a list of poets. The structure will typically include an items array, with each item representing a poet and containing fields such as id and name. For example:


{
  "items": [
    {
      "id": 1,
      "name": "حافظ",
      "slug": "hafez",
      "full_name": "شمس‌الدین محمد حافظ شیرازی"
    },
    {
      "id": 2,
      "name": "سعدی",
      "slug": "saadi",
      "full_name": "ابومحمد مشرف‌الدین مصلح بن عبدالله بن مشرف شیرازی"
    },
    // ... more poets
  ],
  "page_count": 12,
  "current_page": 1,
  "total_items": 120
}

Common next steps

After successfully making your first request, you can explore the full capabilities of the Ganjoor API:

  • Explore Endpoints: Review the API documentation to discover other available endpoints, such as those for retrieving specific poems, verses, or categories. Examples often include endpoints like /api/poets/{id}/poems to get poems by a specific poet.
  • Implement Pagination: For endpoints that return large datasets, learn how to use pagination parameters (e.g., page and page_size) to efficiently retrieve data in manageable chunks.
  • Handle Errors: Implement robust error handling in your application to gracefully manage various HTTP status codes and API-specific error messages.
  • Integrate into Application: Begin integrating the retrieved poetry data into your application's user interface or backend logic.
  • Monitor Usage: Keep track of your API usage through your Ganjoor profile to stay within your plan limits and avoid unexpected interruptions.
  • Explore SDKs: While Python is prominently featured, consider if community-contributed SDKs or libraries exist for other programming languages, though Ganjoor officially supports Python SDKs.

Troubleshooting the first call

Encountering issues during your first API call is common. Here are some steps to diagnose and resolve typical problems:

  • Invalid API Key:
    • Symptom: 401 Unauthorized or 403 Forbidden HTTP status code.
    • Resolution: Double-check that your API key is correct and copied without extra spaces or characters. Ensure it's passed in the Authorization header as Token YOUR_API_KEY. Verify your key is active in your Ganjoor profile.
  • Incorrect Endpoint/URL:
    • Symptom: 404 Not Found HTTP status code.
    • Resolution: Confirm that the URL you are calling precisely matches an endpoint listed in the Ganjoor API documentation. Pay attention to case sensitivity and trailing slashes.
  • Network Issues:
    • Symptom: Connection timeouts or errors like requests.exceptions.ConnectionError.
    • Resolution: Verify your internet connection. Check if there are any firewalls or proxy settings that might be blocking outbound requests from your development environment. You can test basic connectivity to api.ganjoor.net using tools like ping or curl.
  • JSON Parsing Errors:
    • Symptom: json.JSONDecodeError or unexpected data format.
    • Resolution: If the API returns an error page (HTML) instead of JSON, it could indicate an underlying server issue or a misconfigured request preventing the API from responding correctly. Inspect the raw response.text to understand the actual content received.
  • Rate Limiting:
    • Symptom: 429 Too Many Requests HTTP status code.
    • Resolution: If you're on a free tier or a paid plan, you might hit request limits. Check your usage against your plan in your Ganjoor account dashboard and wait for the rate limit to reset, or consider upgrading your plan.
  • Server-Side Issues:
    • Symptom: 5xx HTTP status codes (e.g., 500 Internal Server Error, 503 Service Unavailable).
    • Resolution: These indicate an issue on the Ganjoor API server. While you can't directly fix these, you can check the Ganjoor homepage or related social media for announcements about service interruptions. Often, retrying the request after a short delay resolves transient issues.