---
hide:
  - toc
---

# 🌐 REST API

Flock allows you to easily expose your configured agents and workflows as a RESTful API, making them accessible to other services, web frontends, or remote clients. This is achieved using FastAPI under the hood.

## Starting the API Server

To start the API server, simply call the `start_api()` method on your configured `Flock` instance within your Python script:

```python
from flock.core import Flock, FlockFactory

# --- Configure your Flock and Agents ---
flock = Flock(name="My API Flock", model="openai/gpt-4o")

analyzer_agent = FlockFactory.create_default_agent(
    name="text_analyzer",
    input="text: str",
    output="sentiment: str, keywords: list[str]"
)
flock.add_agent(analyzer_agent)
# ... add more agents ...

# --- Start the API Server ---
if __name__ == "__main__":
    # This will start a Uvicorn server (blocking call)
    flock.start_api(
        host="127.0.0.1", # Host to bind to (0.0.0.0 for external access)
        port=8344,       # Port to listen on
        server_name="My Flock Service API" # Optional title for docs
        # create_ui=False # Set to True to also enable the Web UI
    )
```

Running this script will start a web server listening on http://127.0.0.1:8344.

## Key API Endpoints

The server automatically provides the following endpoints:

### POST /run/flock: 

Executes a single agent workflow run.

**Request Body (JSON)**: FlockAPIRequest

```json
{
  "agent_name": "text_analyzer",
  "inputs": {
    "text": "Flock makes building agents easy and fun!"
  },
  "async_run": false
}
```

- **agent_name** (string, required): The name of the agent to start the workflow with.
- **inputs** (object, optional): Input data for the starting agent.
- **async_run** (boolean, optional, default: false): If true, the API returns immediately with a run_id and processes the request in the background. If false, the API waits for the run to complete before responding.

**Response Body (JSON)**: FlockAPIResponse

- If async_run=true or run is in progress: Contains run_id and status ("starting" or "running").
- If async_run=false and run completes: Contains run_id, status ("completed" or "failed"), result (the output data), started_at, completed_at, and potentially error.

### POST /run/batch: 

Executes a batch processing job.

**Request Body (JSON)**: FlockBatchRequest (See API reference or flock.core.api.models for full details). Allows specifying batch_inputs (list of dicts or CSV path string), agent_name, static_inputs, parallel execution options, etc.

**Response Body (JSON)**: FlockBatchResponse. Batch runs are always asynchronous. Returns batch_id and status ("starting"). Use the /batch/{batch_id} endpoint to track progress and get results.

### GET /run/{run_id}: 

Retrieves the status and result of a specific workflow run initiated via POST /run/flock.

**Response Body (JSON)**: FlockAPIResponse

### GET /batch/{batch_id}: 

Retrieves the status, progress, and results of a specific batch run initiated via POST /run/batch.

**Response Body (JSON)**: FlockBatchResponse (Includes total_items, completed_items, progress_percentage, and results list).

### GET /agents: 

Lists all agents registered within the running Flock instance.

**Response Body (JSON)**:

```json
{
  "agents": [
    {"name": "agent_name_1", "description": "Description 1"},
    {"name": "agent_name_2", "description": "Description 2"}
  ]
}
```

## Example Interaction (curl)

```bash
# Start a synchronous run
curl -X POST http://127.0.0.1:8344/run/flock -H "Content-Type: application/json" -d '{
  "agent_name": "text_analyzer",
  "inputs": {
    "text": "This is great!"
  }
}'

# Start an asynchronous run
curl -X POST http://127.0.0.1:8344/run/flock -H "Content-Type: application/json" -d '{
  "agent_name": "text_analyzer",
  "inputs": {
    "text": "This will run in the background."
  },
  "async_run": true
}'
# Response will include a run_id, e.g.: {"run_id": "...", "status": "running", ...}

# Check the status of the asynchronous run (replace {run_id} with the actual ID)
curl http://127.0.0.1:8344/run/{run_id}
```

## API Documentation

When the API server is running, you can access interactive documentation generated by FastAPI:

- **Swagger UI**: http://<host>:<port>/docs
- **ReDoc**: http://<host>:<port>/redoc

These interfaces allow you to explore endpoints, view request/response schemas, and even try out API calls directly from your browser.



