> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/Antony-Figueroa/my-evershop-app/llms.txt
> Use this file to discover all available pages before exploring further.

# REST API Overview

> Learn about EverShop REST API architecture, conventions, and best practices

## Introduction

EverShop's REST API allows you to create custom endpoints for your e-commerce application. The API follows a modular architecture where endpoints are defined within extensions using a declarative routing system.

## API Architecture

REST endpoints in EverShop are organized within extensions and follow a specific directory structure:

```
extensions/[name]/src/api/[endpoint]/
├── route.json                    # Route configuration
├── [middleware]endpoint.ts       # Middleware handlers (optional)
└── endpoint.ts                   # Main endpoint handler
```

### Key Components

<CardGroup cols={2}>
  <Card title="Route Configuration" icon="route">
    Declarative JSON file defining HTTP methods, path, and access control
  </Card>

  <Card title="Middleware Chain" icon="link">
    Optional middleware functions that run before the main endpoint handler
  </Card>

  <Card title="Endpoint Handler" icon="code">
    Main function that processes the request and returns a response
  </Card>

  <Card title="TypeScript Support" icon="typescript">
    Full TypeScript support with EverShop request/response types
  </Card>
</CardGroup>

## Route Configuration

Every endpoint requires a `route.json` file that defines its routing configuration:

```json route.json theme={null}
{
  "methods": ["POST"],
  "path": "/foos",
  "access": "private"
}
```

### Configuration Fields

<ParamField path="methods" type="string[]" required>
  Array of allowed HTTP methods. Supported values: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`

  ```json theme={null}
  "methods": ["GET", "POST"]
  ```
</ParamField>

<ParamField path="path" type="string" required>
  The URL path where the endpoint will be accessible. Can include path parameters.

  ```json theme={null}
  "path": "/api/products/:id"
  ```
</ParamField>

<ParamField path="access" type="string" required>
  Access control level for the endpoint.

  * `public` - Accessible without authentication
  * `private` - Requires authentication

  ```json theme={null}
  "access": "private"
  ```
</ParamField>

## Request/Response Types

EverShop provides TypeScript types for handling HTTP requests and responses:

```typescript theme={null}
import { EvershopRequest, EvershopResponse } from '@evershop/evershop';

export default (
  request: EvershopRequest,
  response: EvershopResponse,
  next
) => {
  // Your endpoint logic
};
```

### EvershopRequest

Extends Express.js Request with additional properties:

<ResponseField name="body" type="object">
  Parsed request body (requires bodyParser middleware)
</ResponseField>

<ResponseField name="params" type="object">
  URL path parameters
</ResponseField>

<ResponseField name="query" type="object">
  URL query string parameters
</ResponseField>

<ResponseField name="headers" type="object">
  HTTP request headers
</ResponseField>

### EvershopResponse

Extends Express.js Response with standard methods:

<ResponseField name="status(code)" type="function">
  Sets the HTTP status code
</ResponseField>

<ResponseField name="json(data)" type="function">
  Sends a JSON response
</ResponseField>

<ResponseField name="send(data)" type="function">
  Sends a generic response
</ResponseField>

## Middleware Pattern

Middleware functions run before the main endpoint handler. They are named using the pattern `[middlewareName]endpoint.ts`:

```typescript bodyParser.ts theme={null}
import bodyParser from 'body-parser';

export default (request, response, next) => {
  bodyParser.json({ inflate: false })(request, response, next);
};
```

```typescript [bodyParser]createFoo.ts theme={null}
import { EvershopRequest, EvershopResponse } from '@evershop/evershop';

