> ## 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 Endpoints

> Available REST API endpoints in the EverShop application

## Overview

This page documents all available REST API endpoints in the application. Endpoints are organized by extension.

<Note>
  All private endpoints require authentication. Public endpoints can be accessed without credentials.
</Note>

## Sample Extension

The sample extension provides example endpoints demonstrating EverShop's REST API patterns.

### Create Foo

Creates a new Foo resource.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST http://localhost:3000/foos \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Example Foo",
      "description": "This is an example foo item"
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://localhost:3000/foos', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      name: 'Example Foo',
      description: 'This is an example foo item'
    })
  });

  const data = await response.json();
  console.log(data);
  ```

  ```python Python theme={null}
  import requests

  url = 'http://localhost:3000/foos'
  headers = {'Content-Type': 'application/json'}
  payload = {
      'name': 'Example Foo',
      'description': 'This is an example foo item'
  }

  response = requests.post(url, json=payload, headers=headers)
  print(response.json())
  ```
</CodeGroup>

#### Endpoint Details

<ParamField path="method" type="string" default="POST">
  HTTP Method
</ParamField>

<ParamField path="path" type="string" default="/foos">
  Endpoint URL path
</ParamField>

<ParamField path="access" type="string" default="private">
  Requires authentication
</ParamField>

#### Request Body

<ParamField body="name" type="string" required>
  The name of the foo item

  ```json theme={null}
  "name": "Example Foo"
  ```
</ParamField>

<ParamField body="description" type="string" required>
  A description of the foo item

  ```json theme={null}
  "description": "This is an example foo item"
  ```
</ParamField>

#### Response

<ResponseField name="success" type="boolean">
  Indicates if the operation was successful
</ResponseField>

<ResponseField name="data" type="object">
  Contains the created resource

  <Expandable title="data properties">
    <ResponseField name="foo" type="object">
      The created foo object

      <Expandable title="foo properties">
        <ResponseField name="id" type="number">
          Unique identifier (timestamp-based)
        </ResponseField>

        <ResponseField name="name" type="string">
          Name of the foo item
        </ResponseField>

        <ResponseField name="description" type="string">
          Description of the foo item
        </ResponseField>
      </Expandable>
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseExample>
  ```json Success Response (201) theme={null}
  {
    "success": true,
    "data": {
      "foo": {
        "id": 1692345678901,
        "name": "Example Foo",
        "description": "This is an example foo item"
      }
    }
  }
  ```

  ```json Error Response (400) theme={null}
  {
    "error": "Name and description are required"
  }
  ```
</ResponseExample>

#### Implementation Details

<Tabs>
  <Tab title="route.json">
    ```json extensions/sample/src/api/createFoo/route.json theme={null}
    {
      "methods": ["POST"],
      "path": "/foos",
      "access": "private"
    }
    ```
  </Tab>

  <Tab title="Middleware">
    ```typescript extensions/sample/src/api/createFoo/bodyParser.ts theme={null}
    import bodyParser from 'body-parser';

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

  <Tab title="Handler">
    ```typescript extensions/sample/src/api/createFoo/[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 foo item
      const newFoo = {
        id: Date.now(),
        name,
        description
      };

      // Simulate saving to a database
      console.log('Creating new foo:', newFoo);

      // Respond with the created foo item
      response.status(201).json({
        success: true,
        data: {
          foo: newFoo
        }
      });
    };
    ```
  </Tab>
</Tabs>

## Endpoint Reference

All available endpoints organized by extension:

<CardGroup cols={1}>
  <Card title="Sample Extension" icon="flask">
    <div style={{marginTop: '1rem'}}>
      **POST** `/foos` - Create a new Foo resource

      *Status: Private (requires authentication)*
    </div>
  </Card>
</CardGroup>

## Creating Custom Endpoints

To add your own REST endpoints, follow these steps:

