Your first API request
The examples below demonstrate how to authenticate a client and make API requests to Grammarly using OAuth credentials.
Authenticating with OAuth to obtain an Access Token
To authenticate, use the Client ID and Client Secret to request an Access Token from Grammarly’s OAuth server. This token is required for all subsequent API calls.
In this example, we’ll use a curl command in bash to request an Access Token. This example uses the jq tool to parse JSON responses. You can install jq by running sudo apt-get install jq on Ubuntu and Debian or brew install jq on macOS.
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)
Important: To avoid exposing sensitive information in your scripts, always store your Client ID and Client Secret as environment variables or in a secure location.
Making an authenticated API request using an Access Token
Once you have an Access Token, you can use it to make requests to the Grammarly API.
Here’s an example of fetching user data from the Analytics API using the retrieved 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"
Example in Python
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)
Example in Java 11+
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);
}
}
Example in Node.js
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();
Example in C#
cs
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<string> GetAccessTokenAsync()
{
using HttpClient client = new();
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", CLIENT_ID),
new KeyValuePair<string, string>("client_secret", CLIENT_SECRET),
new KeyValuePair<string, string>("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();
}
}