Skip to main content

FastAPI integration for Odoo via XML-RPC

Project description

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 Python 3.8+ License: MIT

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

pip install fastodoo

Initialize a New Project

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:
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')}
  1. Configure your environment (.env file):
ODOO_URL=https://your-odoo-server.com
ODOO_DB=your_database_name
ODOO_USERNAME=your_username
ODOO_PASSWORD=your_password
  1. Run your application:
uvicorn main:app --reload

Core Concepts

ORM-like Interface

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

# 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

# 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

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

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

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:

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

# 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:
git clone https://github.com/your-username/fastodoo.git
cd fastodoo
  1. Create virtual environment:
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. Install dependencies:
pip install -e ".[dev]"
  1. Run linting:
ruff check
  1. Start development server:
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 file for details.

Contributing

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

Support


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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastodoo-0.1.0.tar.gz (87.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastodoo-0.1.0-py3-none-any.whl (22.6 kB view details)

Uploaded Python 3

File details

Details for the file fastodoo-0.1.0.tar.gz.

File metadata

  • Download URL: fastodoo-0.1.0.tar.gz
  • Upload date:
  • Size: 87.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for fastodoo-0.1.0.tar.gz
Algorithm Hash digest
SHA256 9f1a6ea8a2ae03f456a6a382eeceecbc21348d29b869aec70dfe5d9bd7cb6270
MD5 4f2e094ac5ca14a132dd64aa163a551b
BLAKE2b-256 5e2923a8b37ed3c056957fa9a332a48d4b4022e6026d7363a0e7169032ceff80

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastodoo-0.1.0.tar.gz:

Publisher: publish.yml on aidooit/fastodoo

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fastodoo-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: fastodoo-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 22.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for fastodoo-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 90e4bae7b7e1ef4082f04603531ad6199c4de32a5a0ff2dec029fe5b220702d6
MD5 abe47f1f95961bd7b9d7e020b6fce731
BLAKE2b-256 11c0da36bca4483b187e95b6b20ade8826cf17614445dad177a8ad5d1fcb20e7

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastodoo-0.1.0-py3-none-any.whl:

Publisher: publish.yml on aidooit/fastodoo

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page