> ## Documentation Index
> Fetch the complete documentation index at: https://new-docs.simplecloud.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Installation

> Add the Cloud API to your Minecraft plugin or standalone application

export const DependencySnippet = ({dependencies = [], repositories = [{
  id: "simplecloud",
  url: "https://repo.simplecloud.app/snapshots"
}, {
  id: "buf",
  url: "https://buf.build/gen/maven"
}], type = "snapshot"}) => {
  const [versions, setVersions] = useState({});
  useEffect(() => {
    dependencies.forEach(dep => {
      if (dep.version) return;
      const fetchVersion = async () => {
        try {
          const url = type === "snapshot" ? `https://repo.simplecloud.app/api/maven/latest/version/snapshots/${dep.groupId.replace(/\./g, "/")}/${dep.artifactId}?type=raw` : `https://search.maven.org/solrsearch/select?q=g:${dep.groupId}+AND+a:${dep.artifactId}&rows=1&wt=json`;
          const res = await fetch(url);
          if (type === "snapshot") {
            const version = await res.text();
            setVersions(prev => ({
              ...prev,
              [`${dep.groupId}:${dep.artifactId}`]: version.trim()
            }));
          } else {
            const data = await res.json();
            const version = data.response?.docs?.[0]?.latestVersion;
            if (version) {
              setVersions(prev => ({
                ...prev,
                [`${dep.groupId}:${dep.artifactId}`]: version
              }));
            }
          }
        } catch (e) {
          console.error("Failed to fetch version", e);
        }
      };
      fetchVersion();
    });
  }, [dependencies, type]);
  const getVersion = dep => {
    if (dep.version) return dep.version;
    return versions[`${dep.groupId}:${dep.artifactId}`] || "LATEST";
  };
  const generateKotlin = () => {
    const repoLines = repositories.map(r => `    maven("${r.url}")`).join("\n");
    const depLines = dependencies.map(dep => {
      const depType = dep.type || "implementation";
      return `    ${depType}("${dep.groupId}:${dep.artifactId}:${getVersion(dep)}")`;
    }).join("\n");
    return `repositories {\n${repoLines}\n}\n\ndependencies {\n${depLines}\n}`;
  };
  const generateGroovy = () => {
    const repoLines = repositories.map(r => `    maven { url '${r.url}' }`).join("\n");
    const depLines = dependencies.map(dep => {
      const depType = dep.type || "implementation";
      return `    ${depType} '${dep.groupId}:${dep.artifactId}:${getVersion(dep)}'`;
    }).join("\n");
    return `repositories {\n${repoLines}\n}\n\ndependencies {\n${depLines}\n}`;
  };
  const generateMaven = () => {
    const repoLines = repositories.map(r => `    <repository>
      <id>${r.id || 'repo'}</id>
      <url>${r.url}</url>
    </repository>`).join("\n");
    const depLines = dependencies.map(dep => {
      const scope = dep.type === "compileOnly" ? "provided" : "compile";
      return `    <dependency>
      <groupId>${dep.groupId}</groupId>
      <artifactId>${dep.artifactId}</artifactId>
      <version>${getVersion(dep)}</version>
      <scope>${scope}</scope>
    </dependency>`;
    }).join("\n");
    return `<repositories>\n${repoLines}\n</repositories>\n\n<dependencies>\n${depLines}\n</dependencies>`;
  };
  return <Tabs>
      <Tab title="Gradle (Kotlin)">
        <CodeBlock language="kotlin">
          {generateKotlin()}
        </CodeBlock>
      </Tab>
      <Tab title="Gradle (Groovy)">
        <CodeBlock language="groovy">
          {generateGroovy()}
        </CodeBlock>
      </Tab>
      <Tab title="Maven">
        <CodeBlock language="xml">
          {generateMaven()}
        </CodeBlock>
      </Tab>
    </Tabs>;
};

## Add Dependencies

Add the Cloud API to your build configuration. The version is fetched automatically from our Maven repository.

<DependencySnippet
  dependencies={[
{
  groupId: "app.simplecloud.api",
  artifactId: "api",
  type: "implementation",
},
]}
  repositories={[
{ id: "simplecloud", url: "https://repo.simplecloud.app/snapshots" },
{ id: "buf", url: "https://buf.build/gen/maven" },
]}
  type="snapshot"
/>

## Plugin Setup

Add the SimpleCloud API plugin as a dependency in your plugin descriptor:

<Tabs>
  <Tab title="Paper/Spigot (plugin.yml)">
    ```yaml theme={null}
    name: my-plugin
    version: 1.0.0
    main: com.example.MyPlugin
    depend: [simplecloud-api]
    ```
  </Tab>

  <Tab title="Velocity (velocity-plugin.json)">
    ```json theme={null}
    {
      "id": "my-plugin",
      "name": "My Plugin",
      "version": "1.0.0",
      "main": "com.example.MyPlugin",
      "dependencies": [{ "id": "simplecloud-api", "optional": false }]
    }
    ```
  </Tab>

  <Tab title="BungeeCord (bungee.yml)">
    ```yaml theme={null}
    name: my-plugin
    version: 1.0.0
    main: com.example.MyPlugin
    depends: [simplecloud-api]
    ```
  </Tab>
