Metadata-Version: 2.4
Name: fastodoo
Version: 0.1.0
Summary: FastAPI integration for Odoo via XML-RPC
Project-URL: Homepage, https://github.com/aidooit/fastodoo
Project-URL: Repository, https://github.com/aidooit/fastodoo.git
Project-URL: Documentation, https://github.com/aidooit/fastodoo#readme
Project-URL: Issues, https://github.com/aidooit/fastodoo/issues
Author: FastOdoo Team
License: MIT License
        
        Copyright (c) 2025 FastOdoo
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: api,erp,fastapi,odoo,xmlrpc
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.10
Requires-Dist: fastapi>=0.115.0
Requires-Dist: pydantic-settings>=2.6.0
Requires-Dist: requests>=2.32.0
Requires-Dist: rich>=13.9.0
Requires-Dist: typer>=0.15.0
Requires-Dist: uvicorn[standard]>=0.32.0
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'dev'
Requires-Dist: pytest>=8.3.0; extra == 'dev'
Requires-Dist: ruff>=0.11.0; extra == 'dev'
Requires-Dist: ty; extra == 'dev'
Requires-Dist: types-requests; extra == 'dev'
Description-Content-Type: text/markdown

# FastOdoo

**FastAPI integration for Odoo via XML-RPC**

FastOdoo is a Python library that provides a FastAPI-based REST interface for Odoo ERP systems via XML-RPC. It acts as a bridge between web applications and Odoo, offering ORM-like functionality for Python developers.

