"
Enable Dark Mode!
how-to-create-modern-rest-apis-with-fastapi-odoo.jpg
By: Risvana AR

How to Create Modern REST APIs With FastAPI & Odoo

Technical

The modern Rest API with the help of FastAPI is a way to help developers who need to quickly and efficiently expose Odoo databases to third-party systems in a secure, stable, and future-proof manner. The fast rest  APIs are using the fast API libraries and the Odoo backend APIs. FastAPI is one of the Best Python libraries for creating REST APIs with automatic OpenAPI schema, documentation generation, and automatic parameter validation.

It is a very efficient way to create modern rest APIs on top of Odoo using the fast API framework. The Rest API with FastAPI is worked on the basis of an open API mechanism. A web framework leveraging standard python type annotations and pydantic data structure. The compact codes are written in the main.py, run with the uvicorn, and tested with corresponding docs.

First, create a fast API object:

app = FastAPI(title="FastAPI with Update Customers")

The object is an ASGI application. It is the interior probability standard in the python asynchronous and synchronous application.

Creating a barcode object:

class Barcode(BaseModel):
barcode: str

Then create a partner object :

class Partner(BaseModel):
partner_id: int
name: str
email: str
zip: int

Also, we can create events:

@app.on_event("startup")
def set_default_executor() -> None:
_logger.info("Startup 1")
from concurrent.futures import ThreadPoolExecutor
import asyncio
loop = asyncio.get_running_loop()
# Tune this according to your requirements !
loop.set_default_executor(ThreadPoolExecutor(max_workers=2))
@app.on_event("startup")
def initialize_odoo() -> None:
_logger.info("Startup")
# Read Odoo config from $ODOO_RC.
odoo.tools.config.parse_config([])

The python type annotation does not influence the behavior of the interpreter, but it can be used by any kind of tool like checkers to validate the correctness of the code, and the id is to provide type completion. It performs validation and data conversion.

Declaration of the endpoints using decorators:

We use http get, post, patch, etc., and create a response for the particular method.

 This decorator is only used for testing the endpoint.

@app.get("/test", response_model=str)
def test_call():
return "success"

Authentication endpoint:

@app.get("/Authentication/ApiToken")
async def token(username: str, password: str, env: Environment = Depends(odoo_env)):
u_id = env['res.users'].authenticate(env['res.users'], username,
                                      password, '')
if not u_id:
    return {"Status": "Error", "Message": "Incorrect username or password"}
assert password
env.cr.execute(
    "SELECT COALESCE(password, '') FROM res_users WHERE id=%s" % u_id
)
[hashed] = env.cr.fetchone()
valid, replacement = passlib.context.CryptContext(
    ['pbkdf2_sha512', 'plaintext'],
    deprecated=['plaintext'],
) \
    .verify_and_update(password, hashed)
if not valid:
    return {"Status": "Error", "Message": "Incorrect username or password"}
if valid:
    api_authentication_token = env['res.users'].browse(u_id)
    return {"status": "success",
            "Auth_token": api_authentication_token.id
            }

In the authentication, we can declare the get parameter and the function defined as the token by declaring the username, password, and environment for the Odoo functioning.

First, we have to search the users from the res.user model and authenticate with the res.user values. If not in the value, it will generate an error message. Otherwise the password validation method. After validating the id, it will browse with the res.users and return the status and token for the method.

Creating endpoints  for searching the partner barcode: 

@app.get("/partner_id")
async def token(barcode: str, request: Request,
            env: Environment = Depends(odoo_env)):
partner_barcode = env['res.partner'].sudo().search(
    [('barcode', '=', barcode)])
if partner_barcode:
    return {"partner_id": partner_barcode.id}
else:
    return {"Status": "Error",
            "Message": "No partner id found for barcode %s"
                        % barcode}

That's all about the Fast API used in the REST API schema. The method for creating endpoints and events is used to communicate the rest of the APIs. This method learns how to safely and efficiently make the most of the internal API outside of the standard Odoo server. Compared to other approaches that use XML-RPC, JSON-RPC, or community modules like base_rest or graphql_base it is a better and easily created method. We can quickly and efficiently migrate Odoo databases to third-party systems in a secure, resilient, and future-proof manner.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment

 


whatsapp
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

London

Cybrosys Limited
Alpha House,
100 Borough High Street, London,
SE1 1LB, United Kingdom

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message