export default (request: EvershopRequest, response: EvershopResponse, next) => {
  const { name, description } = request.body;

  if (!name || !description) {
    return response
      .status(400)
      .json({ error: 'Name and description are required' });
  }

  // Create the new resource
  const newFoo = {
    id: Date.now(),
    name,
    description
  };

  response.status(201).json({
    success: true,
    data: { foo: newFoo }
  });
};
```

### Middleware Execution Order

Middleware files are executed in alphabetical order based on the middleware name in square brackets:

1. `[auth]endpoint.ts` - Authentication
2. `[bodyParser]endpoint.ts` - Body parsing
3. `[validation]endpoint.ts` - Validation
4. `endpoint.ts` - Main handler

## Response Conventions

### Success Response

For successful operations, return a structured JSON response:

```json theme={null}
{
  "success": true,
  "data": {
    "foo": {
      "id": 1692345678901,
      "name": "Example Foo",
      "description": "This is an example"
    }
  }
}
```

### Error Response

For errors, include descriptive error messages:

```json theme={null}
{
  "error": "Name and description are required"
}
```

### HTTP Status Codes

Follow standard HTTP status code conventions:

| Status Code | Use Case                               |
| ----------- | -------------------------------------- |
| 200         | Successful GET, PUT, or PATCH          |
| 201         | Successful POST (resource created)     |
| 204         | Successful DELETE (no content)         |
| 400         | Bad Request (validation error)         |
| 401         | Unauthorized (authentication required) |
| 403         | Forbidden (insufficient permissions)   |
| 404         | Not Found                              |
| 500         | Internal Server Error                  |

## Best Practices

<AccordionGroup>
  <Accordion title="Use TypeScript">
    Always use TypeScript for type safety and better IDE support:

    ```typescript theme={null}
    interface FooInput {
      name: string;
      description: string;
    }

    export default (request: EvershopRequest, response: EvershopResponse) => {
      const { name, description } = request.body as FooInput;
      // ...
    };
    ```
  </Accordion>

  <Accordion title="Validate Input">
    Always validate request data before processing:

    ```typescript theme={null}
    if (!name || !description) {
      return response
        .status(400)
        .json({ error: 'Name and description are required' });
    }
    ```
  </Accordion>

  <Accordion title="Use Appropriate Status Codes">
    Return the correct HTTP status code for each scenario:

    * 201 for resource creation
    * 400 for validation errors
    * 404 for not found
  </Accordion>

  <Accordion title="Structure Responses Consistently">
    Use a consistent response format across all endpoints:

    ```typescript theme={null}
    // Success
    response.status(200).json({
      success: true,
      data: { /* payload */ }
    });

    // Error
    response.status(400).json({
      error: "Error message"
    });
    ```
  </Accordion>

  <Accordion title="Separate Middleware Logic">
    Keep concerns separated by using dedicated middleware files:

    * Authentication in `[auth]endpoint.ts`
    * Validation in `[validation]endpoint.ts`
    * Body parsing in `[bodyParser]endpoint.ts`
  </Accordion>
</AccordionGroup>

## Example: Complete Endpoint

Here's a complete example of creating a REST endpoint:

<Steps>
  <Step title="Create Directory Structure">
    ```bash theme={null}
    mkdir -p extensions/myExtension/src/api/createFoo
    cd extensions/myExtension/src/api/createFoo
    ```
  </Step>

  <Step title="Create route.json">
    ```json route.json theme={null}
    {
      "methods": ["POST"],
      "path": "/foos",
      "access": "private"
    }
    ```
  </Step>

  <Step title="Create Middleware (optional)">
    ```typescript bodyParser.ts theme={null}
    import bodyParser from 'body-parser';

    export default (request, response, next) => {
      bodyParser.json({ inflate: false })(request, response, next);
    };
    ```
  </Step>

  <Step title="Create Endpoint Handler">
    ```typescript [bodyParser]createFoo.ts theme={null}
    import { EvershopRequest, EvershopResponse } from '@evershop/evershop';

    export default (request: EvershopRequest, response: EvershopResponse) => {
      const { name, description } = request.body;

      if (!name || !description) {
        return response
          .status(400)
          .json({ error: 'Name and description are required' });
      }

      const newFoo = {
        id: Date.now(),
        name,
        description
      };

      console.log('Creating new foo:', newFoo);

      response.status(201).json({
        success: true,
        data: { foo: newFoo }
      });
    };
    ```
  </Step>

  <Step title="Test the Endpoint">
    ```bash theme={null}
    curl -X POST http://localhost:3000/foos \
      -H "Content-Type: application/json" \
      -d '{"name": "Test Foo", "description": "A test item"}'
    ```
  </Step>
</Steps>

## Next Steps

<CardGroup cols={2}>
  <Card title="View Endpoints" icon="list" href="/api/rest/endpoints">
    Browse available REST endpoints in this application
  </Card>

  <Card title="GraphQL API" icon="brackets-curly" href="/api/graphql/overview">
    Learn about the GraphQL API as an alternative
  </Card>

  <Card title="Creating Extensions" icon="puzzle-piece" href="/guides/creating-extensions">
    Learn how to create custom extensions
  </Card>

  <Card title="API Endpoints Guide" icon="code" href="/guides/api-endpoints">
    Step-by-step guide to creating API endpoints
  </Card>
</CardGroup>
