FastComments.com

FastComments Java SDK


Това е официалният Java SDK на FastComments.

Официален Java SDK за API-то на FastComments

Репозитория

Вижте в GitHub


Installation Internal Link

Maven

Add the Repsy repository to your project's POM:

<repositories>
    <repository>
        <id>repsy</id>
        <name>FastComments Maven Repository on Repsy</name>
        <url>https://repo.repsy.io/mvn/winrid/fastcomments</url>
    </repository>
</repositories>

Then add the dependencies you need:

<dependencies>
    <!-- API Client -->
    <dependency>
        <groupId>com.fastcomments</groupId>
        <artifactId>client</artifactId>
        <version>3.0.1</version>
    </dependency>
    
    <!-- Core Library (includes SSO) -->
    <dependency>
        <groupId>com.fastcomments</groupId>
        <artifactId>core</artifactId>
        <version>3.0.1</version>
    </dependency>
    
    <!-- PubSub Library (for live events) -->
    <dependency>
        <groupId>com.fastcomments</groupId>
        <artifactId>pubsub</artifactId>
        <version>3.0.1</version>
    </dependency>
</dependencies>

Gradle

Add the Repsy repository to your build.gradle file:

repositories {
    mavenCentral()
    maven {
        url "https://repo.repsy.io/mvn/winrid/fastcomments"
    }
}

dependencies {
    // API Client
    implementation "com.fastcomments:client:3.0.1"
    
    // Core Library (includes SSO)
    implementation "com.fastcomments:core:3.0.1"
    
    // PubSub Library (for live events)
    implementation "com.fastcomments:pubsub:3.0.1"
}

Library Contents

This library contains three modules. The generated API client, the core Java library which contains hand-written utilities to make working with the API easier, and the pubsub module which is a library for subscribing to change feeds.

Public vs Secured APIs

For the API client, there are three classes, DefaultApi, PublicApi, and ModerationApi. The DefaultApi contains methods that require your API key, and PublicApi contains methods that can be made directly from a browser/mobile device/etc without authentication.

The ModerationApi provides an extensive suite of live and fast moderation APIs. Every ModerationApi method accepts an sso parameter and can authenticate via SSO or a FastComments.com session cookie.

Quick Start Internal Link

Използване на автентифицирани API-та (DefaultApi)

Важно: Трябва да зададете вашия API ключ в ApiClient преди да правите автентифицирани заявки. Ако не го направите, заявките ще се провалят с грешка 401.

import com.fastcomments.invoker.ApiClient;
import com.fastcomments.invoker.ApiException;
import com.fastcomments.api.DefaultApi;
import com.fastcomments.model.*;

public class Example {
    public static void main(String[] args) {
        // Създайте и конфигурирайте API клиента
        ApiClient apiClient = new ApiClient();

        // ЗАДЪЛЖИТЕЛНО: Задайте вашия API ключ (вземете го от таблото на FastComments)
        apiClient.setApiKey("YOUR_API_KEY_HERE");

        // Създайте екземпляр на API-то с конфигурирания клиент
        DefaultApi api = new DefaultApi(apiClient);

        // Сега можете да правите автентифицирани API извиквания
        try {
            // Пример: Добавяне на SSO потребител
            CreateAPISSOUserData userData = new CreateAPISSOUserData();
            userData.setId("user-123");
            userData.setEmail("user@example.com");
            userData.setDisplayName("John Doe");

            AddSSOUserAPIResponse response = api.addSSOUser("YOUR_TENANT_ID", userData)
                .execute();
            System.out.println("User created: " + response);

        } catch (ApiException e) {
            System.err.println("Error: " + e.getResponseBody());
            // Общи грешки:
            // - 401: липсва API ключ или е невалиден
            // - 400: Валидацията на заявката е неуспешна
        }
    }
}

Използване на публични API-та (PublicApi)

Публичните крайни точки не изискват удостоверяване:

import com.fastcomments.api.PublicApi;
import com.fastcomments.invoker.ApiException;

PublicApi publicApi = new PublicApi();

try {
    var response = publicApi.getCommentsPublic("YOUR_TENANT_ID", "page-url-id")
        .execute();
    System.out.println(response);
} catch (ApiException e) {
    e.printStackTrace();
}

Използване на API-та за модерация (ModerationApi)

Класът ModerationApi управлява таблото на модератора. Във всеки метод се приема параметър sso, който идентифицира SSO-автентифицирания модератор от чие име се прави заявката:

import com.fastcomments.api.ModerationApi;
import com.fastcomments.invoker.ApiException;
import com.fastcomments.model.*;

ModerationApi moderationApi = new ModerationApi();

try {
    // Изброяване на коментари, чакащи модерация
    ModerationAPIGetCommentsResponse response = moderationApi.getApiComments()
        .sso("YOUR_SSO_TOKEN")
        .execute();
    System.out.println(response);
} catch (ApiException e) {
    e.printStackTrace();
}

Чести проблеми

  1. 401 "missing-api-key" грешка: Уверете се, че извиквате apiClient.setApiKey("YOUR_KEY") преди да създадете инстанцията на DefaultApi.
  2. Грешен клас API: Използвайте DefaultApi за сървърни автентифицирани заявки, PublicApi за клиентски/публични заявки.
  3. Null API ключ: SDK-то ще пропусне удостоверяването без съобщение, ако API ключът е null, което ще доведе до грешки 401.

Notes Internal Link

Идентификатори на излъчване

Ще видите, че трябва да подадете broadcastId в някои API повиквания. Когато получите събития, ще получите този идентификатор обратно, така че да знаете да игнорирате събитието, ако възнамерявате оптимистично да прилагате промените на клиента (което вероятно ще искате да направите, тъй като осигурява най-доброто потребителско изживяване). Подайте тук UUID. Идентификаторът трябва да е достатъчно уникален, за да не се появи два пъти в рамките на една браузърна сесия.


Нуждаете се от помощ?

Ако срещнете проблеми или имате въпроси относно Java SDK, моля:

Допринасяне

Приноси са добре дошли! Моля посетете хранилището в GitHub за указания относно приноса.