Getting started overview
WakaTime provides an API to access coding activity data collected through its IDE plugins or direct integrations. This guide focuses on the steps required to obtain API credentials and make an initial request to retrieve user-specific data. The process involves creating a WakaTime account, locating your personal API key, and then using this key to authenticate requests to the WakaTime API endpoints.
The WakaTime API is designed as a RESTful service, returning data in JSON format. It supports various data retrieval operations, including fetching summaries of coding activity, detailed time entries, and user statistics. While WakaTime offers several IDE plugins for automated data collection, direct API interaction is necessary for custom reporting, integrating data into other applications, or building bespoke dashboards.
The core interaction model involves sending HTTP GET requests to specific API endpoints, including your API key for authentication. Understanding HTTP methods and JSON parsing is beneficial for working with the WakaTime API. For developers seeking to integrate WakaTime data into their applications, the process generally follows these steps, which are detailed in the subsequent sections:
- Account creation and API key retrieval.
- Making an authenticated request to a basic endpoint.
- Exploring further API capabilities and data models.
Create an account and get keys
To begin using the WakaTime API, you must first create a user account. A free tier is available, which provides access to basic features and API functionality, making it suitable for initial development and testing. Once registered, your unique API key will be accessible through your account settings.
Account Registration
Navigate to the WakaTime signup page. You can register using an email address and password, or by authenticating through a third-party service such as GitHub or Google. Complete the registration process by following the on-screen prompts. No payment information is required for the free tier, which allows unlimited time tracking history for the last 7 days and basic dashboard features. For extended history and advanced analytics, refer to the WakaTime pricing page.
Locating Your API Key
After successfully creating and logging into your WakaTime account, your personal API key is available in your account settings. Follow these steps:
- Log in to your WakaTime account.
- Click on your profile picture or username in the top right corner of the dashboard.
- Select Settings from the dropdown menu.
- On the settings page, navigate to the API Keys section.
- Your API key will be displayed. This key is a unique alphanumeric string (e.g.,
waka_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx). Copy this key, as it will be required for all authenticated API requests.
WakaTime's authentication mechanism relies on this API key. It should be treated as sensitive information, similar to a password. Do not expose it in client-side code, public repositories, or unsecured environments. For server-side applications, store the key securely, for example, using environment variables or a dedicated secret management service.
Your first request
With your API key in hand, you can now make your first authenticated call to the WakaTime API. A common starting point is retrieving the current user's profile information or their daily coding activity summary. This example will demonstrate fetching the current user's profile, which returns basic metadata about the account associated with the API key.
API Endpoint for User Profile
The endpoint for retrieving the current user's profile is https://wakatime.com/api/v1/users/current. This endpoint requires authentication.
Authentication Method
WakaTime uses a simple API key authentication. You pass your API key as a query parameter named api_key in your request. For example: https://wakatime.com/api/v1/users/current?api_key=YOUR_API_KEY.
Example Request (Python)
Using Python's requests library is a straightforward way to interact with RESTful APIs. Ensure you have it installed (pip install requests).
import requests
import os
# It's best practice to store your API key in an environment variable
# For demonstration, replace 'YOUR_WAKATIME_API_KEY' with your actual key if not using env vars
WAKATIME_API_KEY = os.getenv('WAKATIME_API_KEY', 'YOUR_WAKATIME_API_KEY')
api_url = "https://wakatime.com/api/v1/users/current"
# Parameters for the request, including the API key
params = {
'api_key': WAKATIME_API_KEY
}
try:
response = requests.get(api_url, params=params)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
user_data = response.json()
print("Successfully retrieved user data:")
print(f"Username: {user_data['data']['username']}")
print(f"Email: {user_data['data']['email']}")
print(f"Website: {user_data['data']['website']}")
print(f"Created At: {user_data['data']['created_at']}")
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
print(f"Response content: {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}")
Expected Output
A successful response will return a JSON object containing details about the current user. An example of a partial successful output:
{
"data": {
"created_at": "2023-01-01T12:00:00Z",
"email": "[email protected]",
"id": "unique-user-id",
"is_email_public": false,
"is_hireable": false,
"is_onboarded": true,
"is_sso_connected": false,
"last_heartbeat_at": "2023-05-29T10:30:00Z",
"last_plugin": "vs-code",
"last_plugin_name": "VS Code",
"location": null,
"logged_in_at": "2023-05-29T10:00:00Z",
"modified_at": "2023-05-29T09:00:00Z",
"photo": "https://wakatime.com/photo.jpg",
"plan": "free",
"public_email": null,
"share_all_time_since_days": 0,
"timezone": "America/New_York",
"username": "your-username",
"website": "https://yourwebsite.com"
}
}
Quick Reference for Getting Started
This table summarizes the initial steps:
| Step | What to Do | Where to Find/Do It |
|---|---|---|
| 1. Create Account | Register for a WakaTime account. | WakaTime Signup Page |
| 2. Get API Key | Locate your unique API key in account settings. | WakaTime Dashboard > Settings > API Keys |
| 3. Install Requests (Python) | Install the Python requests library. |
pip install requests in your terminal |
| 4. Make First Request | Send a GET request to the current user endpoint with your API key. | Using the provided Python example or a similar HTTP client |
Common next steps
After successfully making your first API call, consider these next steps to further integrate and utilize WakaTime data:
-
Explore More Endpoints: Consult the WakaTime Developers API Reference for a comprehensive list of available endpoints. Common endpoints include
/api/v1/users/current/summariesfor daily coding summaries,/api/v1/users/current/durationsfor detailed time entries, and/api/v1/users/current/stats/{range}for language and project statistics over specified periods (e.g.,last_7_days,last_30_days). - Install IDE Plugins: While the API allows direct data retrieval, the primary method for collecting data into WakaTime is through its various IDE plugins. Install the relevant plugin for your development environment (e.g., VS Code, IntelliJ, Sublime Text) to automatically track your coding activity. This will populate your WakaTime dashboard and make data available via the API.
- Data Visualization and Reporting: Use the retrieved data to build custom dashboards, generate reports, or integrate with business intelligence tools. The JSON data can be parsed and visualized using libraries like Matplotlib (Python), D3.js (JavaScript), or integrated into platforms like Google Charts.
- Webhooks: WakaTime supports webhooks, which can notify your application in real-time about certain events, such as when a new coding activity summary is available. This can be more efficient than polling the API frequently. Information on configuring webhooks can be found in the WakaTime API documentation on webhooks.
- Security Best Practices: For production applications, ensure your API key is managed securely. Use environment variables, secret management services, or a secure configuration file. Avoid hardcoding credentials directly into your codebase. Understanding OAuth 2.0 principles can also be beneficial for more complex authentication scenarios, although WakaTime's primary API key method is sufficient for many integrations.
- Error Handling: Implement robust error handling in your application to gracefully manage API rate limits, network issues, and invalid responses. The WakaTime API will return standard HTTP status codes (e.g., 401 for unauthorized, 404 for not found, 429 for rate limit exceeded) that your application should interpret.
Troubleshooting the first call
Encountering issues during your first API call is common. Here are some troubleshooting steps and common problems:
-
401 UnauthorizedError:- Incorrect API Key: Double-check that you have copied your API key correctly from your WakaTime API Keys settings. Ensure there are no leading or trailing spaces.
- Missing API Key: Verify that the
api_keyparameter is included in your request URL. - Expired/Revoked Key: Although less common for new keys, ensure your key has not been revoked or expired. You can generate a new key in your settings if needed.
-
Network Issues:
- Connectivity: Confirm your internet connection is stable and that your environment can reach
https://wakatime.com. - Firewall/Proxy: If you are in a corporate network, a firewall or proxy might be blocking outbound requests. Consult your network administrator.
- Connectivity: Confirm your internet connection is stable and that your environment can reach
-
Incorrect Endpoint:
- Typo in URL: Verify the API endpoint URL is exactly
https://wakatime.com/api/v1/users/current. - HTTP vs. HTTPS: Always use HTTPS for secure communication.
- Typo in URL: Verify the API endpoint URL is exactly
-
JSON Parsing Errors:
- If your code fails to parse the JSON response, it might be due to an unexpected response format. Print the raw
response.textto inspect the actual content returned by the API. This can reveal HTML error pages or non-JSON responses. - Ensure your JSON parser is correctly configured to handle UTF-8 encoding.
- If your code fails to parse the JSON response, it might be due to an unexpected response format. Print the raw
-
Rate Limiting (
429 Too Many Requests):- While unlikely on a first call, repeated rapid requests can trigger rate limits. The WakaTime API has usage limits to ensure fair access. If you encounter this, implement a delay or exponential backoff in your retry logic. The WakaTime API documentation on rate limits provides more details.
-
Library-Specific Issues:
- Python
requests: Ensure the library is installed and updated. The error messages fromrequests.exceptionsare usually descriptive. - Other Languages: If using other languages or HTTP clients, consult their specific documentation for common issues related to making external HTTP requests and parsing JSON.
- Python
When troubleshooting, using a tool like curl from your terminal can help isolate issues by making a direct, simple HTTP request outside of your code environment:
curl "https://wakatime.com/api/v1/users/current?api_key=YOUR_WAKATIME_API_KEY"
Replace YOUR_WAKATIME_API_KEY with your actual key. This command should return the JSON user data directly in your terminal, confirming basic connectivity and authentication.