<Steps>
  <Step title="Create Extension">
    Create a new extension if you don't have one:

    ```bash theme={null}
    mkdir -p extensions/myExtension/src/api/myEndpoint
    ```
  </Step>

  <Step title="Define Route Configuration">
    Create a `route.json` file:

    ```json extensions/myExtension/src/api/myEndpoint/route.json theme={null}
    {
      "methods": ["GET", "POST"],
      "path": "/api/my-endpoint",
      "access": "public"
    }
    ```
  </Step>

  <Step title="Implement Handler">
    Create your endpoint handler:

    ```typescript extensions/myExtension/src/api/myEndpoint/myEndpoint.ts theme={null}
    import { EvershopRequest, EvershopResponse } from '@evershop/evershop';

    export default (request: EvershopRequest, response: EvershopResponse) => {
      response.status(200).json({
        success: true,
        data: { message: 'Hello from my endpoint' }
      });
    };
    ```
  </Step>

  <Step title="Register Extension">
    Ensure your extension is registered in `config/default.json`:

    ```json theme={null}
    {
      "system": {
        "extensions": [
          {
            "name": "myExtension",
            "resolve": "extensions/myExtension",
            "enabled": true
          }
        ]
      }
    }
    ```
  </Step>

  <Step title="Test Your Endpoint">
    Start the development server and test:

    ```bash theme={null}
    npm run dev
    curl http://localhost:3000/api/my-endpoint
    ```
  </Step>
</Steps>

## Authentication

Endpoints marked as `"access": "private"` require authentication. The authentication mechanism depends on your EverShop configuration.

<Tip>
  For development and testing, you may want to temporarily set endpoints to `"access": "public"`. Remember to change them back to `"private"` before deploying to production.
</Tip>

## HTTP Methods

Supported HTTP methods for REST endpoints:

<Tabs>
  <Tab title="GET">
    Use for retrieving resources:

    ```json theme={null}
    {
      "methods": ["GET"],
      "path": "/api/items/:id",
      "access": "public"
    }
    ```
  </Tab>

  <Tab title="POST">
    Use for creating new resources:

    ```json theme={null}
    {
      "methods": ["POST"],
      "path": "/api/items",
      "access": "private"
    }
    ```
  </Tab>

  <Tab title="PUT">
    Use for full updates of existing resources:

    ```json theme={null}
    {
      "methods": ["PUT"],
      "path": "/api/items/:id",
      "access": "private"
    }
    ```
  </Tab>

  <Tab title="PATCH">
    Use for partial updates of existing resources:

    ```json theme={null}
    {
      "methods": ["PATCH"],
      "path": "/api/items/:id",
      "access": "private"
    }
    ```
  </Tab>

  <Tab title="DELETE">
    Use for deleting resources:

    ```json theme={null}
    {
      "methods": ["DELETE"],
      "path": "/api/items/:id",
      "access": "private"
    }
    ```
  </Tab>

  <Tab title="Multiple Methods">
    Support multiple methods on the same endpoint:

    ```json theme={null}
    {
      "methods": ["GET", "POST", "PUT", "DELETE"],
      "path": "/api/items",
      "access": "private"
    }
    ```

    Handle different methods in your handler:

    ```typescript theme={null}
    export default (request: EvershopRequest, response: EvershopResponse) => {
      switch (request.method) {
        case 'GET':
          // Handle GET
          break;
        case 'POST':
          // Handle POST
          break;
        case 'PUT':
          // Handle PUT
          break;
        case 'DELETE':
          // Handle DELETE
          break;
      }
    };
    ```
  </Tab>
</Tabs>

## Error Handling

Best practices for error handling in REST endpoints:

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

  ```typescript Not Found theme={null}
  // 404 Not Found
  const item = findItem(id);
  if (!item) {
    return response
      .status(404)
      .json({ error: 'Item not found' });
  }
  ```

  ```typescript Unauthorized theme={null}
  // 401 Unauthorized
  if (!request.user) {
    return response
      .status(401)
      .json({ error: 'Authentication required' });
  }
  ```

  ```typescript Server Errors theme={null}
  // 500 Internal Server Error
  try {
    // Your logic
  } catch (error) {
    console.error('Error processing request:', error);
    return response
      .status(500)
      .json({ error: 'Internal server error' });
  }
  ```
</CodeGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="REST API Overview" icon="book" href="/api/rest/overview">
    Learn about REST API conventions and best practices
  </Card>

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

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

  <Card title="Extensions" icon="puzzle-piece" href="/extensions/overview">
    Learn about available extensions
  </Card>
</CardGroup>
