### Get Grammarly Access Token and User Data in Java Source: https://developer.grammarly.com/your-first-api-request This Java example demonstrates how to obtain an OAuth2 access token from Grammarly and then use it to fetch an institutions summary. It requires Java 11+ and relies on environment variables for CLIENT_ID and CLIENT_SECRET. ```java import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.Scanner; import org.json.JSONObject; public class GrammarlyAPIExample { private static final String CLIENT_ID = System.getenv("CLIENT_ID"); private static final String CLIENT_SECRET = System.getenv("CLIENT_SECRET"); private static final String TOKEN_ENDPOINT = "https://auth.grammarly.com/v4/api/oauth2/token"; private static final String SCOPE = "users-api:read"; private static final String API_ENDPOINT = "https://api.grammarly.com/ecosystem/api/institutions-summary"; public static String getAccessToken() throws IOException { String payload = String.format( "grant_type=client_credentials&client_id=%s&client_secret=%s&scope=%s", CLIENT_ID, CLIENT_SECRET, SCOPE); URL url = new URL(TOKEN_ENDPOINT); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.getOutputStream().write(payload.getBytes()); Scanner scanner = new Scanner(connection.getInputStream()); String response = scanner.useDelimiter("\\A").next(); scanner.close(); JSONObject jsonResponse = new JSONObject(response); return jsonResponse.getString("access_token"); } public static String fetchUserData(String accessToken) throws IOException { URL url = new URL(API_ENDPOINT); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", "Bearer " + accessToken); Scanner scanner = new Scanner(connection.getInputStream()); String response = scanner.useDelimiter("\\A").next(); scanner.close(); return response; } public static void main(String[] args) throws IOException { String accessToken = getAccessToken(); String userData = fetchUserData(accessToken); System.out.println(userData); } } ``` -------------------------------- ### Get Grammarly Access Token and User Data in Node.js Source: https://developer.grammarly.com/your-first-api-request This Node.js example shows how to obtain an OAuth2 access token from Grammarly and subsequently make an authenticated API call to fetch user data. It uses the 'axios' library for HTTP requests and 'dotenv' to manage environment variables. ```javascript require('dotenv').config(); // To load environment variables from .env file const axios = require('axios'); const CLIENT_ID = process.env.CLIENT_ID; const CLIENT_SECRET = process.env.CLIENT_SECRET; const TOKEN_ENDPOINT = "https://auth.grammarly.com/v4/api/oauth2/token"; const SCOPE = "users-api:read"; const API_ENDPOINT = "https://api.grammarly.com/ecosystem/api/institutions-summary"; // Step 1: Request Access Token async function getAccessToken() { try { const response = await axios.post(TOKEN_ENDPOINT, new URLSearchParams({ grant_type: "client_credentials", client_id: CLIENT_ID, client_secret: CLIENT_SECRET, scope: SCOPE })); return response.data.access_token; } catch (error) { console.error("Error fetching access token:", error.response.data); throw error; } } // Step 2: Make Authenticated API Request async function fetchUserData() { try { const accessToken = await getAccessToken(); ``` -------------------------------- ### Python SDK Example Source: https://developer.grammarly.com/your-first-api-request Demonstrates how to use Python's requests library to authenticate and make API calls to Grammarly. ```APIDOC ## Python Example ### Description This Python script shows how to obtain an access token and then use it to make an authenticated API request. ### Code ```python import os import requests # Load client credentials from environment variables CLIENT_ID = os.getenv('CLIENT_ID') CLIENT_SECRET = os.getenv('CLIENT_SECRET') TOKEN_ENDPOINT = "https://auth.grammarly.com/v4/api/oauth2/token" SCOPE = "users-api:read" API_ENDPOINT = "https://api.grammarly.com/ecosystem/api/institutions-summary" # Step 1: Request Access Token def get_access_token(): payload = { "grant_type": "client_credentials", "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "scope": SCOPE } response = requests.post(TOKEN_ENDPOINT, data=payload) response.raise_for_status() # Raise an exception for HTTP errors return response.json().get("access_token") # Step 2: Make Authenticated API Request def fetch_institutions_summary(): access_token = get_access_token() headers = { "Authorization": f"Bearer {access_token}" } response = requests.get(API_ENDPOINT, headers=headers) response.raise_for_status() return response.json() # Example usage if __name__ == "__main__": try: summary_data = fetch_institutions_summary() print(summary_data) except requests.exceptions.RequestException as e: print(f"An error occurred: {e}") ``` ``` -------------------------------- ### Fetch User Data Source: https://developer.grammarly.com/your-first-api-request Example endpoint for fetching user data using an access token. This demonstrates how to include the authorization header in your requests. ```APIDOC ## GET /ecosystem/api/v2/analytics/users ### Description Fetches user data from the Analytics API. Requires a valid Bearer token in the Authorization header. ### Method GET ### Endpoint https://api.grammarly.com/ecosystem/api/v2/analytics/users ### Parameters #### Query Parameters - **limit** (integer) - Optional - Maximum number of users to return. - **date_from** (string) - Optional - Start date for the data (YYYY-MM-DD). - **date_to** (string) - Optional - End date for the data (YYYY-MM-DD). #### Request Headers - **Authorization** (string) - Required - Bearer token obtained from the token endpoint (e.g., "Bearer YOUR_ACCESS_TOKEN"). ### Request Example ```bash # Assuming ACCESS_TOKEN is already obtained USER_DATA_ENDPOINT="https://api.grammarly.com/ecosystem/api/v2/analytics/users?limit=10&date_from=2024-10-01&date_to=2024-10-31" curl -s -X GET "$USER_DATA_ENDPOINT" \ -H "Authorization: Bearer $ACCESS_TOKEN" ``` ### Response #### Success Response (200) - **user_data** (object) - Contains the requested user data. #### Response Example ```json { "user_data": [ { "user_id": "123", "name": "Example User" } ] } ``` ``` -------------------------------- ### Token Authentication and Institutions Summary API Source: https://developer.grammarly.com/your-first-api-request This section details how to obtain an access token using client credentials and then use that token to fetch the institutions summary from the Grammarly API. The example is provided in C#. ```APIDOC ## Token Authentication and Institutions Summary API ### Description This API allows you to authenticate using client credentials to obtain an access token. This token can then be used to access protected resources, such as fetching a summary of institutions. ### Method POST ### Endpoint `https://auth.grammarly.com/v4/api/oauth2/token` for token retrieval. `https://api.grammarly.com/ecosystem/api/institutions-summary` for fetching the institutions summary. ### Parameters #### Request Body (for token endpoint) - **grant_type** (string) - Required - Set to `client_credentials`. - **client_id** (string) - Required - Your application's client ID. - **client_secret** (string) - Required - Your application's client secret. - **scope** (string) - Required - The scope of the access requested, e.g., `users-api:read`. ### Request Example (C# for token retrieval) ```csharp using System.Net.Http; using System.Threading.Tasks; using System.Text; using System.Text.Json; // ... within a class private static readonly string CLIENT_ID = Environment.GetEnvironmentVariable("CLIENT_ID"); private static readonly string CLIENT_SECRET = Environment.GetEnvironmentVariable("CLIENT_SECRET"); private const string TOKEN_ENDPOINT = "https://auth.grammarly.com/v4/api/oauth2/token"; private const string SCOPE = "users-api:read"; public static async Task GetAccessTokenAsync() { using HttpClient client = new HttpClient(); var content = new FormUrlEncodedContent(new[] { new KeyValuePair("grant_type", "client_credentials"), new KeyValuePair("client_id", CLIENT_ID), new KeyValuePair("client_secret", CLIENT_SECRET), new KeyValuePair("scope", SCOPE) }); HttpResponseMessage response = await client.PostAsync(TOKEN_ENDPOINT, content); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); JsonDocument json = JsonDocument.Parse(responseBody); return json.RootElement.GetProperty("access_token").GetString(); } ``` ### Request Example (C# for institutions summary) ```csharp using System.Net.Http; using System.Threading.Tasks; // ... within a class private const string API_ENDPOINT = "https://api.grammarly.com/ecosystem/api/institutions-summary"; public static async Task FetchUserDataAsync() { string accessToken = await GetAccessTokenAsync(); // Assuming GetAccessTokenAsync is defined elsewhere using HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}"); HttpResponseMessage response = await client.GetAsync(API_ENDPOINT); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } ``` ### Response #### Success Response (200) for Token Endpoint - **access_token** (string) - The obtained access token. - **token_type** (string) - The type of token, usually `Bearer`. - **expires_in** (integer) - The lifetime in seconds of the access token. #### Success Response (200) for Institutions Summary Endpoint - (Structure depends on the actual API response, likely JSON containing institution data) #### Response Example (Token Endpoint) ```json { "access_token": "YOUR_ACCESS_TOKEN", "token_type": "Bearer", "expires_in": 3600 } ``` #### Response Example (Institutions Summary Endpoint) ```json { "institutions": [ { "id": "123e4567-e89b-12d3-a456-426614174000", "name": "Example University", "member_count": 5000 } // ... more institutions ] } ``` ``` -------------------------------- ### Get Institution Summary using cURL Source: https://developer.grammarly.com/license-management-api This snippet shows how to retrieve a summary of an institution using a cURL GET request. It requires an authorization token and returns a JSON object with details about the institution, including enrollment and seat information. ```bash curl -X GET \ 'https://api.grammarly.com/ecosystem/api/institutions-summary' \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` -------------------------------- ### GET /ecosystem/api/institutions-summary Source: https://developer.grammarly.com/license-management-api Retrieves a summary of an institution, including details about users, seats, and subscription status. ```APIDOC ## GET /ecosystem/api/institutions-summary ### Description This endpoint retrieves an overview of the institution, providing key metrics about its subscription and user enrollment. ### Method GET ### Endpoint `/ecosystem/api/institutions-summary` ### Parameters None ### Request Example ```bash curl -X GET \ 'https://api.grammarly.com/ecosystem/api/institutions-summary' \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` ### Response #### Success Response (200 OK) Returns a JSON object containing the institution's summary. #### Response Parameters - **id** (Integer) - The institution ID. - **name** (String) - The name of the institution. - **seats** (Integer) - The total number of licenses in this subscription. - **enrolled** (Integer) - The number of users who joined your Grammarly institution. - **expiration_date** (String) - The expiration date of the subscription in ISO 8601 format. - **user_types** (Object) - An object specifying the types of current users. - **admins** (Integer) - The number of admins in this institution. - **active** (Integer) - The number of active users in this institution, excluding admins. - **invited** (Integer) - The number of active or expired invitees. - **removed** (Integer) - The number of removed users and invitees. - **overage_seats** (Integer) - Indicates the number of occupied seats that exceed those paid for in the subscription. ### Example Response ```json { "id": 6123456789, "name": "Integration Business", "seats": 15, "enrolled": 4, "expiration_date": "2023-05-03", "user_types": { "removed": 2, "invited": 3, "admins": 3, "active": 1 } } ``` ### Usage Notes The parameters in the `user_types` object will only be returned if they’re > 0. ``` -------------------------------- ### Example AI Detection API Response Source: https://developer.grammarly.com/ai-detection-api This JSON object represents an example response from the AI Detection API. It includes a request ID, the status of the request, the time of the last update, and a score object containing the confidence that the document is AI-generated and the percentage of the document that is AI-generated. ```json { "score_request_id": "4bed7ce8-95f1-4e84-85d4-8f1e5744f950", "status": "COMPLETED", "updated_at": "2024-11-18T14:55:27.337443115Z", "score": { "average_confidence": 0.89, "ai_generated_percentage": 0.5 } } ``` -------------------------------- ### Example JSON Response for Writing Score API Source: https://developer.grammarly.com/writing-score-api This snippet shows an example of the JSON response body returned by the Writing Score API upon successful completion of a score request. It includes a request ID, processing status, update timestamp, and detailed scoring metrics. ```json { "score_request_id": "401124dd-c774-46af-b652-f6627a4ca5f6", "status": "COMPLETED", "updated_at": "2024-04-02T17:09:20.588388505Z", "score": { "general_score": 0.86, "engagement": 0.86, "correctness": 0.89, "delivery": 0.86, "clarity": 0.83 } } ``` -------------------------------- ### Get List of Invitees (cURL) Source: https://developer.grammarly.com/license-management-api This cURL command retrieves a paginated list of invitees associated with a Grammarly institution. It includes query parameters for limiting results and specifying a cursor for pagination, along with an authorization header. ```bash curl -X GET \ 'https://api.grammarly.com/ecosystem/api/v1/invitees?limit=10&cursor=XaB4' \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` -------------------------------- ### Get a list of users Source: https://developer.grammarly.com/license-management-api Retrieves a paginated list of users associated with a Grammarly institution. Supports filtering by limit and cursor for pagination. ```APIDOC ## GET /ecosystem/api/v1/users ### Description This API endpoint retrieves a paginated list of users associated with a Grammarly institution. Each user object in the response includes the user ID, institution ID, email, name, admin identifier, and last activity timestamp. ### Method GET ### Endpoint `https://api.grammarly.com/ecosystem/api/v1/users` ### Parameters #### Query Parameters - **limit** (Integer) - Optional - Specifies the maximum number of user records to return per request. The minimum possible value is 1, while the maximum is 250. If the parameter is missing, it will default to 100. - **cursor** (String) - Optional - Specifies the starting point of the records to return, enabling pagination. When it’s not passed, the API will return the first set of users. The value in the returned `next_cursor` should be set to this cursor value to get the next page set. ### Request Example ```bash curl -X GET \ 'https://api.grammarly.com/ecosystem/api/v1/users?limit=10&cursor=XaB4' \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` ### Response #### Success Response (200) - **data** (Array) - An array of user objects containing user details. - **paging** (Object) - An object containing info about the returned response. Each user object in the `data` array has the following structure: - **user_id** (Integer) - A unique identifier for the user. - **institution_id** (Integer) - The ID of the institution the user is associated with. - **email** (String) - The user’s email address. - **name** (String) - The full name of the user. - **last_activity_at** (String) - Timestamp of the user’s last recorded activity in ISO 8601. - **is_admin** (Boolean) - A boolean to identify if that user is an admin or not. The `paging` object has the following structure: - **next_cursor** (String) - Set to the cursor that can be used to get the next set of users. - **cur_cursor** (String) - Set to the cursor passed in the request or not available if nothing existed. - **has_more** (Boolean) - Set to true if more data exists and can be requested. - **page_size** (Integer) - The total number of elements in the `data` array above. #### Response Example ```json { "data": [ { "user_id": 1234567890, "institution_id": 6123456789, "email": "john.doe@grammarly.com", "name": "John Doe", "last_activity_at": "2024-10-09T23:00:35.834Z", "is_admin": true }, { "user_id": 1234567891, "institution_id": 6123456789, "email": "Jane.Doe@grammarly.com", "name": "Jane Doe", "last_activity_at": "2024-09-07T00:33:01.006Z", "is_admin": false } ], "paging": { "next_cursor": "MTYzNTc5NDQ1", "cur_cursor": "OTIyNzQ3OTM=", "has_more": true, "page_size": 2 } } ``` ### Usage Notes Use `limit` and `cursor` parameters to manage pagination through the user list. The `last_activity_at` field helps track recent user engagement and is formatted in UTC. If the user had no activity at all, this field will be set to the time the user was created. ``` -------------------------------- ### Get a list of invitees Source: https://developer.grammarly.com/license-management-api Retrieves a paginated list of invitees associated with a Grammarly institution. Each invitee object in the response includes the invitee ID, institution ID, email, name, admin identifier, status, and creation timestamp. ```APIDOC ## GET /ecosystem/api/v1/invitees ### Description Retrieves a paginated list of invitees associated with a Grammarly institution. Each invitee object in the response includes the invitee ID, institution ID, email, name, admin identifier, status, and creation timestamp. ### Method GET ### Endpoint https://api.grammarly.com/ecosystem/api/v1/invitees ### Parameters #### Query Parameters - **limit** (Integer) - Optional - Specifies the maximum number of invitees' records to return per request. The minimum possible value is 1, while the maximum is 250. If the parameter is missing, it will default to 100. - **cursor** (String) - Optional - Specifies the starting point of the records to return, enabling pagination. When it’s not passed, the API will return the first set of invitees. The value in the returned `next_cursor` should be set to this cursor value to get the next page set. ### Request Example ```bash curl -X GET \ 'https://api.grammarly.com/ecosystem/api/v1/invitees?limit=10&cursor=XaB4' \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` ### Response #### Success Response (200) - **data** (Array) - An array of invitee objects containing invitee details. - **paging** (Object) - An object containing information about the returned response. Each invitee object in the `data` array has the following structure: - **id** (Integer) - A unique identifier for the invitee. - **institution_id** (Integer) - The ID of the institution the invitee is associated with. - **email** (String) - The invitee’s email address. - **name** (String) - The full name of the invitee. - **created_at** (String) - Timestamp of the invitee’s creation time in ISO 8601. - **is_admin** (Boolean) - A boolean to identify if that invitee is an admin or not. - **status** (String) - Either `INVITED` or `EXPIRED`. The `paging` object has the following structure: - **next_cursor** (String) - Set to the cursor that can be used to get the next set of invitees. It will not be available if no more data exists. - **cur_cursor** (String) - Set to the cursor passed in the request or not available if nothing existed. - **has_more** (Boolean) - Set to true if more data exists and can be requested. - **page_size** (Integer) - The total number of elements in the `data` array. #### Response Example ```json { "data": [ { "id": 1234567890, "institution_id": 6123456789, "email": "john.doe@grammarly.com", "name": "John Doe", "created_at": "2023-05-16T18:19:36Z", "status": "EXPIRED", "is_admin": true }, { "id": 1234567891, "institution_id": 6123456789, "email": "Jane.Doe@grammarly.com", "name": "Jane Doe", "created_at": "2023-05-16T18:21:02Z", "status": "INVITED", "is_admin": false } ], "paging": { "next_cursor": "MTYzNTc5NDQ1", "cur_cursor": "OTIyNzQ3OTM=", "has_more": true, "page_size": 2 } } ``` ``` -------------------------------- ### Grammarly API Authentication and Data Fetching in C# Source: https://developer.grammarly.com/your-first-api-request This C# code snippet demonstrates how to authenticate with the Grammarly API using client credentials to obtain an access token. It then uses this token to make a GET request to the institutions-summary endpoint. Ensure the `CLIENT_ID` and `CLIENT_SECRET` environment variables are set. ```csharp using System; using System.Net.Http; using System.Threading.Tasks; using System.Text; using System.Text.Json; class GrammarlyAPIExample { private static readonly string CLIENT_ID = Environment.GetEnvironmentVariable("CLIENT_ID"); private static readonly string CLIENT_SECRET = Environment.GetEnvironmentVariable("CLIENT_SECRET"); private const string TOKEN_ENDPOINT = "https://auth.grammarly.com/v4/api/oauth2/token"; private const string SCOPE = "users-api:read"; private const string API_ENDPOINT = "https://api.grammarly.com/ecosystem/api/institutions-summary"; public static async Task GetAccessTokenAsync() { using HttpClient client = new(); var content = new FormUrlEncodedContent(new[] { new KeyValuePair("grant_type", "client_credentials"), new KeyValuePair("client_id", CLIENT_ID), new KeyValuePair("client_secret", CLIENT_SECRET), new KeyValuePair("scope", SCOPE) }); HttpResponseMessage response = await client.PostAsync(TOKEN_ENDPOINT, content); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); JsonDocument json = JsonDocument.Parse(responseBody); return json.RootElement.GetProperty("access_token").GetString(); } public static async Task FetchUserDataAsync() { string accessToken = await GetAccessTokenAsync(); using HttpClient client = new(); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}"); HttpResponseMessage response = await client.GetAsync(API_ENDPOINT); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } public static async Task Main(string[] args) { await FetchUserDataAsync(); } } ``` -------------------------------- ### Authenticate and Fetch Data with Python Requests Source: https://developer.grammarly.com/your-first-api-request This Python script shows how to authenticate with the Grammarly API and fetch data using the requests library. It defines functions to obtain an access token and then make an authenticated GET request to the API. Client credentials should be stored as environment variables. ```python import os import requests # Load client credentials from environment variables CLIENT_ID = os.getenv('CLIENT_ID') CLIENT_SECRET = os.getenv('CLIENT_SECRET') TOKEN_ENDPOINT = "https://auth.grammarly.com/v4/api/oauth2/token" SCOPE = "users-api:read" API_ENDPOINT = "https://api.grammarly.com/ecosystem/api/institutions-summary" # Step 1: Request Access Token def get_access_token(): payload = { "grant_type": "client_credentials", "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "scope": SCOPE } response = requests.post(TOKEN_ENDPOINT, data=payload) response.raise_for_status() # Raise an exception for HTTP errors return response.json().get("access_token") # Step 2: Make Authenticated API Request def fetch_user_data(): access_token = get_access_token() headers = { "Authorization": f"Bearer {access_token}" } response = requests.get(API_ENDPOINT, headers=headers) response.raise_for_status() return response.json() # Example usage if __name__ == "__main__": data = fetch_user_data() print(data) ``` -------------------------------- ### Make Authenticated API Request with Bash and cURL Source: https://developer.grammarly.com/your-first-api-request This bash snippet demonstrates how to make a GET request to the Grammarly API using an obtained access token. It fetches user data from the Analytics API and prints the response. The Authorization header is set with the bearer token. ```bash # Define the API endpoint for the user data USER_DATA_ENDPOINT="https://api.grammarly.com/ecosystem/api/v2/analytics/users?limit=10&date_from=2024-10-01&date_to=2024-10-31 # Make a GET request to the API with the access token user_data=$(curl -s -X GET "$USER_DATA_ENDPOINT" \ -H "Authorization: Bearer $ACCESS_TOKEN") # Output the user data echo "$user_data" ``` -------------------------------- ### Get a list of users from Grammarly API Source: https://developer.grammarly.com/license-management-api Retrieves a paginated list of users associated with a Grammarly institution. It accepts optional 'limit' and 'cursor' parameters for pagination. The response includes user details and paging information, useful for managing user access and activity. ```bash curl -X GET \ 'https://api.grammarly.com/ecosystem/api/v1/users?limit=10&cursor=XaB4' \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` -------------------------------- ### Get analytics for users Source: https://developer.grammarly.com/analytics-api Retrieves a paginated list of users associated with a Grammarly subscription, including their usage statistics. Requires 'analytics-api:read' scope. ```APIDOC ## GET /ecosystem/api/v2/analytics/users ### Description This API endpoint retrieves a paginated list of users associated with a Grammarly subscription. Each user object in the response includes the user ID and Grammarly usage statistics. ### Method GET ### Endpoint `https://api.grammarly.com/ecosystem/api/v2/analytics/users/` ### Parameters #### Query Parameters - **date_from** (String) - Required - Start date for filtering user statistics in the YYYY-MM-DD format. The earliest supported start date is one year prior to the current date. - **date_to** (String) - Required - End date for filtering user statistics in the YYYY-MM-DD format. The latest supported date is two days before the current date. - **cursor** (String) - Optional - Marker to paginate through large data sets. No cursor is required for the initial request. If additional pages are available, the response will contain a **next_cursor** value, which should be used as the **cursor** value in the subsequent request. - **limit** (Integer) - Optional - Limit on the number of returned entries. The maximum value is 400. Must be a positive number. ### Request Example ```bash curl -X GET \ 'https://api.grammarly.com/ecosystem/api/v2/analytics/users?limit=10&date_from=2024-10-19&date_to=2024-10-22' \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` ### Response #### Success Response (200) - **data** (Array) - An array of user objects containing user statistics details. - **paging** (Object) - API paging object. Each user object in the `data` array has the following structure: - **id** (Integer) - A unique identifier for the user. - **name** (String) - Name of the user. - **email** (String) - User’s email address. - **days_active** (Integer) - The number of days a team member actively used Grammarly within the specified date range. - **sessions_count** (Integer) - The number of writing sessions that took place during the specified date range. A writing session occurs when a team member uses Grammarly to actively write or edit text. A session automatically ends after 30 minutes of inactivity. - **sessions_improved_percent** (Float) - The percentage of writing sessions that were improved out of writing sessions that had at least one error and took place during the selected date range. A writing session is considered improved if there are fewer mistakes in the text at the end of a session than at the beginning. - **prompt_count** (Integer) - The number of generative AI prompts used by a team member within the date range. The `paging` object has the following structure: - **next_cursor** (String) - An encoded cursor that is used to fetch the next set of results, if available. It will not be returned if no more data is available. - **cur_cursor** (String) - The cursor from the client request will be used if specified. - **has_more** (Boolean) - Indicates whether there are additional records available in the database. - **page_size** (Integer) - Number of items included in the `data` array in the current response. #### Response Example ```json { "data": [ { "id": 123, "name": "name", "email": "email.address@email.com", "days_active": 1, "sessions_count": 2, "prompt_count": 3, "sessions_improved_percent": 28.571428571428573 } ], "paging": { "next_cursor": "MTI=", "cur_cursor": "xyZ", "has_more": true, "page_size": 1 } } ``` ### Data availability The data is accessible for 365 days prior, with a two-day lag from the current date. For example, if you make a request on November 1, 2024, the valid date range for **date_from** and **date_to** would be between October 30, 2023 and October 30, 2024. ``` -------------------------------- ### Example JSON Response for User Analytics Source: https://developer.grammarly.com/analytics-api This JSON structure represents a typical response from the Grammarly Analytics API when fetching user data. It includes an array of user objects, each with detailed usage statistics, and a paging object for navigating through results. ```json { "data": [ { "id": 123, "name": "name", "email": "email.address@email.com", "days_active": 1, "sessions_count": 2, "prompt_count": 3, "sessions_improved_percent": 28.571428571428573 } ], "paging": { "next_cursor": "MTI=", "cur_cursor": "xyZ", "has_more": true, "page_size": 1 } } ``` -------------------------------- ### Get Invitees Response (JSON) Source: https://developer.grammarly.com/license-management-api This JSON object represents a successful response from the invitees endpoint. It contains an array of invitee objects, each with details like ID, email, status, and admin status, along with a paging object for managing subsequent requests. ```json { "data": [ { "id": 1234567890, "institution_id": 6123456789, "email": "john.doe@grammarly.com", "name": "John Doe", "created_at": "2023-05-16T18:19:36Z", "status": "EXPIRED", "is_admin": true }, { "id": 1234567891, "institution_id": 6123456789, "email": "Jane.Doe@grammarly.com", "name": "Jane Doe", "created_at": "2023-05-16T18:21:02Z", "status": "INVITED", "is_admin": false } ], "paging": { "next_cursor": "MTYzNTc5NDQ1", "cur_cursor": "OTIyNzQ3OTM=", "has_more": true, "page_size": 2 } } ``` -------------------------------- ### Get User Analytics using cURL Source: https://developer.grammarly.com/analytics-api This snippet demonstrates how to retrieve a paginated list of users and their Grammarly usage statistics using a cURL command. It requires an access token and specifies date ranges and a limit for the results. The response includes user details and pagination information. ```bash curl -X GET \ 'https://api.grammarly.com/ecosystem/api/v2/analytics/users?limit=10&date_from=2024-10-19&date_to=2024-10-22' \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` -------------------------------- ### GET /ecosystem/api/v1/plagiarism/{score_request_id} Source: https://developer.grammarly.com/plagiarism-detection-api Retrieves the result of the plagiarism detection evaluation using the `score_request_id` obtained from the initial request. ```APIDOC ## GET /ecosystem/api/v1/plagiarism/{score_request_id} ### Description This API endpoint returns the result of the plagiarism detection evaluation. It requires the `score_request_id` obtained from the initial POST request. ### Method GET ### Endpoint https://api.grammarly.com/ecosystem/api/v1/plagiarism/ ### Parameters #### Path Parameters - **score_request_id** (String) - Required - Request ID from the previous step. ### Request Example ```bash curl -X GET \ 'https://api.grammarly.com/ecosystem/api/v1/plagiarism/' \ -H 'Authorization: Bearer ' \ -H 'Accept: application/json' \ -H 'user-agent: API client' ``` ### Response #### Success Response (200) - **score_request_id** (String) - Request ID used to request the plagiarism detection score evaluation results. - **status** (String) - Request processing status (`PENDING`, `FAILED`, `COMPLETED`). - **updated_at** (DateTime) - Date and time of the status update. - **score** (Object) - Object with the resulting value. - **score.originality** (Number) - A number from 0 to 1 that represents the originality of the text. The higher the score, the more original the text. A completely plagiarised text will have a score of 0. #### Response Example ```json { "score_request_id": "4bed7ce8-95f1-4e84-85d4-8f1e5744f950", "status": "COMPLETED", "updated_at": "2024-11-18T14:55:27.337443115Z", "score": { "originality": 0.89 } } ``` ``` -------------------------------- ### OAuth 2.0 Credentials Source: https://developer.grammarly.com/oauth-credentials Instructions for obtaining OAuth 2.0 client ID and secret for Grammarly API integration. ```APIDOC ## Receive OAuth 2.0 credentials Grammarly API uses OAuth 2.0 protocol for secure integration with third-party applications. To receive OAuth credentials for your application, follow these steps: 1. Go to your **Admin panel**. 2. Open the **Organization** tab and choose **OAuth 2.0 credentials** in the **Configurations** section. 3. On the next page, click **Add credential** in the upper-right corner. 4. In the window that appears, enter a name and check the box next to the API you will use. 5. Click **Create**. 6. Next, click **Copy to clipboard** to save your **Client ID** and **Secret**. ``` -------------------------------- ### Obtain Access Token with Bash and cURL Source: https://developer.grammarly.com/your-first-api-request This snippet shows how to request an access token from Grammarly's OAuth server using a cURL command in bash. It requires client ID and secret, and outputs a JSON response from which the access token can be extracted using jq. ```bash # Define your client credentials and API endpoint CLIENT_ID="your_client_id" CLIENT_SECRET="your_client_secret" TOKEN_ENDPOINT="https://auth.grammarly.com/v4/api/oauth2/token" SCOPE="users-api:read, users-api:write" # string with comma separated scopes # Use curl to make a POST request to obtain an access token with the specified scope response=$(curl -s -X POST "$TOKEN_ENDPOINT" \ -d "grant_type=client_credentials" \ -d "client_id=$CLIENT_ID" \ -d "client_secret=$CLIENT_SECRET" \ -d "scope=$SCOPE") # Extract the access token from the response ACCESS_TOKEN=$(echo $response | jq -r .access_token) ``` -------------------------------- ### GET /ecosystem/api/v1/ai-detection - Request Evaluation Result Source: https://developer.grammarly.com/ai-detection-api Retrieves the AI detection evaluation results for a given score request ID. It returns the status of the evaluation and the AI score if ready. ```APIDOC ## GET /ecosystem/api/v1/ai-detection/{score_request_id} ### Description This API endpoint returns the result of the AI detection evaluation. It requires the `score_request_id` obtained from the initial transaction request. The response contains the status of the evaluation and, if ready, the AI score details. ### Method GET ### Endpoint https://api.grammarly.com/ecosystem/api/v1/ai-detection/{score_request_id} ### Parameters #### Path Parameters - **score_request_id** (String) - Required - Request ID from the previous step. #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X GET \ 'https://api.grammarly.com/ecosystem/api/v1/ai-detection/' \ -H 'Authorization: Bearer ' \ -H 'Accept: application/json' \ -H 'user-agent: API client' ``` ### Response #### Success Response (200) - **status** (String) - The status of the evaluation process (e.g., 'processing', 'completed'). - **score** (Object) - Contains the AI detection results if the evaluation is completed. - **ai_generated_percentage** (Number) - Percentage of text that appears AI-generated. - **confidence_level** (Number) - Confidence level that the text is AI-generated. #### Response Example ```json { "status": "completed", "score": { "ai_generated_percentage": 85.5, "confidence_level": 0.92 } } ``` ``` -------------------------------- ### GET /ecosystem/api/v2/scores/ Source: https://developer.grammarly.com/writing-score-api Retrieves the writing score evaluation results for a given score request ID. This endpoint allows users to check the status and results of a previously submitted document. ```APIDOC ## GET /ecosystem/api/v2/scores/ ### Description Retrieves the writing score evaluation results for a given score request ID. This endpoint allows users to check the status and results of a previously submitted document. ### Method GET ### Endpoint /ecosystem/api/v2/scores/ ### Parameters #### Path Parameters - **score_request_id** (String) - Required - The unique identifier for the score request. #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "" } ``` ### Response #### Success Response (200) - **score_request_id** (String) - The request ID for the writing score evaluation results. - **status** (String) - Request processing status (`PENDING`, `FAILED`, `COMPLETED`). - **updated_at** (DateTime) - DateTime when the status was updated. - **score** (Object) - Object containing the resulting scores. - **general_score** (Number) - The overall score representing writing quality. - **engagement** (Number) - Score highlighting potential to make writing more engaging. - **correctness** (Number) - Score reflecting spelling, punctuation, and grammar issues. - **delivery** (Number) - Score assessing politeness, formality, and friendliness balance. - **clarity** (Number) - Score signifying potential clarity and conciseness improvements. #### Response Example ```json { "score_request_id": "401124dd-c774-46af-b652-f6627a4ca5f6", "status": "COMPLETED", "updated_at": "2024-04-02T17:09:20.588388505Z", "score": { "general_score": 0.86, "engagement": 0.86, "correctness": 0.89, "delivery": 0.86, "clarity": 0.83 } } ``` ``` -------------------------------- ### Overview of OAuth Scopes Source: https://developer.grammarly.com/oauth-credentials Details the available OAuth scopes for Grammarly API, defining the permissions granted to integrated applications. ```APIDOC ## Overview of OAuth scopes Grammarly’s OAuth credentials can be assigned OAuth scopes, which are features that define the specific permissions granted to an OAuth client when accessing the Grammarly API. OAuth scopes limit access to only necessary resources, enhancing security by minimizing granted permissions. Each OAuth client can be assigned the following scopes: | Scope | Description | |---|---| | `scores-api:read` | Provides read-only access to the Writing Score API, allowing applications to retrieve writing scores for submitted text. Suitable for applications that evaluate or analyze text quality, offering insights like writing clarity, engagement, and overall score. | | `scores-api:write` | Provides write access to the Writing Score API, enabling applications to submit documents for writing score evaluations. Suitable for applications that evaluate or analyze text quality, offering insights like writing clarity, engagement, and overall score. | | `analytics-api:read` | Grants read-only access to the Analytics API, which provides Grammarly usage statistics for team plan members, including metrics like the number of writing sessions, the percentage of improved writing sessions, and generative AI prompt usage. This scope is commonly used by BI applications or analytical dashboards that show engagement with Grammarly. | | `users-api:read` | Grants read-only access to the License Management API, allowing applications to retrieve user and invitee details such as name, email, and subscription status, and get the institution subscription summary. Suitable for applications that need to retrieve user and invitee data for display purposes or account verification. | | `users-api:write` | Grants write access to the License Management API, enabling applications to update and delete user and invitee information. Suitable for applications that need to remove users or invitees from the Grammarly subscription. | ``` -------------------------------- ### Obtain Access Token Source: https://developer.grammarly.com/your-first-api-request This endpoint is used to authenticate a client and obtain an access token from Grammarly's OAuth server. The access token is required for all subsequent API calls. ```APIDOC ## POST /v4/api/oauth2/token ### Description Requests an access token using client credentials and specified scopes. ### Method POST ### Endpoint https://auth.grammarly.com/v4/api/oauth2/token ### Parameters #### Query Parameters - **grant_type** (string) - Required - Must be "client_credentials". - **client_id** (string) - Required - Your application's client ID. - **client_secret** (string) - Required - Your application's client secret. - **scope** (string) - Required - A space-separated string of scopes your application requires. ### Request Example ```bash CLIENT_ID="your_client_id" CLIENT_SECRET="your_client_secret" TOKEN_ENDPOINT="https://auth.grammarly.com/v4/api/oauth2/token" SCOPE="users-api:read, users-api:write" curl -s -X POST "$TOKEN_ENDPOINT" \ -d "grant_type=client_credentials" \ -d "client_id=$CLIENT_ID" \ -d "client_secret=$CLIENT_SECRET" \ -d "scope=$SCOPE" ``` ### Response #### Success Response (200) - **access_token** (string) - The obtained access token. - **token_type** (string) - The type of token (e.g., "Bearer"). - **expires_in** (integer) - The lifetime in seconds of the access token. #### Response Example ```json { "access_token": "eyJ...".", "token_type": "Bearer", "expires_in": 3600 } ``` ```