[![Lint](https://github.com/your-username/fastodoo/workflows/Lint/badge.svg)](https://github.com/your-username/fastodoo/actions)
![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)
![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)

## Features

- 🚀 **FastAPI Integration**: Ready-to-use REST API endpoints for common Odoo operations
- 🎯 **ORM-like Interface**: Familiar `env['model.name'].search()` syntax similar to Odoo's Python ORM
- 🔒 **Secure Credentials**: Built-in credential masking and flexible authentication providers
- ⚡ **Performance Optimized**: Intelligent caching with LRU cache and TTL support
- 🔗 **Relation Handling**: Automatic conversion of relational fields to RecordSet objects
- 🛠️ **CLI Tools**: Built-in command-line interface for project initialization
- 📋 **Type Safety**: Full type annotations and Pydantic integration
- 🔍 **Extensible**: Plugin-based credential providers (AWS Secrets Manager, etc.)

## Quick Start

### Installation

```bash
pip install fastodoo
```

### Initialize a New Project

```bash
fastodoo init
```

This will create a new FastAPI application with FastOdoo integration and guide you through the setup process.

### Manual Setup

1. **Create your FastAPI application:**

```python
from fastapi import FastAPI, Depends
from fastodoo import Odoo, Environment, odoo_router

app = FastAPI()

# Include pre-built CRUD endpoints (optional)
app.include_router(odoo_router, prefix="/odoo", tags=["Odoo CRUD"])

# Initialize Odoo connection
odoo = Odoo(version=18)  # Specify your Odoo version

def get_env() -> Environment:
    return odoo.env

@app.get("/contacts")
def get_contacts(env: Environment = Depends(get_env)):
    contacts = env['res.partner'].search([], limit=5)
    return {"contacts": contacts.mapped('name')}
```

2. **Configure your environment (.env file):**

```env
ODOO_URL=https://your-odoo-server.com
ODOO_DB=your_database_name
ODOO_USERNAME=your_username
ODOO_PASSWORD=your_password
```

3. **Run your application:**

```bash
uvicorn main:app --reload
```

## Core Concepts

### ORM-like Interface

FastOdoo provides an ORM-like interface similar to Odoo's native Python ORM:

```python
# Access models through environment
env = odoo.env
partners = env['res.partner'].search([('is_company', '=', True)])

# ORM-like field access with automatic relation handling
for partner in partners:
    print(partner.name)  # Direct field access
    print(partner.parent_id.name)  # Many2one relation access
    
# Use mapped() for bulk operations
names = partners.mapped('name')
parent_names = partners.mapped('parent_id.name')
```

### CRUD Operations

```python
# Create records
partner_id = env['res.partner'].create({
    'name': 'New Contact',
    'email': 'contact@example.com'
})

# Search and read
partners = env['res.partner'].search([('is_company', '=', True)], limit=10)
data = env['res.partner'].search_read([('active', '=', True)], ['name', 'email'])

# Update records
partner.write({'name': 'Updated Name'})

# Delete records
partner.unlink()
```

### RecordSet Features

```python
partners = env['res.partner'].browse([1, 2, 3, 4, 5])

# Length and iteration
print(len(partners))  # 5
for partner in partners:
    print(partner.name)

# Slicing and indexing
first_partner = partners[0]
first_three = partners[:3]

# Field access and relations
names = partners.mapped('name')
countries = partners.mapped('country_id.name')  # Traversing relations
```

## Built-in REST API

FastOdoo includes pre-built REST endpoints for common operations:

- `GET /odoo/info` - Get Odoo server information
- `GET /odoo/search_read/{model_name}` - Search and read records
- `GET /odoo/browse/{model_name}` - Browse specific records by ID
- `POST /odoo/create/{model_name}` - Create new records
- `PUT /odoo/write/{model_name}` - Update existing records
- `DELETE /odoo/delete/{model_name}` - Delete records

### API Examples

```bash
# Get server info
curl http://localhost:8000/odoo/info

# Search partners
curl "http://localhost:8000/odoo/search_read/res.partner?fields=name,email&limit=5"

# Create a new partner
curl -X POST "http://localhost:8000/odoo/create/res.partner" \
  -H "Content-Type: application/json" \
  -d '{"name": "New Partner", "email": "new@example.com"}'
```

## Advanced Configuration

### Custom Credentials Provider

For production environments, you can implement custom credential providers:

```python
from fastodoo.auth import CredentialsProvider, SecureCredential
import boto3

class AWSSecretsCredentialsProvider(CredentialsProvider):
    def __init__(self, secret_name: str):
        self.secret_name = secret_name
        self.client = boto3.client('secretsmanager')
    
    def get_credentials(self) -> Dict[str, str]:
        secret = self.client.get_secret_value(SecretId=self.secret_name)
        data = json.loads(secret['SecretString'])
        
        return {
            'url': data['odoo_url'],
            'db': data['odoo_db'],
            'username': data['odoo_username'],
            'password': SecureCredential(data['odoo_password'])
        }

# Use custom provider
odoo = Odoo(version=18, credentials_provider=AWSSecretsCredentialsProvider("odoo-creds"))
```

### Caching Configuration

FastOdoo includes intelligent caching for better performance:

```python
# Caching is automatically handled
partners = env['res.partner'].search([('is_company', '=', True)])
# Subsequent calls with same parameters will use cache

# Cache is invalidated automatically on write operations
partner.write({'name': 'Updated'})  # Cache cleared for this record
```

## CLI Commands

FastOdoo includes a powerful CLI for project management:

```bash
# Initialize new project with interactive prompts
fastodoo init

# Initialize with specific options
fastodoo init --port 8080 --template --output my_app.py

# Show version
fastodoo version

# Get help
fastodoo --help
```

## Project Structure

```
fastodoo/
├── fastodoo/
│   ├── __init__.py          # Main exports and version
│   ├── odoo.py             # Core Odoo client and ORM classes
│   ├── api.py              # XML-RPC API mixins
│   ├── router.py           # FastAPI router with CRUD endpoints
│   ├── auth.py             # Authentication and credentials handling
│   ├── settings.py         # Pydantic settings configuration
│   ├── exceptions.py       # Custom exceptions
│   ├── cli.py              # Command-line interface
│   └── template.py         # FastAPI app template
├── pyproject.toml          # Project configuration and dependencies
├── README.md               # This file
└── LICENSE                 # MIT License
```

## Requirements

- **Python**: 3.8+
- **Odoo**: 14.0+ (tested with versions 14-18)
- **Dependencies**:
  - `fastapi` - Web framework
  - `uvicorn[standard]` - ASGI server
  - `pydantic-settings` - Configuration management
  - `typer[all]` - CLI framework
  - `rich` - Terminal formatting

## Development Setup

1. **Clone the repository:**
```bash
git clone https://github.com/your-username/fastodoo.git
cd fastodoo
```

2. **Create virtual environment:**
```bash
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
```

3. **Install dependencies:**
```bash
pip install -e ".[dev]"
```

4. **Run linting:**
```bash
ruff check
```

5. **Start development server:**
```bash
python main.py
```

## Important Notes

### Odoo User Configuration

- Create a user in your Odoo instance **without 2FA enabled**. Two-factor authentication will cause XML-RPC authentication to fail.
- Ensure the user has appropriate permissions for the models you plan to access.

### Security Considerations

- Always use HTTPS in production
- Store credentials securely (use credential providers, not plain text)
- FastOdoo automatically masks passwords in logs and debug output
- Validate and sanitize all user inputs in your endpoints

### Performance Tips

- Use `search_read()` instead of `search()` + `read()` when possible
- Leverage the built-in caching system
- Use `mapped()` for bulk field access
- Set appropriate limits on search operations

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## Support

- **Issues**: [GitHub Issues](https://github.com/your-username/fastodoo/issues)
- **Documentation**: [GitHub README](https://github.com/your-username/fastodoo#readme)

---

**FastOdoo** - Bridge the gap between modern web development and Odoo ERP systems.