# API

This module allows you to create application endpoints that can be used to interact with the application from the outside, such as other applications and more.

**Security Warning:** When creating custom API endpoints, always protect them with proper authentication middleware. See the [Security Best Practices](/app-project-module/security/) guide to learn how to secure your endpoints with `moduleKey` validation.

[API Module](https://support.crowdin.com/developer/crowdin-apps-module-api/)

## Sample

```js ins={14-26} wrap title="index.js"
    import crowdinModule from '@crowdin/app-project-module';

    const app = crowdinModule.express();

    const configuration = {
      baseUrl: 'https://123.ngrok.io',
      clientId: 'clientId',
      clientSecret: 'clientSecret',
      name: 'Sample App',
      identifier: 'sample-app',
      description: 'Sample App description',
      dbFolder: import.meta.dirname,
      imagePath: import.meta.dirname + '/logo.png',
      api: {
        default: true,
        docFile: import.meta.filename,
        endpoints: [
          {
            key: 'generate-report',
            name: 'Generate report',
            description: 'Get your report',
            url: '/report',
            method: 'GET'
          }
        ]
      }
    };

    const crowdinApp = crowdinModule.addCrowdinEndpoints(app, configuration);

    /**
     * @openapi
     * /report:
     *   get:
     *     tags:
     *       - 'Report'
     *     summary: 'Test'
     *     operationId: test.report
     *     parameters:
     *       -
     *         name: userId
     *         in: query
     *         required: true
     *         schema:
     *           type: integer
     *           example: 102
     *     responses:
     *       200:
     *         content:
     *          application/json:
     *            schema:
     *              properties:
     *                data:
     *                  type: object
     *                  properties:
     *                    reportUrl:
     *                      type: string
     *                      example: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf'
     */
    app.get('/report', async (req, res) => {
      try {
        // Always specify moduleKey to restrict access to authorized modules only
        const { client, context, subscriptionInfo } = await crowdinApp.establishCrowdinConnection({
          authRequest: req,
          moduleKey: ['my-api-module'] // Only allow access from specified modules
        });
        // check subscribe
        // get crowdin data
        // endpoint logic
        res.status(200).send({ reportUrl: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf' });
      } catch (e) {
        return res.status(403).send({ error: 'Access denied' });
      }
    });

    app.listen(3000, () =>  console.log('Crowdin app started'));
    ```
  ```ts ins={16-28} wrap title="index.ts"
    import crowdinModule from '@crowdin/app-project-module';
    import type { ClientConfig, CrowdinClientRequest } from '@crowdin/app-project-module';
    import { RequestMethods } from '@crowdin/app-project-module/modules/api';

    const app = crowdinModule.express();

    const configuration: ClientConfig = {
      baseUrl: 'https://123.ngrok.io',
      clientId: 'clientId',
      clientSecret: 'clientSecret',
      name: 'Sample App',
      identifier: 'sample-app',
      description: 'Sample App description',
      dbFolder: import.meta.dirname,
      imagePath: import.meta.dirname + '/logo.png',
      api: {
        default: true,
        docFile: import.meta.filename,
        endpoints: [
          {
            key: 'generate-report',
            name: 'Generate report',
            description: 'Get your report',
            url: '/report',
            method: RequestMethods.GET
          }
        ]
      }
    };

    const crowdinApp = crowdinModule.addCrowdinEndpoints(app, configuration);

    /**
     * @openapi
     * /report:
     *   get:
     *     tags:
     *       - 'Report'
     *     summary: 'Test'
     *     operationId: test.report
     *     parameters:
     *       -
     *         name: userId
     *         in: query
     *         required: true
     *         schema:
     *           type: integer
     *           example: 102
     *     responses:
     *       200:
     *         content:
     *          application/json:
     *            schema:
     *              properties:
     *                data:
     *                  type: object
     *                  properties:
     *                    reportUrl:
     *                      type: string
     *                      example: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf'
     */
    app.get('/report', async (req, res) => {
      try {
        // Always specify moduleKey to restrict access to authorized modules only
        const { client, context } = await crowdinApp.establishCrowdinConnection({
          authRequest: req as CrowdinClientRequest,
          moduleKey: ['my-api-module'] // Only allow access from specified modules
        });
        // check subscribe
        // get crowdin data
        // endpoint logic
        res.status(200).send({ reportUrl: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf' });
      } catch (e) {
        return res.status(403).send({ error: 'Access denied' });
      }
    });

    app.listen(3000, () =>  console.log('Crowdin app started'));
    ```
  In this example, we create a new endpoint `/report` that returns a link to a report. The endpoint is protected by the Crowdin authentication mechanism. It's described in the OpenAPI format, which allows you to generate documentation for your API.

**Security Note:** The `moduleKey` parameter ensures that only the specified modules can access this endpoint. Without it, any user with a valid JWT token from any module in your app could potentially call this endpoint. For more details, see the [Security Best Practices](/app-project-module/security/) guide.

## Configuration

| Parameter   | Description                                | Default value |
|-------------|--------------------------------------------|---------------|
| `default`   | Enable default endpoints for other modules | `true`        |
| `docFile`   | Path to the jsdoc file                     | `import.meta.filename` |
| `endpoints` | List of custom endpoints                   | -             |

The `endpoints` parameter is an array of objects with the following properties:

```yml
{
  name: string;
  url: string;
  method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
  description?: string;
}
```

## Default Endpoints for Project Integration

The [Project Integration](/app-project-module/project-integration/) module automatically includes the API module with the `default: true` parameter. This means the default endpoints are enabled without additional configuration:

| Endpoint              | Method   | Description                                      |
|-----------------------|----------|--------------------------------------------------|
| `/crowdin-files`      | `GET`    | Get a list of synced files                       |
| `/file-progress`      | `GET`    | Get file translation progress                    |
| `/integration-files`  | `GET`    | Get integration data                             |
| `/crowdin-update`     | `POST`   | Update crowdin data                              |
| `/integration-update` | `POST`   | Update integration data                          |
| `/all-jobs`           | `GET`    | Get all jobs                                     |
| `/job-info`           | `GET`    | Get job info                                     |
| `/jobs`               | `GET`    | Get job info (deprecated)                        |
| `/jobs`               | `DELETE` | Cancel job                                       |
| `/settings/schema`    | `GET`    | Get settings schema with field types and options |
| `/settings`           | `GET`    | Get application settings                         |
| `/settings`           | `POST`   | Update application settings                      |
| `/sync-settings`      | `GET`    | Get auto-sync files list                         |
| `/sync-settings`      | `POST`   | Update auto-sync files configuration             |
| `/login-fields`       | `GET`    | Get integration login form fields <sup>\*</sup>  |
| `/login`              | `POST`   | Integration login <sup>\*</sup>                  |

<sup>\*</sup> The `/login-fields` and `/login` endpoints are only available when the [Project Integration](/app-project-module/project-integration/) module is configured with a `loginForm`.