</Tabs>

<Warning>
  Don't shade the Cloud API into your plugin. Depend on the `simplecloud-api`
  plugin instead.
</Warning>

## Initialize the API

### Default Configuration

When running inside a SimpleCloud server, the API auto-configures from environment variables:

<Tabs>
  <Tab title="Java">
    ```java theme={null}
    import app.simplecloud.api.CloudApi;

    public class MyPlugin extends JavaPlugin {
        private CloudApi api;

        @Override
        public void onEnable() {
            api = CloudApi.create();
        }
    }
    ```
  </Tab>

  <Tab title="Kotlin">
    ```kotlin theme={null}
    import app.simplecloud.api.CloudApi

    class MyPlugin : JavaPlugin() {
        private lateinit var api: CloudApi

        override fun onEnable() {
            api = CloudApi.create()
        }
    }
    ```
  </Tab>
</Tabs>

### Custom Configuration

For standalone applications or custom setups, provide configuration options:

<Tabs>
  <Tab title="Java">
    ```java theme={null}
    CloudApi api = CloudApi.create(CloudApiOptions.builder()
        .networkId("your-network-id")
        .networkSecret("your-secret")
        .controllerUrl("https://controller.simplecloud.app")
        .natsUrl("nats://platform.simplecloud.app:4222")
        .build());
    ```
  </Tab>

  <Tab title="Kotlin">
    ```kotlin theme={null}
    val api = CloudApi.create(CloudApiOptions.builder()
        .networkId("your-network-id")
        .networkSecret("your-secret")
        .controllerUrl("https://controller.simplecloud.app")
        .natsUrl("nats://platform.simplecloud.app:4222")
        .build())
    ```
  </Tab>
</Tabs>

## Environment Variables

The API reads these environment variables by default:

| Variable                     | Default                                  | Description             |
| ---------------------------- | ---------------------------------------- | ----------------------- |
| `SIMPLECLOUD_NETWORK_ID`     | `"default"`                              | Your network identifier |
| `SIMPLECLOUD_NETWORK_SECRET` | `""`                                     | Authentication secret   |
| `SIMPLECLOUD_CONTROLLER_URL` | `"https://controller.simplecloud.app"`   | Controller API endpoint |
| `SIMPLECLOUD_NATS_URL`       | `"nats://platform.simplecloud.app:4222"` | NATS server for events  |

<Note>
  Inside SimpleCloud servers, these variables are set automatically. You only
  need to configure them for standalone applications or external services.
</Note>

## Best Practices

<AccordionGroup>
  <Accordion title="Use a single API instance">
    Create one `CloudApi` instance and reuse it. Use dependency injection if your framework supports it.

    ```java theme={null}
    // Good - single instance
    private final CloudApi api = CloudApi.create();

    // Avoid - multiple instances
    public void doSomething() {
        CloudApi api = CloudApi.create(); // Don't do this
    }
    ```
  </Accordion>

  <Accordion title="Handle async operations properly">
    All API methods return `CompletableFuture`. Don't block on the main thread.

    ```java theme={null}
    // Good - async handling
    api.server().getAllServers().thenAccept(servers -> {
        // Process servers
    });

    // Avoid - blocking
    List<Server> servers = api.server().getAllServers().join(); // Don't block!
    ```
  </Accordion>

  <Accordion title="Clean up event subscriptions">
    Subscriptions implement `AutoCloseable`. Close them when done.

    ```java theme={null}
    Subscription sub = api.event().server().onStarted(event -> { ... });

    // When shutting down
    sub.close();
    ```
  </Accordion>
</AccordionGroup>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Dependency not found">
    **Symptom:** Gradle/Maven can't resolve `app.simplecloud.api:api`.

    **Solution:**

    1. Add both repositories:
       * `https://repo.simplecloud.app/snapshots`
       * `https://buf.build/gen/maven`
    2. Refresh: `gradle --refresh-dependencies` or `mvn -U clean install`
    3. Check network access to repository URLs
  </Accordion>

  <Accordion title="NoClassDefFoundError at runtime">
    **Symptom:** Plugin fails with `ClassNotFoundException` for SimpleCloud classes.

    **Cause:** API shaded into JAR or plugin load order wrong.

    **Solution:**

    1. Don't shade the API - use `compileOnly` scope
    2. Add `simplecloud-api` to plugin descriptor dependencies
    3. Verify SimpleCloud API plugin loads before yours
  </Accordion>

  <Accordion title="API initialization fails">
    **Symptom:** `CloudApi.create()` throws exception.

    **If connection refused:**

    * Verify server runs inside SimpleCloud
    * Check environment variables are set
    * For standalone apps, verify controller/NATS URLs

    **If authentication failed:**

    * Check `SIMPLECLOUD_NETWORK_ID` is correct
    * Check `SIMPLECLOUD_NETWORK_SECRET` matches
  </Accordion>

  <Accordion title="Version conflicts">
    **Symptom:** Errors about incompatible API versions.

    **Solution:**

    1. Use `compileOnly` scope (not `implementation`)
    2. Check other plugins for bundled API versions
    3. Match API version to your SimpleCloud installation
  </Accordion>
</AccordionGroup>
