diff --git a/fastapi/README.rst b/fastapi/README.rst new file mode 100644 index 000000000..e7b954503 --- /dev/null +++ b/fastapi/README.rst @@ -0,0 +1,1675 @@ +============ +Odoo FastAPI +============ + +.. + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! This file is generated by oca-gen-addon-readme !! + !! changes will be overwritten. !! + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! source digest: sha256:833b38a7daeeb3a130e9ad1725cad278b183489b8c241dedd0cdb1346157f89f + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png + :target: https://odoo-community.org/page/development-status + :alt: Beta +.. |badge2| image:: https://img.shields.io/badge/licence-LGPL--3-blue.png + :target: http://www.gnu.org/licenses/lgpl-3.0-standalone.html + :alt: License: LGPL-3 +.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Frest--framework-lightgray.png?logo=github + :target: https://github.com/OCA/rest-framework/tree/18.0/fastapi + :alt: OCA/rest-framework +.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png + :target: https://translation.odoo-community.org/projects/rest-framework-18-0/rest-framework-18-0-fastapi + :alt: Translate me on Weblate +.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png + :target: https://runboat.odoo-community.org/builds?repo=OCA/rest-framework&target_branch=18.0 + :alt: Try me on Runboat + +|badge1| |badge2| |badge3| |badge4| |badge5| + +This addon provides the basis to smoothly integrate the +`FastAPI `__ framework into Odoo. + +This integration allows you to use all the goodies from +`FastAPI `__ to build custom APIs for +your Odoo server based on standard Python type hints. + +**What is building an API?** + +An API is a set of functions that can be called from the outside world. +The goal of an API is to provide a way to interact with your application +from the outside world without having to know how it works internally. A +common mistake when you are building an API is to expose all the +internal functions of your application and therefore create a tight +coupling between the outside world and your internal datamodel and +business logic. This is not a good idea because it makes it very hard to +change your internal datamodel and business logic without breaking the +outside world. + +When you are building an API, you define a contract between the outside +world and your application. This contract is defined by the functions +that you expose and the parameters that you accept. This contract is the +API. When you change your internal datamodel and business logic, you can +still keep the same API contract and therefore you don't break the +outside world. Even if you change your implementation, as long as you +keep the same API contract, the outside world will still work. This is +the beauty of an API and this is why it is so important to design a good +API. + +A good API is designed to be stable and to be easy to use. It's designed +to provide high-level functions related to a specific use case. It's +designed to be easy to use by hiding the complexity of the internal +datamodel and business logic. A common mistake when you are building an +API is to expose all the internal functions of your application and let +the oustide world deal with the complexity of your internal datamodel +and business logic. Don't forget that on a transactional point of view, +each call to an API function is a transaction. This means that if a +specific use case requires multiple calls to your API, you should +provide a single function that does all the work in a single +transaction. This why APIs methods are called high-level and atomic +functions. + +**Table of contents** + +.. contents:: + :local: + +Usage +===== + +What's building an API with fastapi? +------------------------------------ + +FastAPI is a modern, fast (high-performance), web framework for building +APIs with Python 3.7+ based on standard Python type hints. This addons +let's you keep advantage of the fastapi framework and use it with Odoo. + +Before you start, we must define some terms: + +- **App**: A FastAPI app is a collection of routes, dependencies, and + other components that can be used to build a web application. +- **Router**: A router is a collection of routes that can be mounted in + an app. +- **Route**: A route is a mapping between an HTTP method and a path, and + defines what should happen when the user requests that path. +- **Dependency**: A dependency is a callable that can be used to get + some information from the user request, or to perform some actions + before the request handler is called. +- **Request**: A request is an object that contains all the information + sent by the user's browser as part of an HTTP request. +- **Response**: A response is an object that contains all the + information that the user's browser needs to build the result page. +- **Handler**: A handler is a function that takes a request and returns + a response. +- **Middleware**: A middleware is a function that takes a request and a + handler, and returns a response. + +The FastAPI framework is based on the following principles: + +- **Fast**: Very high performance, on par with NodeJS and Go (thanks to + Starlette and Pydantic). [One of the fastest Python frameworks + available] +- **Fast to code**: Increase the speed to develop features by about 200% + to 300%. +- **Fewer bugs**: Reduce about 40% of human (developer) induced errors. +- **Intuitive**: Great editor support. Completion everywhere. Less time + debugging. +- **Easy**: Designed to be easy to use and learn. Less time reading + docs. +- **Short**: Minimize code duplication. Multiple features from each + parameter declaration. Fewer bugs. +- **Robust**: Get production-ready code. With automatic interactive + documentation. +- **Standards-based**: Based on (and fully compatible with) the open + standards for APIs: OpenAPI (previously known as Swagger) and JSON + Schema. +- **Open Source**: FastAPI is fully open-source, under the MIT license. + +The first step is to install the fastapi addon. You can do it with the +following command: + + $ pip install odoo-addon-fastapi + +Once the addon is installed, you can start building your API. The first +thing you need to do is to create a new addon that depends on 'fastapi'. +For example, let's create an addon called *my_demo_api*. + +Then, you need to declare your app by defining a model that inherits +from 'fastapi.endpoint' and add your app name into the app field. For +example: + +.. code:: python + + from odoo import fields, models + + class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + app: str = fields.Selection( + selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"} + ) + +The **'fastapi.endpoint'** model is the base model for all the +endpoints. An endpoint instance is the mount point for a fastapi app +into Odoo. When you create a new endpoint, you can define the app that +you want to mount in the **'app'** field and the path where you want to +mount it in the **'path'** field. + +figure:: static/description/endpoint_create.png + + FastAPI Endpoint + +Thanks to the **'fastapi.endpoint'** model, you can create as many +endpoints as you want and mount as many apps as you want in each +endpoint. The endpoint is also the place where you can define +configuration parameters for your app. A typical example is the +authentication method that you want to use for your app when accessed at +the endpoint path. + +Now, you can create your first router. For that, you need to define a +global variable into your fastapi_endpoint module called for example +'demo_api_router' + +.. code:: python + + from fastapi import APIRouter + from odoo import fields, models + + class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + app: str = fields.Selection( + selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"} + ) + + # create a router + demo_api_router = APIRouter() + +To make your router available to your app, you need to add it to the +list of routers returned by the **\_get_fastapi_routers** method of your +fastapi_endpoint model. + +.. code:: python + + from fastapi import APIRouter + from odoo import api, fields, models + + class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + app: str = fields.Selection( + selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"} + ) + + def _get_fastapi_routers(self): + if self.app == "demo": + return [demo_api_router] + return super()._get_fastapi_routers() + + # create a router + demo_api_router = APIRouter() + +Now, you can start adding routes to your router. For example, let's add +a route that returns a list of partners. + +.. code:: python + + from typing import Annotated + + from fastapi import APIRouter + from pydantic import BaseModel + + from odoo import api, fields, models + from odoo.api import Environment + + from odoo.addons.fastapi.dependencies import odoo_env + + class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + app: str = fields.Selection( + selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"} + ) + + def _get_fastapi_routers(self): + if self.app == "demo": + return [demo_api_router] + return super()._get_fastapi_routers() + + # create a router + demo_api_router = APIRouter() + + class PartnerInfo(BaseModel): + name: str + email: str + + @demo_api_router.get("/partners", response_model=list[PartnerInfo]) + def get_partners(env: Annotated[Environment, Depends(odoo_env)]) -> list[PartnerInfo]: + return [ + PartnerInfo(name=partner.name, email=partner.email) + for partner in env["res.partner"].search([]) + ] + +Now, you can start your Odoo server, install your addon and create a new +endpoint instance for your app. Once it's done click on the docs url to +access the interactive documentation of your app. + +Before trying to test your app, you need to define on the endpoint +instance the user that will be used to run the app. You can do it by +setting the **'user_id'** field. This information is the most important +one because it's the basis for the security of your app. The user that +you define in the endpoint instance will be used to run the app and to +access the database. This means that the user will be able to access all +the data that he has access to in Odoo. To ensure the security of your +app, you should create a new user that will be used only to run your app +and that will have no access to the database. + +.. code:: xml + + + My Demo Endpoint User + my_demo_app_user + + + +At the same time you should create a new group that will be used to +define the access rights of the user that will run your app. This group +should imply the predefined group **'FastAPI Endpoint Runner'**. This +group defines the minimum access rights that the user needs to: + +- access the endpoint instance it belongs to +- access to its own user record +- access to the partner record that is linked to its user record + +.. code:: xml + + + My Demo Endpoint Group + + + + +Now, you can test your app. You can do it by clicking on the 'Try it +out' button of the route that you have defined. The result of the +request will be displayed in the 'Response' section and contains the +list of partners. + +Note + +The **'FastAPI Endpoint Runner'** group ensures that the user cannot +access any information others than the 3 ones mentioned above. This +means that for every information that you want to access from your app, +you need to create the proper ACLs and record rules. (see `Managing +security into the route +handlers <#managing-security-into-the-route-handlers>`__) It's a good +practice to use a dedicated user into a specific group from the +beginning of your project and in your tests. This will force you to +define the proper security rules for your endoints. + +Dealing with the odoo environment +--------------------------------- + +The **'odoo.addons.fastapi.dependencies'** module provides a set of +functions that you can use to inject reusable dependencies into your +routes. For example, the **'odoo_env'** function returns the current +odoo environment. You can use it to access the odoo models and the +database from your route handlers. + +.. code:: python + + from typing import Annotated + + from odoo.api import Environment + from odoo.addons.fastapi.dependencies import odoo_env + + @demo_api_router.get("/partners", response_model=list[PartnerInfo]) + def get_partners(env: Annotated[Environment, Depends(odoo_env)]) -> list[PartnerInfo]: + return [ + PartnerInfo(name=partner.name, email=partner.email) + for partner in env["res.partner"].search([]) + ] + +As you can see, you can use the **'Depends'** function to inject the +dependency into your route handler. The **'Depends'** function is +provided by the **'fastapi'** framework. You can use it to inject any +dependency into your route handler. As your handler is a python +function, the only way to get access to the odoo environment is to +inject it as a dependency. The fastapi addon provides a set of function +that can be used as dependencies: + +- **'odoo_env'**: Returns the current odoo environment. +- **'fastapi_endpoint'**: Returns the current fastapi endpoint model + instance. +- **'authenticated_partner'**: Returns the authenticated partner. +- **'authenticated_partner_env'**: Returns the current odoo environment + with the authenticated_partner_id into the context. + +By default, the **'odoo_env'** and **'fastapi_endpoint'** dependencies +are available without extra work. + +Note + +Even if 'odoo_env' and 'authenticated_partner_env' returns the current +odoo environment, they are not the same. The 'odoo_env' dependency +returns the environment without any modification while the +'authenticated_partner_env' adds the authenticated partner id into the +context of the environment. As it will be explained in the section +`Managing security into the route +handlers <#managing-security-into-the-route-handlers>`__ dedicated to +the security, the presence of the authenticated partner id into the +context is the key information that will allow you to enforce the +security of your endpoint methods. As consequence, you should always use +the 'authenticated_partner_env' dependency instead of the 'odoo_env' +dependency for all the methods that are not public. + +The dependency injection mechanism +---------------------------------- + +The **'odoo_env'** dependency relies on a simple implementation that +retrieves the current odoo environment from ContextVar variable +initialized at the start of the request processing by the specific +request dispatcher processing the fastapi requests. + +The **'fastapi_endpoint'** dependency relies on the +'dependency_overrides' mechanism provided by the **'fastapi'** module. +(see the fastapi documentation for more details about the +dependency_overrides mechanism). If you take a look at the current +implementation of the **'fastapi_endpoint'** dependency, you will see +that the method depends of two parameters: **'endpoint_id'** and +**'env'**. Each of these parameters are dependencies themselves. + +.. code:: python + + def fastapi_endpoint_id() -> int: + """This method is overriden by default to make the fastapi.endpoint record + available for your endpoint method. To get the fastapi.endpoint record + in your method, you just need to add a dependency on the fastapi_endpoint method + defined below + """ + + + def fastapi_endpoint( + _id: Annotated[int, Depends(fastapi_endpoint_id)], + env: Annotated[Environment, Depends(odoo_env)], + ) -> "FastapiEndpoint": + """Return the fastapi.endpoint record""" + return env["fastapi.endpoint"].browse(_id) + +As you can see, one of these dependencies is the +**'fastapi_endpoint_id'** dependency and has no concrete implementation. +This method is used as a contract that must be implemented/provided at +the time the fastapi app is created. Here comes the power of the +dependency_overrides mechanism. + +If you take a look at the **'\_get_app'** method of the +**'FastapiEndpoint'** model, you will see that the +**'fastapi_endpoint_id'** dependency is overriden by registering a +specific method that returns the id of the current fastapi endpoint +model instance for the original method. + +.. code:: python + + def _get_app(self) -> FastAPI: + app = FastAPI(**self._prepare_fastapi_endpoint_params()) + for router in self._get_fastapi_routers(): + app.include_router(prefix=self.root_path, router=router) + app.dependency_overrides[dependencies.fastapi_endpoint_id] = partial( + lambda a: a, self.id + ) + +This kind of mechanism is very powerful and allows you to inject any +dependency into your route handlers and moreover, define an abstract +dependency that can be used by any other addon and for which the +implementation could depend on the endpoint configuration. + +The authentication mechanism +---------------------------- + +To make our app not tightly coupled with a specific authentication +mechanism, we will use the **'authenticated_partner'** dependency. As +for the **'fastapi_endpoint'** this dependency depends on an abstract +dependency. + +When you define a route handler, you can inject the +**'authenticated_partner'** dependency as a parameter of your route +handler. + +.. code:: python + + from odoo.addons.base.models.res_partner import Partner + + + @demo_api_router.get("/partners", response_model=list[PartnerInfo]) + def get_partners( + env: Annotated[Environment, Depends(odoo_env)], partner: Annotated[Partner, Depends(authenticated_partner)] + ) -> list[PartnerInfo]: + return [ + PartnerInfo(name=partner.name, email=partner.email) + for partner in env["res.partner"].search([]) + ] + +At this stage, your handler is not tied to a specific authentication +mechanism but only expects to get a partner as a dependency. Depending +on your needs, you can implement different authentication mechanism +available for your app. The fastapi addon provides a default +authentication mechanism using the 'BasicAuth' method. This +authentication mechanism is implemented in the +**'odoo.addons.fastapi.dependencies'** module and relies on +functionalities provided by the **'fastapi.security'** module. + +.. code:: python + + def authenticated_partner( + env: Annotated[Environment, Depends(odoo_env)], + security: Annotated[HTTPBasicCredentials, Depends(HTTPBasic())], + ) -> "res.partner": + """Return the authenticated partner""" + partner = env["res.partner"].search( + [("email", "=", security.username)], limit=1 + ) + if not partner: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid authentication credentials", + headers={"WWW-Authenticate": "Basic"}, + ) + if not partner.check_password(security.password): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid authentication credentials", + headers={"WWW-Authenticate": "Basic"}, + ) + return partner + +As you can see, the **'authenticated_partner'** dependency relies on the +**'HTTPBasic'** dependency provided by the **'fastapi.security'** +module. In this dummy implementation, we just check that the provided +credentials can be used to authenticate a user in odoo. If the +authentication is successful, we return the partner record linked to the +authenticated user. + +In some cases you could want to implement a more complex authentication +mechanism that could rely on a token or a session. In this case, you can +override the **'authenticated_partner'** dependency by registering a +specific method that returns the authenticated partner. Moreover, you +can make it configurable on the fastapi endpoint model instance. + +To do it, you just need to implement a specific method for each of your +authentication mechanism and allows the user to select one of these +methods when he creates a new fastapi endpoint. Let's say that we want +to allow the authentication by using an api key or via basic auth. Since +basic auth is already implemented, we will only implement the api key +authentication mechanism. + +.. code:: python + + from fastapi.security import APIKeyHeader + + def api_key_based_authenticated_partner_impl( + api_key: Annotated[str, Depends( + APIKeyHeader( + name="api-key", + description="In this demo, you can use a user's login as api key.", + ) + )], + env: Annotated[Environment, Depends(odoo_env)], + ) -> Partner: + """A dummy implementation that look for a user with the same login + as the provided api key + """ + partner = env["res.users"].search([("login", "=", api_key)], limit=1).partner_id + if not partner: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect API Key" + ) + return partner + +As for the 'BasicAuth' authentication mechanism, we also rely on one of +the native security dependency provided by the **'fastapi.security'** +module. + +Now that we have an implementation for our two authentication +mechanisms, we can allows the user to select one of these authentication +mechanisms by adding a selection field on the fastapi endpoint model. + +.. code:: python + + from odoo import fields, models + + class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + app: str = fields.Selection( + selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"} + ) + demo_auth_method = fields.Selection( + selection=[("api_key", "Api Key"), ("http_basic", "HTTP Bacic")], + string="Authenciation method", + ) + +Note + +A good practice is to prefix specific configuration fields of your app +with the name of your app. This will avoid conflicts with other app when +the 'fastapi.endpoint' model is extended for other 'app'. + +Now that we have a selection field that allows the user to select the +authentication method, we can use the dependency override mechanism to +provide the right implementation of the **'authenticated_partner'** +dependency when the app is instantiated. + +.. code:: python + + from odoo.addons.fastapi.dependencies import authenticated_partner + class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + app: str = fields.Selection( + selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"} + ) + demo_auth_method = fields.Selection( + selection=[("api_key", "Api Key"), ("http_basic", "HTTP Bacic")], + string="Authenciation method", + ) + + def _get_app(self) -> FastAPI: + app = super()._get_app() + if self.app == "demo": + # Here we add the overrides to the authenticated_partner_impl method + # according to the authentication method configured on the demo app + if self.demo_auth_method == "http_basic": + authenticated_partner_impl_override = ( + authenticated_partner_from_basic_auth_user + ) + else: + authenticated_partner_impl_override = ( + api_key_based_authenticated_partner_impl + ) + app.dependency_overrides[ + authenticated_partner_impl + ] = authenticated_partner_impl_override + return app + +To see how the dependency override mechanism works, you can take a look +at the demo app provided by the fastapi addon. If you choose the app +'demo' in the fastapi endpoint form view, you will see that the +authentication method is configurable. You can also see that depending +on the authentication method configured on your fastapi endpoint, the +documentation will change. + +Note + +At time of writing, the dependency override mechanism is not supported +by the fastapi documentation generator. A fix has been proposed and is +waiting to be merged. You can follow the progress of the fix on +`github `__ + +Managing configuration parameters for your app +---------------------------------------------- + +As we have seen in the previous section, you can add configuration +fields on the fastapi endpoint model to allow the user to configure your +app (as for any odoo model you extend). When you need to access these +configuration fields in your route handlers, you can use the +**'odoo.addons.fastapi.dependencies.fastapi_endpoint'** dependency +method to retrieve the 'fastapi.endpoint' record associated to the +current request. + +.. code:: python + + from pydantic import BaseModel, Field + from odoo.addons.fastapi.dependencies import fastapi_endpoint + + class EndpointAppInfo(BaseModel): + id: str + name: str + app: str + auth_method: str = Field(alias="demo_auth_method") + root_path: str + model_config = ConfigDict(from_attributes=True) + + + @demo_api_router.get( + "/endpoint_app_info", + response_model=EndpointAppInfo, + dependencies=[Depends(authenticated_partner)], + ) + async def endpoint_app_info( + endpoint: Annotated[FastapiEndpoint, Depends(fastapi_endpoint)], + ) -> EndpointAppInfo: + """Returns the current endpoint configuration""" + # This method show you how to get access to current endpoint configuration + # It also show you how you can specify a dependency to force the security + # even if the method doesn't require the authenticated partner as parameter + return EndpointAppInfo.model_validate(endpoint) + +Some of the configuration fields of the fastapi endpoint could impact +the way the app is instantiated. For example, in the previous section, +we have seen that the authentication method configured on the +'fastapi.endpoint' record is used in order to provide the right +implementation of the **'authenticated_partner'** when the app is +instantiated. To ensure that the app is re-instantiated when an element +of the configuration used in the instantiation of the app is modified, +you must override the **'\_fastapi_app_fields'** method to add the name +of the fields that impact the instantiation of the app into the returned +list. + +.. code:: python + + class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + app: str = fields.Selection( + selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"} + ) + demo_auth_method = fields.Selection( + selection=[("api_key", "Api Key"), ("http_basic", "HTTP Bacic")], + string="Authenciation method", + ) + + @api.model + def _fastapi_app_fields(self) -> List[str]: + fields = super()._fastapi_app_fields() + fields.append("demo_auth_method") + return fields + +Dealing with languages +---------------------- + +The fastapi addon parses the Accept-Language header of the request to +determine the language to use. This parsing is done by respecting the +`RFC 7231 +specification `__. +That means that the language is determined by the first language found +in the header that is supported by odoo (with care of the priority +order). If no language is found in the header, the odoo default language +is used. This language is then used to initialize the Odoo's environment +context used by the route handlers. All this makes the management of +languages very easy. You don't have to worry about. This feature is also +documented by default into the generated openapi documentation of your +app to instruct the api consumers how to request a specific language. + +How to extend an existing app +----------------------------- + +When you develop a fastapi app, in a native python app it's not possible +to extend an existing one. This limitation doesn't apply to the fastapi +addon because the fastapi endpoint model is designed to be extended. +However, the way to extend an existing app is not the same as the way to +extend an odoo model. + +First of all, it's important to keep in mind that when you define a +route, you are actually defining a contract between the client and the +server. This contract is defined by the route path, the method (GET, +POST, PUT, DELETE, etc.), the parameters and the response. If you want +to extend an existing app, you must ensure that the contract is not +broken. Any change to the contract will respect the `Liskov substitution +principle `__. +This means that the client should not be impacted by the change. + +What does it mean in practice? It means that you can't change the route +path or the method of an existing route. You can't change the name of a +parameter or the type of a response. You can't add a new parameter or a +new response. You can't remove a parameter or a response. If you want to +change the contract, you must create a new route. + +What can you change? + +- You can change the implementation of the route handler. +- You can override the dependencies of the route handler. +- You can add a new route handler. +- You can extend the model used as parameter or as response of the route + handler. + +Let's see how to do that. + +Changing the implementation of the route handler +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Let's say that you want to change the implementation of the route +handler **'/demo/echo'**. Since a route handler is just a python method, +it could seems a tedious task since we are not into a model method and +therefore we can't take advantage of the Odoo inheritance mechanism. + +However, the fastapi addon provides a way to do that. Thanks to the +**'odoo_env'** dependency method, you can access the current odoo +environment. With this environment, you can access the registry and +therefore the model you want to delegate the implementation to. If you +want to change the implementation of the route handler **'/demo/echo'**, +the only thing you have to do is to inherit from the model where the +implementation is defined and override the method **'echo'**. + +.. code:: python + + from pydantic import BaseModel + from fastapi import Depends, APIRouter + from odoo import models + from odoo.addons.fastapi.dependencies import odoo_env + + class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + def _get_fastapi_routers(self) -> List[APIRouter]: + routers = super()._get_fastapi_routers() + routers.append(demo_api_router) + return routers + + demo_api_router = APIRouter() + + @demo_api_router.get( + "/echo", + response_model=EchoResponse, + dependencies=[Depends(odoo_env)], + ) + async def echo( + message: str, + odoo_env: Annotated[Environment, Depends(odoo_env)], + ) -> EchoResponse: + """Echo the message""" + return EchoResponse(message=odoo_env["demo.fastapi.endpoint"].echo(message)) + + class EchoResponse(BaseModel): + message: str + + class DemoEndpoint(models.AbstractModel): + + _name = "demo.fastapi.endpoint" + _description = "Demo Endpoint" + + def echo(self, message: str) -> str: + return message + + class DemoEndpointInherit(models.AbstractModel): + + _inherit = "demo.fastapi.endpoint" + + def echo(self, message: str) -> str: + return f"Hello {message}" + +Note + +It's a good programming practice to implement the business logic outside +the route handler. This way, you can easily test your business logic +without having to test the route handler. In the example above, the +business logic is implemented in the method **'echo'** of the model +**'demo.fastapi.endpoint'**. The route handler just delegate the +implementation to this method. + +Overriding the dependencies of the route handler +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +As you've previously seen, the dependency injection mechanism of fastapi +is very powerful. By designing your route handler to rely on +dependencies with a specific functional scope, you can easily change the +implementation of the dependency without having to change the route +handler. With such a design, you can even define abstract dependencies +that must be implemented by the concrete application. This is the case +of the **'authenticated_partner'** dependency in our previous example. +(you can find the implementation of this dependency in the file +**'odoo/addons/fastapi/dependencies.py'** and it's usage in the file +**'odoo/addons/fastapi/models/fastapi_endpoint_demo.py'**) + +Adding a new route handler +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Let's say that you want to add a new route handler **'/demo/echo2'**. +You could be tempted to add this new route handler in your new addons by +importing the router of the existing app and adding the new route +handler to it. + +.. code:: python + + from odoo.addons.fastapi.models.fastapi_endpoint_demo import demo_api_router + + @demo_api_router.get( + "/echo2", + response_model=EchoResponse, + dependencies=[Depends(odoo_env)], + ) + async def echo2( + message: str, + odoo_env: Annotated[Environment, Depends(odoo_env)], + ) -> EchoResponse: + """Echo the message""" + echo = odoo_env["demo.fastapi.endpoint"].echo2(message) + return EchoResponse(message=f"Echo2: {echo}") + +The problem with this approach is that you unconditionally add the new +route handler to the existing app even if the app is called for a +different database where your new addon is not installed. + +The solution is to define a new router and to add it to the list of +routers returned by the method **'\_get_fastapi_routers'** of the model +**'fastapi.endpoint'** you are inheriting from into your new addon. + +.. code:: python + + class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + def _get_fastapi_routers(self) -> List[APIRouter]: + routers = super()._get_fastapi_routers() + if self.app == "demo": + routers.append(additional_demo_api_router) + return routers + + additional_demo_api_router = APIRouter() + + @additional_demo_api_router.get( + "/echo2", + response_model=EchoResponse, + dependencies=[Depends(odoo_env)], + ) + async def echo2( + message: str, + odoo_env: Annotated[Environment, Depends(odoo_env)], + ) -> EchoResponse: + """Echo the message""" + echo = odoo_env["demo.fastapi.endpoint"].echo2(message) + return EchoResponse(message=f"Echo2: {echo}") + +In this way, the new router is added to the list of routers of your app +only if the app is called for a database where your new addon is +installed. + +Extending the model used as parameter or as response of the route handler +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The fastapi python library uses the pydantic library to define the +models. By default, once a model is defined, it's not possible to extend +it. However, a companion python library called +`extendable_pydantic `__ +provides a way to use inheritance with pydantic models to extend an +existing model. If used alone, it's your responsibility to instruct this +library the list of extensions to apply to a model and the order to +apply them. This is not very convenient. Fortunately, an dedicated odoo +addon exists to make this process complete transparent. This addon is +called +`odoo-addon-extendable-fastapi `__. + +When you want to allow other addons to extend a pydantic model, you must +first define the model as an extendable model by using a dedicated +metaclass + +.. code:: python + + from pydantic import BaseModel + from extendable_pydantic import ExtendableModelMeta + + class Partner(BaseModel, metaclass=ExtendableModelMeta): + name = 0.1 + model_config = ConfigDict(from_attributes=True) + +As any other pydantic model, you can now use this model as parameter or +as response of a route handler. You can also use all the features of +models defined with pydantic. + +.. code:: python + + @demo_api_router.get( + "/partner", + response_model=Location, + dependencies=[Depends(authenticated_partner)], + ) + async def partner( + partner: Annotated[ResPartner, Depends(authenticated_partner)], + ) -> Partner: + """Return the location""" + return Partner.model_validate(partner) + +If you need to add a new field into the model **'Partner'**, you can +extend it in your new addon by defining a new model that inherits from +the model **'Partner'**. + +.. code:: python + + from typing import Optional + from odoo.addons.fastapi.models.fastapi_endpoint_demo import Partner + + class PartnerExtended(Partner, extends=Partner): + email: Optional[str] + +If your new addon is installed in a database, a call to the route +handler **'/demo/partner'** will return a response with the new field +**'email'** if a value is provided by the odoo record. + +.. code:: python + + { + "name": "John Doe", + "email": "jhon.doe@acsone.eu" + } + +If your new addon is not installed in a database, a call to the route +handler **'/demo/partner'** will only return the name of the partner. + +.. code:: python + + { + "name": "John Doe" + } + +Note + +The liskov substitution principle has also to be respected. That means +that if you extend a model, you must add new required fields or you must +provide default values for the new optional fields. + +Managing security into the route handlers +----------------------------------------- + +By default the route handlers are processed using the user configured on +the **'fastapi.endpoint'** model instance. (default is the Public user). +You have seen previously how to define a dependency that will be used to +enforce the authentication of a partner. When a method depends on this +dependency, the 'authenticated_partner_id' key is added to the context +of the partner environment. (If you don't need the partner as dependency +but need to get an environment with the authenticated user, you can use +the dependency 'authenticated_partner_env' instead of +'authenticated_partner'.) + +The fastapi addon extends the 'ir.rule' model to add into the evaluation +context of the security rules the key 'authenticated_partner_id' that +contains the id of the authenticated partner. + +As briefly introduced in a previous section, a good practice when you +develop a fastapi app and you want to protect your data in an efficient +and traceable way is to: + +- create a new user specific to the app but with any access rights. +- create a security group specific to the app and add the user to this + group. (This group must implies the group 'AFastAPI Endpoint Runner' + that give the minimal access rights) +- for each model you want to protect: + + - add a 'ir.model.access' record for the model to allow read access to + your model and add the group to the record. + - create a new 'ir.rule' record for the model that restricts the + access to the records of the model to the authenticated partner by + using the key 'authenticated_partner_id' in domain of the rule. (or + to the user defined on the 'fastapi.endpoint' model instance if the + method is public) + +- add a dependency on the 'authenticated_partner' to your handlers when + you need to access the authenticated partner or ensure that the + service is called by an authenticated partner. + +.. code:: xml + + + My Demo Endpoint User + my_demo_app_user + + + + + My Demo Endpoint Group + + + + + + + My Demo App: access to sale.order + + + + + + + + + + + Sale Order Rule + + [('partner_id', '=', authenticated_partner_id)] + + + +How to test your fastapi app +---------------------------- + +Thanks to the starlette test client, it's possible to test your fastapi +app in a very simple way. With the test client, you can call your route +handlers as if they were real http endpoints. The test client is +available in the **'fastapi.testclient'** module. + +Once again the dependency injection mechanism comes to the rescue by +allowing you to inject into the test client specific implementations of +the dependencies normally provided by the normal processing of the +request by the fastapi app. (for example, you can inject a mock of the +dependency 'authenticated_partner' to test the behavior of your route +handlers when the partner is not authenticated, you can also inject a +mock for the odoo_env etc...) + +The fastapi addon provides a base class for the test cases that you can +use to write your tests. This base class is +**'odoo.fastapi.tests.common.FastAPITransactionCase'**. This class +mainly provides the method **'\_create_test_client'** that you can use +to create a test client for your fastapi app. This method encapsulates +the creation of the test client and the injection of the dependencies. +It also ensures that the odoo environment is make available into the +context of the route handlers. This method is designed to be used when +you need to test your app or when you need to test a specific router +(It's therefore easy to defines tests for routers in an addon that +doesn't provide a fastapi endpoint). + +With this base class, writing a test for a route handler is as simple +as: + +.. code:: python + + from odoo.fastapi.tests.common import FastAPITransactionCase + + from odoo.addons.fastapi import dependencies + from odoo.addons.fastapi.routers import demo_router + + class FastAPIDemoCase(FastAPITransactionCase): + + @classmethod + def setUpClass(cls) -> None: + super().setUpClass() + cls.default_fastapi_running_user = cls.env.ref("fastapi.my_demo_app_user") + cls.default_fastapi_authenticated_partner = cls.env["res.partner"].create({"name": "FastAPI Demo"}) + + def test_hello_world(self) -> None: + with self._create_test_client(router=demo_router) as test_client: + response: Response = test_client.get("/demo/") + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertDictEqual(response.json(), {"Hello": "World"}) + +In the previous example, we created a test client for the demo_router. +We could have created a test client for the whole app by not specifying +the router but the app instead. + +.. code:: python + + from odoo.fastapi.tests.common import FastAPITransactionCase + + from odoo.addons.fastapi import dependencies + from odoo.addons.fastapi.routers import demo_router + + class FastAPIDemoCase(FastAPITransactionCase): + + @classmethod + def setUpClass(cls) -> None: + super().setUpClass() + cls.default_fastapi_running_user = cls.env.ref("fastapi.my_demo_app_user") + cls.default_fastapi_authenticated_partner = cls.env["res.partner"].create({"name": "FastAPI Demo"}) + + def test_hello_world(self) -> None: + demo_endpoint = self.env.ref("fastapi.fastapi_endpoint_demo") + with self._create_test_client(app=demo_endpoint._get_app()) as test_client: + response: Response = test_client.get(f"{demo_endpoint.root_path}/demo/") + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertDictEqual(response.json(), {"Hello": "World"}) + +Overall considerations when you develop an fastapi app +------------------------------------------------------ + +Developing a fastapi app requires to follow some good practices to +ensure that the app is robust and easy to maintain. Here are some of +them: + +- A route handler must be as simple as possible. It must not contain any + business logic. The business logic must be implemented into the + service layer. The route handler must only call the service layer and + return the result of the service layer. To ease extension on your + business logic, your service layer can be implemented as an odoo + abstract model that can be inherited by other addons. +- A route handler should not expose the internal data structure and api + of Odoo. It should provide the api that is needed by the client. More + widely, an app provides a set of services that address a set of use + cases specific to a well defined functional domain. You must always + keep in mind that your api will remain the same for a long time even + if you upgrade your odoo version of modify your business logic. +- A route handler is a transactional unit of work. When you design your + api you must ensure that the completeness of a use case is guaranteed + by a single transaction. If you need to perform several transactions + to complete a use case, you introduce a risk of inconsistency in your + data or extra complexity in your client code. +- Properly handle the errors. The route handler must return a proper + error response when an error occurs. The error response must be + consistent with the rest of the api. The error response must be + documented in the api documentation. By default, the + **'odoo-addon-fastapi'** module handles the common exception types + defined in the **'odoo.exceptions'** module and returns a proper error + response with the corresponding http status code. An error in the + route handler must always return an error response with a http status + code different from 200. The error response must contain a human + readable message that can be displayed to the user. The error response + can also contain a machine readable code that can be used by the + client to handle the error in a specific way. +- When you design your json document through the pydantic models, you + must use the appropriate data types. For example, you must use the + data type **'datetime.date'** to represent a date and not a string. + You must also properly define the constraints on the fields. For + example, if a field is optional, you must use the data type + **'typing.Optional'**. `pydantic `__ + provides everything you need to properly define your json document. +- Always use an appropriate pydantic model as request and/or response + for your route handler. Constraints on the fields of the pydantic + model must apply to the specific use case. For example, if your route + handler is used to create a sale order, the pydantic model must not + contain the field 'id' because the id of the sale order will be + generated by the route handler. But if the id is required afterwords, + the pydantic model for the response must contain the field 'id' as + required. +- Uses descriptive property names in your json documents. For example, + avoid the use of documents providing a flat list of key value pairs. +- Be consistent in the naming of your fields into your json documents. + For example, if you use 'id' to represent the id of a sale order, you + must use 'id' to represent the id of all the other objects. +- Be consistent in the naming style of your fields. Always prefer + underscore to camel case. +- Always use plural for the name of the fields that contain a list of + items. For example, if you have a field 'lines' that contains a list + of sale order lines, you must use 'lines' and not 'line'. +- You can't expect that a client will provide you the identifier of a + specific record in odoo (for example the id of a carrier) if you don't + provide a specific route handler to retrieve the list of available + records. Sometimes, the client must share with odoo the identity of a + specific record to be able to perform an appropriate action specific + to this record (for example, the processing of a payment is different + for each payment acquirer). In this case, you must provide a specific + attribute that allows both the client and odoo to identify the record. + The field 'provider' on a payment acquirer allows you to identify a + specific record in odoo. This kind of approach allows both the client + and odoo to identify the record without having to rely on the id of + the record. (This will ensure that the client will not break if the id + of the record is changed in odoo for example when tests are run on an + other database). +- Always use the same name for the same kind of object. For example, if + you have a field 'lines' that contains a list of sale order lines, you + must use the same name for the same kind of object in all the other + json documents. +- Manage relations between objects in your json documents the same way. + By default, you should return the id of the related object in the json + document. But this is not always possible or convenient, so you can + also return the related object in the json document. The main + advantage of returning the id of the related object is that it allows + you to avoid the `n+1 + problem `__ . The main + advantage of returning the related object in the json document is that + it allows you to avoid an extra call to retrieve the related object. + By keeping in mind the pros and cons of each approach, you can choose + the best one for your use case. Once it's done, you must be consistent + in the way you manage the relations of the same object. +- It's not always a good idea to name your fields into your json + documents with the same name as the fields of the corresponding odoo + model. For example, in your document representing a sale order, you + must not use the name 'order_line' for the field that contains the + list of sale order lines. The name 'order_line' in addition to being + confusing and not consistent with the best practices, is not + auto-descriptive. The name 'lines' is much better. +- Keep a defensive programming approach. If you provide a route handler + that returns a list of records, you must ensure that the computation + of the list is not too long or will not drain your server resources. + For example, for search route handlers, you must ensure that the + search is limited to a reasonable number of records by default. +- As a corollary of the previous point, a search handler must always use + the pagination mechanism with a reasonable default page size. The + result list must be enclosed in a json document that contains the + count of records into the system matching your search criteria and the + list of records for the given page and size. +- Use plural for the name of a service. For example, if you provide a + service that allows you to manage the sale orders, you must use the + name 'sale_orders' and not 'sale_order'. +- ... and many more. + +We could write a book about the best practices to follow when you design +your api but we will stop here. This list is the result of our +experience at `ACSONE SA/NV `__ and it evolves over +time. It's a kind of rescue kit that we would provide to a new developer +that starts to design an api. This kit must be accompanied with the +reading of some useful resources link like the `REST +Guidelines `__. On +a technical level, the `fastapi +documentation `__ provides a lot of +useful information as well, with a lot of examples. Last but not least, +the `pydantic `__ documentation is also very +useful. + +Miscellaneous +------------- + +Development of a search route handler +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The **'odoo-addon-fastapi'** module provides 2 useful piece of code to +help you be consistent when writing a route handler for a search route. + +1. A dependency method to use to specify the pagination parameters in + the same way for all the search route handlers: + **'odoo.addons.fastapi.paging'**. +2. A PagedCollection pydantic model to use to return the result of a + search route handler enclosed in a json document that contains the + count of records. + +.. code:: python + + from typing import Annotated + from pydantic import BaseModel + + from odoo.api import Environment + from odoo.addons.fastapi.dependencies import paging, authenticated_partner_env + from odoo.addons.fastapi.schemas import PagedCollection, Paging + + class SaleOrder(BaseModel): + id: int + name: str + model_config = ConfigDict(from_attributes=True) + + + @router.get( + "/sale_orders", + response_model=PagedCollection[SaleOrder], + response_model_exclude_unset=True, + ) + def get_sale_orders( + paging: Annotated[Paging, Depends(paging)], + env: Annotated[Environment, Depends(authenticated_partner_env)], + ) -> PagedCollection[SaleOrder]: + """Get the list of sale orders.""" + count = env["sale.order"].search_count([]) + orders = env["sale.order"].search([], limit=paging.limit, offset=paging.offset) + return PagedCollection[SaleOrder]( + count=count, + items=[SaleOrder.model_validate(order) for order in orders], + ) + +Note + +The **'odoo.addons.fastapi.schemas.Paging'** and +**'odoo.addons.fastapi.schemas.PagedCollection'** pydantic models are +not designed to be extended to not introduce a dependency between the +**'odoo-addon-fastapi'** module and the **'odoo-addon-extendable'** + +Error handling +~~~~~~~~~~~~~~ + +The error handling is a very important topic in the design of the +fastapi integration with odoo. By default, when instantiating the +fastapi app, the fastapi library declare a default exception handler +that will catch any exception raised by the route handlers and return a +proper error response. This is done to ensure that the serving of the +app is not interrupted by an unhandled exception. If this implementation +makes sense for a native fastapi app, it's not the case for the fastapi +integration with odoo. The transactional nature of the calls to odoo's +api is implemented at the root of the request processing by odoo. To +ensure that the transaction is properly managed, the integration with +odoo must ensure that the exceptions raised by the route handlers +properly bubble up to the handling of the request by odoo. This is done +by the monkey patching of the registered exception handler of the +fastapi app in the **'odoo.addons.fastapi.models.error_handlers'** +module. As a result, it's no longer possible to define a custom +exception handler in your fastapi app. If you add a custom exception +handler in your app, it will be ignored. + +FastAPI addons directory structure +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When you develop a new addon to expose an api with fastapi, it's a good +practice to follow the same directory structure and naming convention +for the files related to the api. It will help you to easily find the +files related to the api and it will help the other developers to +understand your code. + +Here is the directory structure that we recommend. It's based on +practices that are used in the python community when developing a +fastapi app. + +:: + + . + ├── x_api + │   ├── data + │   │ ├── ... .xml + │   ├── demo + │   │ ├── ... .xml + │   ├── i18n + │   │ ├── ... .po + │   ├── models + │   │ ├── __init__.py + │   │ ├── fastapi_endpoint.py # your app + │   │ └── ... .py + │   └── routers + │   │ ├── __init__.py + │   │ ├── items.py + │   │ └── ... .py + │   ├── schemas | schemas.py + │   │ ├── __init__.py + │   │ ├── my_model.py # pydantic model + │   │ └── ... .py + │   ├── security + │   │ ├── ... .xml + │   ├── views + │   │ ├── ... .xml + │   ├── __init__.py + │   ├── __manifest__.py + │   ├── dependencies.py # custom dependencies + │   ├── error_handlers.py # custom error handlers + +- The **'models'** directory contains the odoo models. When you define a + new app, as for the others addons, you will add your new model + inheriting from the **'fastapi.endpoint'** model in this directory. + +- The **'routers'** directory contains the fastapi routers. You will add + your new routers in this directory. Each route starting with the same + prefix should be grouped in the same file. For example, all the routes + starting with '/items' should be defined in the **'items.py'** file. + The **'\__init\_\_.py'** file in this directory is used to import all + the routers defined in the directory and create a global router that + can be used in an app. For example, in your **'items.py'** file, you + will define a router like this: + + .. code:: python + + router = APIRouter(tags=["items"]) + + router.get("/items", response_model=List[Item]) + def list_items(): + pass + + In the **'\__init\_\_.py'** file, you will import the router and add + it to the global router or your addon. + + .. code:: python + + from fastapi import APIRouter + + from .items import router as items_router + + router = APIRouter() + router.include_router(items_router) + +- The **'schemas.py'** will be used to define the pydantic models. For + complex APIs with a lot of models, it will be better to create a + **'schemas'** directory and split the models in different files. The + **'\__init\_\_.py'** file in this directory will be used to import all + the models defined in the directory. For example, in your + **'my_model.py'** file, you will define a model like this: + + .. code:: python + + from pydantic import BaseModel + + class MyModel(BaseModel): + name: str + description: str = None + + In the **'\__init\_\_.py'** file, you will import the model's classes + from the files in the directory. + + .. code:: python + + from .my_model import MyModel + + This will allow to always import the models from the schemas module + whatever the models are spread across different files or defined in + the **'schemas.py'** file. + + .. code:: python + + from x_api_addon.schemas import MyModel + +- The **'dependencies.py'** file contains the custom dependencies that + you will use in your routers. For example, you can define a dependency + to check the access rights of the user. + +- The **'error_handlers.py'** file contains the custom error handlers + that you will use in your routers. The **'odoo-addon-fastapi'** module + provides the default error handlers for the common odoo exceptions. + Chance are that you will not need to define your own error handlers. + But if you need to do it, you can define them in this file. + +What's next? +------------ + +The **'odoo-addon-fastapi'** module is still in its early stage of +development. It will evolve over time to integrate your feedback and to +provide the missing features. It's now up to you to try it and to +provide your feedback. + +Known issues / Roadmap +====================== + +The +`roadmap `__ +and `known +issues `__ +can be found on GitHub. + +The **FastAPI** module provides an easy way to use WebSockets. +Unfortunately, this support is not 'yet' available in the **Odoo** +framework. The challenge is high because the integration of the fastapi +is based on the use of a specific middleware that convert the WSGI +request consumed by odoo to a ASGI request. The question is to know if +it is also possible to develop the same kind of bridge for the +WebSockets and to stream large responses. + +Changelog +========= + +17.0.3.0.0 (2024-10-03) +----------------------- + +Features +~~~~~~~~ + +- + + - A new parameter is now available on the endpoint model to let you + disable the creation and the store of session files used by Odoo for + calls to your application endpoint. This is usefull to prevent disk + space consumption and IO operations if your application doesn't need + to use this sessions files which are mainly used by Odoo by to store + the session info of logged in users. + (`#442 `__) + +Bugfixes +~~~~~~~~ + +- Fix issue with the retry of a POST request with a body content. + + Prior to this fix the retry of a POST request with a body content + would stuck in a loop and never complete. This was due to the fact + that the request input stream was not reset after a failed attempt to + process the request. + (`#440 `__) + +17.0.2.0.0 (2024-10-03) +----------------------- + +Bugfixes +~~~~~~~~ + +- This change is a complete rewrite of the way the transactions are + managed when integrating a fastapi application into Odoo. + + In the previous implementation, specifics error handlers were put in + place to catch exception occurring in the handling of requests made to + a fastapi application and to rollback the transaction in case of + error. This was done by registering specifics error handlers methods + to the fastapi application using the 'add_exception_handler' method of + the fastapi application. In this implementation, the transaction was + rolled back in the error handler method. + + This approach was not working as expected for several reasons: + + - The handling of the error at the fastapi level prevented the retry + mechanism to be triggered in case of a DB concurrency error. This is + because the error was catch at the fastapi level and never bubbled + up to the early stage of the processing of the request where the + retry mechanism is implemented. + - The cleanup of the environment and the registry was not properly + done in case of error. In the **'odoo.service.model.retrying'** + method, you can see that the cleanup process is different in case of + error raised by the database and in case of error raised by the + application. + + This change fix these issues by ensuring that errors are no more catch + at the fastapi level and bubble up the fastapi processing stack + through the event loop required to transform WSGI to ASGI. As result + the transactional nature of the requests to the fastapi applications + is now properly managed by the Odoo framework. + + (`#422 `__) + +17.0.1.0.1 (2024-10-02) +----------------------- + +Bugfixes +~~~~~~~~ + +- Fix compatibility issues with the latest Odoo version + + From + https://github.com/odoo/odoo/commit/cb1d057dcab28cb0b0487244ba99231ee292502e + the original werkzeug HTTPRequest class has been wrapped in a new + class to keep under control the attributes developers use. This + changes take care of this new implementation but also keep + compatibility with the old ones. + (`#414 `__) + +16.0.1.2.5 (2024-01-17) +----------------------- + +Bugfixes +~~~~~~~~ + +- Odoo has done an update and now, it checks domains of ir.rule on + creation and modification. + + The ir.rule 'Fastapi: Running user rule' uses a field + (authenticate\ *partner_id) that comes from the context. This field + wasn't always set and this caused an error when Odoo checked the + domain. So now it is set to False by default. + (``#410 ``*) + +16.0.1.2.3 (2023-12-21) +----------------------- + +Bugfixes +~~~~~~~~ + +- In case of exception in endpoint execution, close the database cursor + after rollback. + + This is to ensure that the *retrying* method in *service/model.py* + does not try to flush data to the database. + (`#405 `__) + +16.0.1.2.2 (2023-12-12) +----------------------- + +Bugfixes +~~~~~~~~ + +- When using the 'FastAPITransactionCase' class, allows to specify a + specific override of the 'authenticated_partner_impl' method into the + list of overrides to apply. Before this change, the + 'authenticated_partner_impl' override given in the 'overrides' + parameter was always overridden in the '\_create_test_client' method + of the 'FastAPITransactionCase' class. It's now only overridden if the + 'authenticated_partner_impl' method is not already present in the list + of overrides to apply and no specific partner is given. If a specific + partner is given at same time of an override for the + 'authenticated_partner_impl' method, an error is raised. + (`#396 `__) + +16.0.1.2.1 (2023-11-03) +----------------------- + +Bugfixes +~~~~~~~~ + +- Fix a typo in the Field declaration of the 'count' attribute of the + 'PagedCollection' schema. + + Misspelt parameter was triggering a deprecation warning due to recent + versions of Pydantic seeing it as an arbitrary parameter. + (`#389 `__) + +16.0.1.2.0 (2023-10-13) +----------------------- + +Features +~~~~~~~~ + +- The field *total* in the *PagedCollection* schema is replaced by the + field *count*. The field *total* is now deprecated and will be removed + in the next major version. This change is backward compatible. The + json document returned will now contain both fields *total* and + *count* with the same value. In your python code the field *total*, if + used, will fill the field *count* with the same value. You are + encouraged to use the field *count* instead of *total* and adapt your + code accordingly. + (`#380 `__) + +Bug Tracker +=========== + +Bugs are tracked on `GitHub Issues `_. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us to smash it by providing a detailed and welcomed +`feedback `_. + +Do not contact contributors directly about support or help with technical issues. + +Credits +======= + +Authors +------- + +* ACSONE SA/NV + +Contributors +------------ + +- Laurent Mignon + +Maintainers +----------- + +This module is maintained by the OCA. + +.. image:: https://odoo-community.org/logo.png + :alt: Odoo Community Association + :target: https://odoo-community.org + +OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use. + +.. |maintainer-lmignon| image:: https://github.com/lmignon.png?size=40px + :target: https://github.com/lmignon + :alt: lmignon + +Current `maintainer `__: + +|maintainer-lmignon| + +This module is part of the `OCA/rest-framework `_ project on GitHub. + +You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute. diff --git a/fastapi/__init__.py b/fastapi/__init__.py new file mode 100644 index 000000000..f4d0f5d36 --- /dev/null +++ b/fastapi/__init__.py @@ -0,0 +1,3 @@ +from . import models +from . import fastapi_dispatcher +from . import error_handlers diff --git a/fastapi/__manifest__.py b/fastapi/__manifest__.py new file mode 100644 index 000000000..e201c1afb --- /dev/null +++ b/fastapi/__manifest__.py @@ -0,0 +1,34 @@ +# Copyright 2022 ACSONE SA/NV +# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL). + +{ + "name": "Odoo FastAPI", + "summary": """ + Odoo FastAPI endpoint""", + "version": "18.0.1.0.0", + "license": "LGPL-3", + "author": "ACSONE SA/NV,Odoo Community Association (OCA)", + "maintainers": ["lmignon"], + "website": "https://github.com/OCA/rest-framework", + "depends": ["endpoint_route_handler"], + "data": [ + "security/res_groups.xml", + "security/fastapi_endpoint.xml", + "security/ir_rule+acl.xml", + "views/fastapi_menu.xml", + "views/fastapi_endpoint.xml", + "views/fastapi_endpoint_demo.xml", + ], + "demo": ["demo/fastapi_endpoint_demo.xml"], + "external_dependencies": { + "python": [ + "fastapi>=0.110.0", + "python-multipart", + "ujson", + "a2wsgi>=1.10.6", + "parse-accept-language", + ] + }, + "development_status": "Beta", + "installable": True, +} diff --git a/fastapi/context.py b/fastapi/context.py new file mode 100644 index 000000000..a8de1ef61 --- /dev/null +++ b/fastapi/context.py @@ -0,0 +1,10 @@ +# Copyright 2022 ACSONE SA/NV +# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL). + +# define context vars to hold the odoo env + +from contextvars import ContextVar + +from odoo.api import Environment + +odoo_env_ctx: ContextVar[Environment] = ContextVar("odoo_env_ctx") diff --git a/fastapi/demo/fastapi_endpoint_demo.xml b/fastapi/demo/fastapi_endpoint_demo.xml new file mode 100644 index 000000000..94c3c373f --- /dev/null +++ b/fastapi/demo/fastapi_endpoint_demo.xml @@ -0,0 +1,47 @@ + + + + + + My Demo Endpoint User + my_demo_app_user + + + + + + My Demo Endpoint Group + + + + + + + + Fastapi Demo Endpoint + + demo + /fastapi_demo + http_basic + + + diff --git a/fastapi/dependencies.py b/fastapi/dependencies.py new file mode 100644 index 000000000..16226bf29 --- /dev/null +++ b/fastapi/dependencies.py @@ -0,0 +1,177 @@ +# Copyright 2022 ACSONE SA/NV +# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL). + +from typing import TYPE_CHECKING, Annotated + +from odoo.api import Environment +from odoo.exceptions import AccessDenied + +from odoo.addons.base.models.res_partner import Partner +from odoo.addons.base.models.res_users import Users + +from fastapi import Depends, Header, HTTPException, Query, status +from fastapi.security import HTTPBasic, HTTPBasicCredentials + +from .context import odoo_env_ctx +from .schemas import Paging + +if TYPE_CHECKING: + from .models.fastapi_endpoint import FastapiEndpoint + + +def company_id() -> int | None: + """This method may be overriden by the FastAPI app to set the allowed company + in the Odoo env of the endpoint. By default, the company defined on the + endpoint record is used. + """ + return None + + +def odoo_env(company_id: Annotated[int | None, Depends(company_id)]) -> Environment: + env = odoo_env_ctx.get() + if company_id is not None: + env = env(context=dict(env.context, allowed_company_ids=[company_id])) + + yield env + + +def authenticated_partner_impl() -> Partner: + """This method has to be overriden when you create your fastapi app + to declare the way your partner will be provided. In some case, this + partner will come from the authentication mechanism (ex jwt token) in other cases + it could comme from a lookup on an email received into an HTTP header ... + See the fastapi_endpoint_demo for an example""" + + +def optionally_authenticated_partner_impl() -> Partner | None: + """This method has to be overriden when you create your fastapi app + and you need to get an optional authenticated partner into your endpoint. + """ + + +def authenticated_partner_env( + partner: Annotated[Partner, Depends(authenticated_partner_impl)], +) -> Environment: + """Return an environment with the authenticated partner id in the context""" + return partner.with_context(authenticated_partner_id=partner.id).env + + +def optionally_authenticated_partner_env( + partner: Annotated[Partner | None, Depends(optionally_authenticated_partner_impl)], + env: Annotated[Environment, Depends(odoo_env)], +) -> Environment: + """Return an environment with the authenticated partner id in the context if + the partner is not None + """ + if partner: + return partner.with_context(authenticated_partner_id=partner.id).env + return env + + +def authenticated_partner( + partner: Annotated[Partner, Depends(authenticated_partner_impl)], + partner_env: Annotated[Environment, Depends(authenticated_partner_env)], +) -> Partner: + """If you need to get access to the authenticated partner into your + endpoint, you can add a dependency into the endpoint definition on this + method. + This method is a safe way to declare a dependency without requiring a + specific implementation. It depends on `authenticated_partner_impl`. The + concrete implementation of authenticated_partner_impl has to be provided + when the FastAPI app is created. + This method return a partner into the authenticated_partner_env + """ + return partner_env["res.partner"].browse(partner.id) + + +def optionally_authenticated_partner( + partner: Annotated[Partner | None, Depends(optionally_authenticated_partner_impl)], + partner_env: Annotated[Environment, Depends(optionally_authenticated_partner_env)], +) -> Partner | None: + """If you need to get access to the authenticated partner if the call is + authenticated, you can add a dependency into the endpoint definition on this + method. + + This method defer from authenticated_partner by the fact that it returns + None if the partner is not authenticated . + """ + if partner: + return partner_env["res.partner"].browse(partner.id) + return None + + +def paging( + page: Annotated[int, Query(ge=1)] = 1, page_size: Annotated[int, Query(ge=1)] = 80 +) -> Paging: + """Return a Paging object from the page and page_size parameters""" + return Paging(limit=page_size, offset=(page - 1) * page_size) + + +def basic_auth_user( + credential: Annotated[HTTPBasicCredentials, Depends(HTTPBasic())], + env: Annotated[Environment, Depends(odoo_env)], +) -> Users: + username = credential.username + password = credential.password + try: + response = ( + env["res.users"] + .sudo() + .authenticate( + db=env.cr.dbname, + credential={ + "type": "password", + "login": username, + "password": password, + }, + user_agent_env=None, + ) + ) + return env["res.users"].browse(response.get("uid")) + except AccessDenied as ad: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect username or password", + headers={"WWW-Authenticate": "Basic"}, + ) from ad + + +def authenticated_partner_from_basic_auth_user( + user: Annotated[Users, Depends(basic_auth_user)], + env: Annotated[Environment, Depends(odoo_env)], +) -> Partner: + return env["res.partner"].browse(user.sudo().partner_id.id) + + +def fastapi_endpoint_id() -> int: + """This method is overriden by the FastAPI app to make the fastapi.endpoint record + available for your endpoint method. To get the fastapi.endpoint record + in your method, you just need to add a dependency on the fastapi_endpoint method + defined below + """ + + +def fastapi_endpoint( + _id: Annotated[int, Depends(fastapi_endpoint_id)], + env: Annotated[Environment, Depends(odoo_env)], +) -> "FastapiEndpoint": + """Return the fastapi.endpoint record""" + return env["fastapi.endpoint"].browse(_id) + + +def accept_language( + accept_language: Annotated[ + str | None, + Header( + alias="Accept-Language", + description="The Accept-Language header is used to specify the language " + "of the content to be returned. If a language is not available, the " + "server will return the content in the default language.", + ), + ] = None, +) -> str: + """This dependency is used at application level to document the way the language + to use for the response is specified. The header is processed outside of the + fastapi app to initialize the odoo environment with the right language. + """ + return accept_language diff --git a/fastapi/depends.py b/fastapi/depends.py new file mode 100644 index 000000000..5b8c11bac --- /dev/null +++ b/fastapi/depends.py @@ -0,0 +1,12 @@ +# Copyright 2023 ACSONE SA/NV +# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL). + +import warnings + +warnings.warn( + "The 'depends' package is deprecated. Please use 'dependencies' instead.", + DeprecationWarning, + stacklevel=2, +) + +from .dependencies import * # noqa: F403, F401, E402 diff --git a/fastapi/error_handlers.py b/fastapi/error_handlers.py new file mode 100644 index 000000000..2e4202d6b --- /dev/null +++ b/fastapi/error_handlers.py @@ -0,0 +1,77 @@ +# Copyright 2022 ACSONE SA/NV +# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL). + +from starlette import status +from starlette.exceptions import HTTPException, WebSocketException +from starlette.middleware.errors import ServerErrorMiddleware +from starlette.middleware.exceptions import ExceptionMiddleware +from starlette.responses import JSONResponse +from starlette.websockets import WebSocket +from werkzeug.exceptions import HTTPException as WerkzeugHTTPException + +from odoo.exceptions import AccessDenied, AccessError, MissingError, UserError + +from fastapi import Request +from fastapi.encoders import jsonable_encoder +from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError +from fastapi.utils import is_body_allowed_for_status_code + + +def convert_exception_to_status_body(exc: Exception) -> tuple[int, dict]: + body = {} + status_code = status.HTTP_500_INTERNAL_SERVER_ERROR + details = "Internal Server Error" + + if isinstance(exc, WerkzeugHTTPException): + status_code = exc.code + details = exc.description + elif isinstance(exc, HTTPException): + status_code = exc.status_code + details = exc.detail + elif isinstance(exc, RequestValidationError): + status_code = status.HTTP_422_UNPROCESSABLE_ENTITY + details = jsonable_encoder(exc.errors()) + elif isinstance(exc, WebSocketRequestValidationError): + status_code = status.WS_1008_POLICY_VIOLATION + details = jsonable_encoder(exc.errors()) + elif isinstance(exc, AccessDenied | AccessError): + status_code = status.HTTP_403_FORBIDDEN + details = "AccessError" + elif isinstance(exc, MissingError): + status_code = status.HTTP_404_NOT_FOUND + details = "MissingError" + elif isinstance(exc, UserError): + status_code = status.HTTP_400_BAD_REQUEST + details = exc.args[0] + + if is_body_allowed_for_status_code(status_code): + # use the same format as in + # fastapi.exception_handlers.http_exception_handler + body = {"detail": details} + return status_code, body + + +# we need to monkey patch the ServerErrorMiddleware and ExceptionMiddleware classes +# to ensure that all the exceptions that are handled by these specific +# middlewares are let to bubble up to the retrying mechanism and the +# dispatcher error handler to ensure that appropriate action are taken +# regarding the transaction, environment, and registry. These middlewares +# are added by default by FastAPI when creating an application and it's not +# possible to remove them. So we need to monkey patch them. + + +def pass_through_exception_handler( + self, request: Request, exc: Exception +) -> JSONResponse: + raise exc + + +def pass_through_websocket_exception_handler( + self, websocket: WebSocket, exc: WebSocketException +) -> None: + raise exc + + +ServerErrorMiddleware.error_response = pass_through_exception_handler +ExceptionMiddleware.http_exception = pass_through_exception_handler +ExceptionMiddleware.websocket_exception = pass_through_websocket_exception_handler diff --git a/fastapi/fastapi_dispatcher.py b/fastapi/fastapi_dispatcher.py new file mode 100644 index 000000000..1a8eb3532 --- /dev/null +++ b/fastapi/fastapi_dispatcher.py @@ -0,0 +1,114 @@ +# Copyright 2022 ACSONE SA/NV +# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL). + +from contextlib import contextmanager +from io import BytesIO + +from odoo.http import Dispatcher, request + +from .context import odoo_env_ctx +from .error_handlers import convert_exception_to_status_body + + +class FastApiDispatcher(Dispatcher): + routing_type = "fastapi" + + @classmethod + def is_compatible_with(cls, request): + return True + + def dispatch(self, endpoint, args): + # don't parse the httprequest let starlette parse the stream + self.request.params = {} # dict(self.request.get_http_params(), **args) + environ = self._get_environ() + root_path = "/" + environ["PATH_INFO"].split("/")[1] + # TODO store the env into contextvar to be used by the odoo_env + # depends method + fastapi_endpoint = self.request.env["fastapi.endpoint"].sudo() + app = fastapi_endpoint.get_app(root_path) + uid = fastapi_endpoint.get_uid(root_path) + data = BytesIO() + with self._manage_odoo_env(uid): + for r in app(environ, self._make_response): + data.write(r) + if self.inner_exception: + raise self.inner_exception + return self.request.make_response( + data.getvalue(), headers=self.headers, status=self.status + ) + + def handle_error(self, exc): + headers = getattr(exc, "headers", None) + status_code, body = convert_exception_to_status_body(exc) + return self.request.make_json_response( + body, status=status_code, headers=headers + ) + + def _make_response(self, status_mapping, headers_tuple, content): + self.status = status_mapping[:3] + self.headers = dict(headers_tuple) + self.inner_exception = None + # in case of exception, the method asgi_done_callback of the + # ASGIResponder will trigger an "a2wsgi.error" event with the exception + # instance stored in a tuple with the type of the exception and the traceback. + # The event loop will then be notified and then call the `error_response` + # method of the ASGIResponder. This method will then call the + # `_make_response` method provided as callback to the app with the tuple + # of the exception as content. In this case, we store the exception + # instance in the `inner_exception` attribute to be able to raise it + # in the `dispatch` method. + if ( + isinstance(content, tuple) + and len(content) == 3 + and isinstance(content[1], Exception) + ): + self.inner_exception = content[1] + + def _get_environ(self): + try: + # normal case after + # https://github.com/odoo/odoo/commit/cb1d057dcab28cb0b0487244ba99231ee292502e + httprequest = self.request.httprequest._HTTPRequest__wrapped + except AttributeError: + # fallback for older odoo versions + # The try except is the most efficient way to handle this + # as we expect that most of the time the attribute will be there + # and this code will no more be executed if it runs on an up to + # date odoo version. (EAFP: Easier to Ask for Forgiveness than Permission) + httprequest = self.request.httprequest + environ = httprequest.environ + stream = httprequest._get_stream_for_parsing() + # Check if the stream supports seeking + if hasattr(stream, "seekable") and stream.seekable(): + # Reset the stream to the beginning to ensure it can be consumed + # again by the application in case of a retry mechanism + stream.seek(0) + else: + # If the stream does not support seeking, we need wrap it + # in a BytesIO object. This way we can seek back to the beginning + # of the stream to read the data again if needed. + if not hasattr(httprequest, "_cached_stream"): + httprequest._cached_stream = BytesIO(stream.read()) + stream = httprequest._cached_stream + stream.seek(0) + environ["wsgi.input"] = stream + return environ + + @contextmanager + def _manage_odoo_env(self, uid=None): + env = request.env + accept_language = request.httprequest.headers.get("Accept-language") + context = env.context + if accept_language: + lang = ( + env["res.lang"].sudo()._get_lang_from_accept_language(accept_language) + ) + if lang: + env = env(context=dict(context, lang=lang)) + if uid: + env = env(user=uid) + token = odoo_env_ctx.set(env) + try: + yield + finally: + odoo_env_ctx.reset(token) diff --git a/fastapi/i18n/fastapi.pot b/fastapi/i18n/fastapi.pot new file mode 100644 index 000000000..33439cdfc --- /dev/null +++ b/fastapi/i18n/fastapi.pot @@ -0,0 +1,246 @@ +# Translation of Odoo Server. +# This file contains the translation of the following modules: +# * fastapi +# +msgid "" +msgstr "" +"Project-Id-Version: Odoo Server 17.0\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language-Team: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: \n" +"Plural-Forms: \n" + +#. module: fastapi +#: model:ir.model.fields,help:fastapi.field_fastapi_endpoint__description +msgid "A short description of the API. It can use Markdown" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__active +msgid "Active" +msgstr "" + +#. module: fastapi +#: model:res.groups,name:fastapi.group_fastapi_manager +msgid "Administrator" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields.selection,name:fastapi.selection__fastapi_endpoint__demo_auth_method__api_key +msgid "Api Key" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__app +#: model_terms:ir.ui.view,arch_db:fastapi.fastapi_endpoint_search_view +msgid "App" +msgstr "" + +#. module: fastapi +#: model_terms:ir.ui.view,arch_db:fastapi.fastapi_endpoint_form_view +#: model_terms:ir.ui.view,arch_db:fastapi.fastapi_endpoint_search_view +msgid "Archived" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__demo_auth_method +msgid "Authenciation method" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__company_id +msgid "Company" +msgstr "" + +#. module: fastapi +#: model_terms:ir.ui.view,arch_db:fastapi.fastapi_endpoint_demo_form_view +msgid "Configuration" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__create_uid +msgid "Created by" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__create_date +msgid "Created on" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields.selection,name:fastapi.selection__fastapi_endpoint__app__demo +msgid "Demo Endpoint" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__description +msgid "Description" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__display_name +msgid "Display Name" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__docs_url +msgid "Docs Url" +msgstr "" + +#. module: fastapi +#: model:ir.module.category,name:fastapi.module_category_fastapi +#: model:ir.ui.menu,name:fastapi.menu_fastapi_root +msgid "FastAPI" +msgstr "" + +#. module: fastapi +#: model:ir.actions.act_window,name:fastapi.fastapi_endpoint_act_window +#: model:ir.model,name:fastapi.model_fastapi_endpoint +#: model:ir.ui.menu,name:fastapi.fastapi_endpoint_menu +msgid "FastAPI Endpoint" +msgstr "" + +#. module: fastapi +#: model:res.groups,name:fastapi.group_fastapi_endpoint_runner +msgid "FastAPI Endpoint Runner" +msgstr "" + +#. module: fastapi +#: model_terms:ir.ui.view,arch_db:fastapi.fastapi_endpoint_search_view +msgid "Group by..." +msgstr "" + +#. module: fastapi +#: model:ir.model.fields.selection,name:fastapi.selection__fastapi_endpoint__demo_auth_method__http_basic +msgid "HTTP Basic" +msgstr "" + +#. module: fastapi +#: model:ir.module.category,description:fastapi.module_category_fastapi +msgid "Helps you manage your Fastapi Endpoints" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__id +msgid "ID" +msgstr "" + +#. module: fastapi +#: model:ir.model,name:fastapi.model_res_lang +msgid "Languages" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__write_uid +msgid "Last Updated by" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__write_date +msgid "Last Updated on" +msgstr "" + +#. module: fastapi +#: model:res.groups,name:fastapi.my_demo_app_group +msgid "My Demo Endpoint Group" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__name +msgid "Name" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,help:fastapi.field_fastapi_endpoint__registry_sync +msgid "" +"ON: the record has been modified and registry was not notified.\n" +"No change will be active until this flag is set to false via proper action.\n" +"\n" +"OFF: record in line with the registry, nothing to do." +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__openapi_url +msgid "Openapi Url" +msgstr "" + +#. module: fastapi +#: model:ir.model,name:fastapi.model_ir_rule +msgid "Record Rule" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__redoc_url +msgid "Redoc Url" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__registry_sync +msgid "Registry Sync" +msgstr "" + +#. module: fastapi +#: model_terms:ir.ui.view,arch_db:fastapi.fastapi_endpoint_form_view +msgid "Registry Sync Required" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__root_path +msgid "Root Path" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__save_http_session +msgid "Save HTTP Session" +msgstr "" + +#. module: fastapi +#: model:ir.actions.server,name:fastapi.fastapi_endpoint_action_sync_registry +#: model_terms:ir.ui.view,arch_db:fastapi.fastapi_endpoint_form_view +#: model_terms:ir.ui.view,arch_db:fastapi.fastapi_endpoint_tree_view +msgid "Sync Registry" +msgstr "" + +#. module: fastapi +#. odoo-python +#: code:addons/fastapi/models/fastapi_endpoint_demo.py:0 +#, python-format +msgid "The authentication method is required for app %(app)s" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,help:fastapi.field_fastapi_endpoint__name +msgid "The title of the API." +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,help:fastapi.field_fastapi_endpoint__user_id +msgid "The user to use to execute the API calls." +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__user_id +#: model:res.groups,name:fastapi.group_fastapi_user +msgid "User" +msgstr "" + +#. module: fastapi +#: model:ir.model.fields,help:fastapi.field_fastapi_endpoint__save_http_session +msgid "" +"Whether session should be saved into the session store. This is required if " +"for example you use the Odoo's authentication mechanism. Oherwise chance are" +" high that you don't need it and could turn off this behaviour. Additionaly " +"turning off this option will prevent useless IO operation when storing and " +"reading the session on the disk and prevent unexpecteed disk space " +"consumption." +msgstr "" + +#. module: fastapi +#. odoo-python +#: code:addons/fastapi/models/fastapi_endpoint.py:0 +#, python-format +msgid "`%(name)s` uses a blacklisted root_path = `%(root_path)s`" +msgstr "" diff --git a/fastapi/i18n/it.po b/fastapi/i18n/it.po new file mode 100644 index 000000000..3f3376b77 --- /dev/null +++ b/fastapi/i18n/it.po @@ -0,0 +1,264 @@ +# Translation of Odoo Server. +# This file contains the translation of the following modules: +# * fastapi +# +msgid "" +msgstr "" +"Project-Id-Version: Odoo Server 16.0\n" +"Report-Msgid-Bugs-To: \n" +"PO-Revision-Date: 2024-10-04 09:06+0000\n" +"Last-Translator: mymage \n" +"Language-Team: none\n" +"Language: it\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: \n" +"Plural-Forms: nplurals=2; plural=n != 1;\n" +"X-Generator: Weblate 5.6.2\n" + +#. module: fastapi +#: model:ir.model.fields,help:fastapi.field_fastapi_endpoint__description +msgid "A short description of the API. It can use Markdown" +msgstr "Una breve descrizione dell'API. Può contenere Markdown" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__active +msgid "Active" +msgstr "Attivo" + +#. module: fastapi +#: model:res.groups,name:fastapi.group_fastapi_manager +msgid "Administrator" +msgstr "Amministratore" + +#. module: fastapi +#: model:ir.model.fields.selection,name:fastapi.selection__fastapi_endpoint__demo_auth_method__api_key +msgid "Api Key" +msgstr "Chiave API" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__app +#: model_terms:ir.ui.view,arch_db:fastapi.fastapi_endpoint_search_view +msgid "App" +msgstr "Applicazione" + +#. module: fastapi +#: model_terms:ir.ui.view,arch_db:fastapi.fastapi_endpoint_form_view +#: model_terms:ir.ui.view,arch_db:fastapi.fastapi_endpoint_search_view +msgid "Archived" +msgstr "In archivio" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__demo_auth_method +msgid "Authenciation method" +msgstr "Metodo autenticazione" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__company_id +msgid "Company" +msgstr "Azienda" + +#. module: fastapi +#: model_terms:ir.ui.view,arch_db:fastapi.fastapi_endpoint_demo_form_view +msgid "Configuration" +msgstr "Configurazione" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__create_uid +msgid "Created by" +msgstr "Creato da" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__create_date +msgid "Created on" +msgstr "Creato il" + +#. module: fastapi +#: model:ir.model.fields.selection,name:fastapi.selection__fastapi_endpoint__app__demo +msgid "Demo Endpoint" +msgstr "Endpoint esempio" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__description +msgid "Description" +msgstr "Descrizione" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__display_name +msgid "Display Name" +msgstr "Nome visualizzato" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__docs_url +msgid "Docs Url" +msgstr "URL documenti" + +#. module: fastapi +#: model:ir.module.category,name:fastapi.module_category_fastapi +#: model:ir.ui.menu,name:fastapi.menu_fastapi_root +msgid "FastAPI" +msgstr "FastAPI" + +#. module: fastapi +#: model:ir.actions.act_window,name:fastapi.fastapi_endpoint_act_window +#: model:ir.model,name:fastapi.model_fastapi_endpoint +#: model:ir.ui.menu,name:fastapi.fastapi_endpoint_menu +msgid "FastAPI Endpoint" +msgstr "Endopoint FastAPI" + +#. module: fastapi +#: model:res.groups,name:fastapi.group_fastapi_endpoint_runner +msgid "FastAPI Endpoint Runner" +msgstr "Esecutore endopoint FastAPI" + +#. module: fastapi +#: model_terms:ir.ui.view,arch_db:fastapi.fastapi_endpoint_search_view +msgid "Group by..." +msgstr "Raggruppa per..." + +#. module: fastapi +#: model:ir.model.fields.selection,name:fastapi.selection__fastapi_endpoint__demo_auth_method__http_basic +msgid "HTTP Basic" +msgstr "Base HTTP" + +#. module: fastapi +#: model:ir.module.category,description:fastapi.module_category_fastapi +msgid "Helps you manage your Fastapi Endpoints" +msgstr "Aiuta nella gestione degli endpoint FastAPI" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__id +msgid "ID" +msgstr "ID" + +#. module: fastapi +#: model:ir.model,name:fastapi.model_res_lang +msgid "Languages" +msgstr "Lingue" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__write_uid +msgid "Last Updated by" +msgstr "Ultimo aggiornamento di" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__write_date +msgid "Last Updated on" +msgstr "Ultimo aggiornamento il" + +#. module: fastapi +#: model:res.groups,name:fastapi.my_demo_app_group +msgid "My Demo Endpoint Group" +msgstr "Il mio gruppo endpoint esempio" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__name +msgid "Name" +msgstr "Nome" + +#. module: fastapi +#: model:ir.model.fields,help:fastapi.field_fastapi_endpoint__registry_sync +msgid "" +"ON: the record has been modified and registry was not notified.\n" +"No change will be active until this flag is set to false via proper action.\n" +"\n" +"OFF: record in line with the registry, nothing to do." +msgstr "" +"Acceso: il record è stato modificato e il registro non è stato notificato.\n" +"Nessuna modifica sarà attiva finchè questa opzione è impostata a falso " +"attraverso un'azione opportuna.\n" +"\n" +"Spento: record allineato con il registro, non c'è niente da fare." + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__openapi_url +msgid "Openapi Url" +msgstr "URL OpenAPI" + +#. module: fastapi +#: model:ir.model,name:fastapi.model_ir_rule +msgid "Record Rule" +msgstr "Regola su record" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__redoc_url +msgid "Redoc Url" +msgstr "URL record" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__registry_sync +msgid "Registry Sync" +msgstr "Sincro registro" + +#. module: fastapi +#: model_terms:ir.ui.view,arch_db:fastapi.fastapi_endpoint_form_view +msgid "Registry Sync Required" +msgstr "Sincro registro richiesto" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__root_path +msgid "Root Path" +msgstr "Percorso radice" + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__save_http_session +msgid "Save HTTP Session" +msgstr "Salva sessione HTTP" + +#. module: fastapi +#: model:ir.actions.server,name:fastapi.fastapi_endpoint_action_sync_registry +#: model_terms:ir.ui.view,arch_db:fastapi.fastapi_endpoint_form_view +#: model_terms:ir.ui.view,arch_db:fastapi.fastapi_endpoint_tree_view +msgid "Sync Registry" +msgstr "Sincronizza registro" + +#. module: fastapi +#. odoo-python +#: code:addons/fastapi/models/fastapi_endpoint_demo.py:0 +#, python-format +msgid "The authentication method is required for app %(app)s" +msgstr "Il metodo di autenticazione è richiesto per l'app %(app)s" + +#. module: fastapi +#: model:ir.model.fields,help:fastapi.field_fastapi_endpoint__name +msgid "The title of the API." +msgstr "Titolo dell'API." + +#. module: fastapi +#: model:ir.model.fields,help:fastapi.field_fastapi_endpoint__user_id +msgid "The user to use to execute the API calls." +msgstr "Utente da utilizzare per eseguire la chiamata API." + +#. module: fastapi +#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__user_id +#: model:res.groups,name:fastapi.group_fastapi_user +msgid "User" +msgstr "Utente" + +#. module: fastapi +#: model:ir.model.fields,help:fastapi.field_fastapi_endpoint__save_http_session +msgid "" +"Whether session should be saved into the session store. This is required if " +"for example you use the Odoo's authentication mechanism. Oherwise chance are " +"high that you don't need it and could turn off this behaviour. Additionaly " +"turning off this option will prevent useless IO operation when storing and " +"reading the session on the disk and prevent unexpecteed disk space " +"consumption." +msgstr "" +"Se la sessione deve essere salvata nell'archivio sessioni. Questo è " +"necessario se, ad esempio, si utilizza il meccanismo di autenticazione di " +"Odoo. In caso contrario, è probabile che non se ne abbia bisogno e si può " +"disattivare questo comportamento. Inoltre, disattivando questa opzione si " +"impediranno operazioni di I/O inutili durante l'archiviazione e la lettura " +"della sessione sul disco e si impedirà un consumo inaspettato di spazio su " +"disco." + +#. module: fastapi +#. odoo-python +#: code:addons/fastapi/models/fastapi_endpoint.py:0 +#, python-format +msgid "`%(name)s` uses a blacklisted root_path = `%(root_path)s`" +msgstr "`%(name)s` utilizza un root_path bloccato = `%(root_path)s`" + +#~ msgid "Last Modified on" +#~ msgstr "Ultima modifica il" diff --git a/fastapi/models/__init__.py b/fastapi/models/__init__.py new file mode 100644 index 000000000..18185a2fd --- /dev/null +++ b/fastapi/models/__init__.py @@ -0,0 +1,4 @@ +from .fastapi_endpoint import FastapiEndpoint +from . import fastapi_endpoint_demo +from . import ir_rule +from . import res_lang diff --git a/fastapi/models/fastapi_endpoint.py b/fastapi/models/fastapi_endpoint.py new file mode 100644 index 000000000..b77bf5141 --- /dev/null +++ b/fastapi/models/fastapi_endpoint.py @@ -0,0 +1,277 @@ +# Copyright 2022 ACSONE SA/NV +# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL). + +import logging +from collections.abc import Callable +from functools import partial +from itertools import chain +from typing import Any + +from a2wsgi import ASGIMiddleware +from starlette.middleware import Middleware +from starlette.routing import Mount + +from odoo import _, api, exceptions, fields, models, tools + +from fastapi import APIRouter, Depends, FastAPI + +from .. import dependencies + +_logger = logging.getLogger(__name__) + + +class FastapiEndpoint(models.Model): + _name = "fastapi.endpoint" + _inherit = "endpoint.route.sync.mixin" + _description = "FastAPI Endpoint" + + name: str = fields.Char(required=True, help="The title of the API.") + description: str = fields.Text( + help="A short description of the API. It can use Markdown" + ) + root_path: str = fields.Char( + required=True, + index=True, + compute="_compute_root_path", + inverse="_inverse_root_path", + readonly=False, + store=True, + copy=False, + ) + app: str = fields.Selection(selection=[], required=True) + user_id = fields.Many2one( + comodel_name="res.users", + string="User", + help="The user to use to execute the API calls.", + default=lambda self: self.env.ref("base.public_user"), + ) + docs_url: str = fields.Char(compute="_compute_urls") + redoc_url: str = fields.Char(compute="_compute_urls") + openapi_url: str = fields.Char(compute="_compute_urls") + company_id = fields.Many2one( + "res.company", + compute="_compute_company_id", + store=True, + readonly=False, + domain="[('user_ids', 'in', user_id)]", + ) + save_http_session = fields.Boolean( + string="Save HTTP Session", + help="Whether session should be saved into the session store. This is " + "required if for example you use the Odoo's authentication mechanism. " + "Oherwise chance are high that you don't need it and could turn off " + "this behaviour. Additionaly turning off this option will prevent useless " + "IO operation when storing and reading the session on the disk and prevent " + "unexpecteed disk space consumption.", + default=True, + ) + + @api.depends("root_path") + def _compute_root_path(self): + for rec in self: + rec.root_path = rec._clean_root_path() + + def _inverse_root_path(self): + for rec in self: + rec.root_path = rec._clean_root_path() + + def _clean_root_path(self): + root_path = (self.root_path or "").strip() + if not root_path.startswith("/"): + root_path = "/" + root_path + return root_path + + _blacklist_root_paths = {"/", "/web", "/website"} + + @api.constrains("root_path") + def _check_root_path(self): + for rec in self: + if rec.root_path in self._blacklist_root_paths: + raise exceptions.UserError( + _( + "`%(name)s` uses a blacklisted root_path = `%(root_path)s`", + name=rec.name, + root_path=rec.root_path, + ) + ) + + @api.depends("root_path") + def _compute_urls(self): + for rec in self: + rec.docs_url = f"{rec.root_path}/docs" + rec.redoc_url = f"{rec.root_path}/redoc" + rec.openapi_url = f"{rec.root_path}/openapi.json" + + @api.depends("user_id") + def _compute_company_id(self): + for endpoint in self: + endpoint.company_id = endpoint.user_id.company_id + + # + # endpoint.route.sync.mixin methods implementation + # + def _prepare_endpoint_rules(self, options=None): + return [rec._make_routing_rule(options=options) for rec in self] + + def _registered_endpoint_rule_keys(self): + res = [] + for rec in self: + routing = rec._get_routing_info() + res.append(rec._endpoint_registry_route_unique_key(routing)) + return tuple(res) + + @api.model + def _routing_impacting_fields(self) -> tuple[str]: + """The list of fields requiring to refresh the mount point of the pp + into odoo if modified""" + return ("root_path",) + + # + # end of endpoint.route.sync.mixin methods implementation + # + + def write(self, vals): + res = super().write(vals) + self._handle_route_updates(vals) + return res + + def action_sync_registry(self): + self.filtered(lambda e: not e.registry_sync).write({"registry_sync": True}) + + def _handle_route_updates(self, vals): + observed_fields = [self._routing_impacting_fields(), self._fastapi_app_fields()] + refresh_fastapi_app = any([x in vals for x in chain(*observed_fields)]) + if refresh_fastapi_app: + self._reset_app() + if "user_id" in vals: + self.env.registry.clear_cache() + return False + + @api.model + def _fastapi_app_fields(self) -> list[str]: + """The list of fields requiring to refresh the fastapi app if modified""" + return [] + + def _make_routing_rule(self, options=None): + """Generator of rule""" + self.ensure_one() + routing = self._get_routing_info() + options = options or self._default_endpoint_options() + route = "|".join(routing["routes"]) + key = self._endpoint_registry_route_unique_key(routing) + endpoint_hash = hash(route) + return self._endpoint_registry.make_rule( + key, route, options, routing, endpoint_hash + ) + + def _default_endpoint_options(self): + options = {"handler": self._default_endpoint_options_handler()} + return options + + def _default_endpoint_options_handler(self): + # The handler is useless in the context of a fastapi endpoint since the + # routing type is "fastapi" and the routing is handled by a dedicated + # dispatcher that will forward the request to the fastapi app. + base_path = "odoo.addons.endpoint_route_handler.controllers.main" + return { + "klass_dotted_path": f"{base_path}.EndpointNotFoundController", + "method_name": "auto_not_found", + } + + def _get_routing_info(self): + self.ensure_one() + return { + "type": "fastapi", + "auth": "public", + "methods": ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"], + "routes": [ + f"{self.root_path}/", + f"{self.root_path}/", + ], + "save_session": self.save_http_session, + "readonly": False, + # csrf ????? + } + + def _endpoint_registry_route_unique_key(self, routing: dict[str, Any]): + route = "|".join(routing["routes"]) + path = route.replace(self.root_path, "") + return f"{self._name}:{self.id}:{path}" + + def _reset_app(self): + self.env.registry.clear_cache() + + @api.model + @tools.ormcache("root_path") + # TODO cache on thread local by db to enable to get 1 middelware by + # thread when odoo runs in multi threads mode and to allows invalidate + # specific entries in place og the overall cache as we have to do into + # the _rest_app method + def get_app(self, root_path): + record = self.search([("root_path", "=", root_path)]) + if not record: + return None + app = FastAPI() + app.mount(record.root_path, record._get_app()) + self._clear_fastapi_exception_handlers(app) + return ASGIMiddleware(app) + + def _clear_fastapi_exception_handlers(self, app: FastAPI) -> None: + """ + Clear the exception handlers of the given fastapi app. + + This method is used to ensure that the exception handlers are handled + by odoo and not by fastapi. We therefore need to remove all the handlers + added by default when instantiating a FastAPI app. Since apps can be + mounted recursively, we need to apply this method to all the apps in the + mounted tree. + """ + app.exception_handlers = {} + for route in app.routes: + if isinstance(route, Mount): + self._clear_fastapi_exception_handlers(route.app) + + @api.model + @tools.ormcache("root_path") + def get_uid(self, root_path): + record = self.search([("root_path", "=", root_path)]) + if not record: + return None + return record.user_id.id + + def _get_app(self) -> FastAPI: + app = FastAPI(**self._prepare_fastapi_app_params()) + for router in self._get_fastapi_routers(): + app.include_router(router=router) + app.dependency_overrides.update(self._get_app_dependencies_overrides()) + return app + + def _get_app_dependencies_overrides(self) -> dict[Callable, Callable]: + return { + dependencies.fastapi_endpoint_id: partial(lambda a: a, self.id), + dependencies.company_id: partial(lambda a: a, self.company_id.id), + } + + def _prepare_fastapi_app_params(self) -> dict[str, Any]: + """Return the params to pass to the Fast API app constructor""" + return { + "title": self.name, + "description": self.description, + "middleware": self._get_fastapi_app_middlewares(), + "dependencies": self._get_fastapi_app_dependencies(), + } + + def _get_fastapi_routers(self) -> list[APIRouter]: + """Return the api routers to use for the instance. + + This method must be implemented when registering a new api type. + """ + return [] + + def _get_fastapi_app_middlewares(self) -> list[Middleware]: + """Return the middlewares to use for the fastapi app.""" + return [] + + def _get_fastapi_app_dependencies(self) -> list[Depends]: + """Return the dependencies to use for the fastapi app.""" + return [Depends(dependencies.accept_language)] diff --git a/fastapi/models/fastapi_endpoint_demo.py b/fastapi/models/fastapi_endpoint_demo.py new file mode 100644 index 000000000..cf3df84c1 --- /dev/null +++ b/fastapi/models/fastapi_endpoint_demo.py @@ -0,0 +1,104 @@ +# Copyright 2022 ACSONE SA/NV +# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL). +from typing import Annotated, Any + +from odoo import _, api, fields, models +from odoo.api import Environment +from odoo.exceptions import ValidationError + +from odoo.addons.base.models.res_partner import Partner + +from fastapi import APIRouter, Depends, HTTPException, status +from fastapi.security import APIKeyHeader + +from ..dependencies import ( + authenticated_partner_from_basic_auth_user, + authenticated_partner_impl, + odoo_env, +) +from ..routers import demo_router, demo_router_doc + + +class FastapiEndpoint(models.Model): + _inherit = "fastapi.endpoint" + + app: str = fields.Selection( + selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"} + ) + demo_auth_method = fields.Selection( + selection=[("api_key", "Api Key"), ("http_basic", "HTTP Basic")], + string="Authenciation method", + ) + + def _get_fastapi_routers(self) -> list[APIRouter]: + if self.app == "demo": + return [demo_router] + return super()._get_fastapi_routers() + + @api.constrains("app", "demo_auth_method") + def _valdiate_demo_auth_method(self): + for rec in self: + if rec.app == "demo" and not rec.demo_auth_method: + raise ValidationError( + _( + "The authentication method is required for app %(app)s", + app=rec.app, + ) + ) + + @api.model + def _fastapi_app_fields(self) -> list[str]: + fields = super()._fastapi_app_fields() + fields.append("demo_auth_method") + return fields + + def _get_app(self): + app = super()._get_app() + if self.app == "demo": + # Here we add the overrides to the authenticated_partner_impl method + # according to the authentication method configured on the demo app + if self.demo_auth_method == "http_basic": + authenticated_partner_impl_override = ( + authenticated_partner_from_basic_auth_user + ) + else: + authenticated_partner_impl_override = ( + api_key_based_authenticated_partner_impl + ) + app.dependency_overrides[authenticated_partner_impl] = ( + authenticated_partner_impl_override + ) + return app + + def _prepare_fastapi_app_params(self) -> dict[str, Any]: + params = super()._prepare_fastapi_app_params() + if self.app == "demo": + tags_metadata = params.get("openapi_tags", []) or [] + tags_metadata.append({"name": "demo", "description": demo_router_doc}) + params["openapi_tags"] = tags_metadata + return params + + +def api_key_based_authenticated_partner_impl( + api_key: Annotated[ + str, + Depends( + APIKeyHeader( + name="api-key", + description="In this demo, you can use a user's login as api key.", + ) + ), + ], + env: Annotated[Environment, Depends(odoo_env)], +) -> Partner: + """A dummy implementation that look for a user with the same login + as the provided api key + """ + partner = ( + env["res.users"].sudo().search([("login", "=", api_key)], limit=1).partner_id + ) + if not partner: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect API Key" + ) + return partner diff --git a/fastapi/models/ir_rule.py b/fastapi/models/ir_rule.py new file mode 100644 index 000000000..68bda16f6 --- /dev/null +++ b/fastapi/models/ir_rule.py @@ -0,0 +1,27 @@ +# Copyright 2022 ACSONE SA/NV +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). + +from odoo import api, models + + +class IrRule(models.Model): + """Add authenticated_partner_id in record rule evaluation context. + + This come from the env current odoo environment which is + populated by dependency method authenticated_partner_env or authenticated_partner + when a route handler depends one of them and is called by the FastAPI service layer. + """ + + _inherit = "ir.rule" + + @api.model + def _eval_context(self): + ctx = super()._eval_context() + ctx["authenticated_partner_id"] = self.env.context.get( + "authenticated_partner_id", False + ) + return ctx + + def _compute_domain_keys(self): + """Return the list of context keys to use for caching ``_compute_domain``.""" + return super()._compute_domain_keys() + ["authenticated_partner_id"] diff --git a/fastapi/models/res_lang.py b/fastapi/models/res_lang.py new file mode 100644 index 000000000..55453c405 --- /dev/null +++ b/fastapi/models/res_lang.py @@ -0,0 +1,46 @@ +# Copyright 2023 ACSONE SA/NV +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from collections import defaultdict + +from accept_language import parse_accept_language + +from odoo import api, models, tools + + +class ResLang(models.Model): + _inherit = "res.lang" + + @api.model + @tools.ormcache("accept_language") + def _get_lang_from_accept_language(self, accept_language): + """Get the language from the Accept-Language header. + + :param accept_language: The Accept-Language header. + :return: The language code. + """ + if not accept_language: + return + parsed_accepted_langs = parse_accept_language(accept_language) + installed_locale_langs = set() + installed_locale_by_lang = defaultdict(list) + for lang_code, _name in self.get_installed(): + installed_locale_langs.add(lang_code) + installed_locale_by_lang[lang_code.split("_")[0]].append(lang_code) + + # parsed_acccepted_langs is sorted by priority (higher first) + for lang in parsed_accepted_langs: + # we first check if a locale (en_GB) is available into the list of + # available locales into Odoo + locale = None + if lang.locale in installed_locale_langs: + locale = lang.locale + # if no locale language is installed, we look for an available + # locale for the given language (en). We return the first one + # found for this language. + else: + locales = installed_locale_by_lang.get(lang.language) + if locales: + locale = locales[0] + if locale: + return locale diff --git a/fastapi/pyproject.toml b/fastapi/pyproject.toml new file mode 100644 index 000000000..4231d0ccc --- /dev/null +++ b/fastapi/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["whool"] +build-backend = "whool.buildapi" diff --git a/fastapi/readme/CONTRIBUTORS.md b/fastapi/readme/CONTRIBUTORS.md new file mode 100644 index 000000000..f2af9193c --- /dev/null +++ b/fastapi/readme/CONTRIBUTORS.md @@ -0,0 +1 @@ +- Laurent Mignon \<\> diff --git a/fastapi/readme/DESCRIPTION.md b/fastapi/readme/DESCRIPTION.md new file mode 100644 index 000000000..d0261086d --- /dev/null +++ b/fastapi/readme/DESCRIPTION.md @@ -0,0 +1,41 @@ +This addon provides the basis to smoothly integrate the +[FastAPI](https://fastapi.tiangolo.com/) framework into Odoo. + +This integration allows you to use all the goodies from +[FastAPI](https://fastapi.tiangolo.com/) to build custom APIs for your +Odoo server based on standard Python type hints. + +**What is building an API?** + +An API is a set of functions that can be called from the outside world. +The goal of an API is to provide a way to interact with your application +from the outside world without having to know how it works internally. A +common mistake when you are building an API is to expose all the +internal functions of your application and therefore create a tight +coupling between the outside world and your internal datamodel and +business logic. This is not a good idea because it makes it very hard to +change your internal datamodel and business logic without breaking the +outside world. + +When you are building an API, you define a contract between the outside +world and your application. This contract is defined by the functions +that you expose and the parameters that you accept. This contract is the +API. When you change your internal datamodel and business logic, you can +still keep the same API contract and therefore you don't break the +outside world. Even if you change your implementation, as long as you +keep the same API contract, the outside world will still work. This is +the beauty of an API and this is why it is so important to design a good +API. + +A good API is designed to be stable and to be easy to use. It's designed +to provide high-level functions related to a specific use case. It's +designed to be easy to use by hiding the complexity of the internal +datamodel and business logic. A common mistake when you are building an +API is to expose all the internal functions of your application and let +the oustide world deal with the complexity of your internal datamodel +and business logic. Don't forget that on a transactional point of view, +each call to an API function is a transaction. This means that if a +specific use case requires multiple calls to your API, you should +provide a single function that does all the work in a single +transaction. This why APIs methods are called high-level and atomic +functions. diff --git a/fastapi/readme/HISTORY.md b/fastapi/readme/HISTORY.md new file mode 100644 index 000000000..95723e1d5 --- /dev/null +++ b/fastapi/readme/HISTORY.md @@ -0,0 +1,119 @@ +## 17.0.3.0.0 (2024-10-03) + +### Features + +- * A new parameter is now available on the endpoint model to let you disable the creation and the store of session files used by Odoo for calls to your application endpoint. This is usefull to prevent disk space consumption and IO operations if your application doesn't need to use this sessions files which are mainly used by Odoo by to store the session info of logged in users. ([#442](https://github.com/OCA/rest-framework/issues/442)) + +### Bugfixes + +- Fix issue with the retry of a POST request with a body content. + + Prior to this fix the retry of a POST request with a body content would + stuck in a loop and never complete. This was due to the fact that the + request input stream was not reset after a failed attempt to process the + request. ([#440](https://github.com/OCA/rest-framework/issues/440)) + + +## 17.0.2.0.0 (2024-10-03) + +### Bugfixes + +- This change is a complete rewrite of the way the transactions are managed when + integrating a fastapi application into Odoo. + + In the previous implementation, specifics error handlers were put in place to + catch exception occurring in the handling of requests made to a fastapi application + and to rollback the transaction in case of error. This was done by registering + specifics error handlers methods to the fastapi application using the 'add_exception_handler' + method of the fastapi application. In this implementation, the transaction was + rolled back in the error handler method. + + This approach was not working as expected for several reasons: + + - The handling of the error at the fastapi level prevented the retry mechanism + to be triggered in case of a DB concurrency error. This is because the error + was catch at the fastapi level and never bubbled up to the early stage of the + processing of the request where the retry mechanism is implemented. + - The cleanup of the environment and the registry was not properly done in case + of error. In the **'odoo.service.model.retrying'** method, you can see that + the cleanup process is different in case of error raised by the database + and in case of error raised by the application. + + This change fix these issues by ensuring that errors are no more catch at the + fastapi level and bubble up the fastapi processing stack through the event loop + required to transform WSGI to ASGI. As result the transactional nature of the + requests to the fastapi applications is now properly managed by the Odoo framework. + + ([#422](https://github.com/OCA/rest-framework/issues/422)) + + +## 17.0.1.0.1 (2024-10-02) + +### Bugfixes + +- Fix compatibility issues with the latest Odoo version + + From https://github.com/odoo/odoo/commit/cb1d057dcab28cb0b0487244ba99231ee292502e + the original werkzeug HTTPRequest class has been wrapped in a new class to keep + under control the attributes developers use. This changes take care of this + new implementation but also keep compatibility with the old ones. ([#414](https://github.com/OCA/rest-framework/issues/414)) + + +## 16.0.1.2.5 (2024-01-17) + +### Bugfixes + +- Odoo has done an update and now, it checks domains of ir.rule on creation and + modification. + + The ir.rule 'Fastapi: Running user rule' uses a field (authenticate*partner_id) that + comes from the context. This field wasn't always set and this caused an error when + Odoo checked the domain. So now it is set to *False* by default. + (`#410 `*) + +## 16.0.1.2.3 (2023-12-21) + +### Bugfixes + +- In case of exception in endpoint execution, close the database cursor after rollback. + + This is to ensure that the _retrying_ method in _service/model.py_ does not try to + flush data to the database. + ([\#405](https://github.com/OCA/rest-framework/issues/405)) + +## 16.0.1.2.2 (2023-12-12) + +### Bugfixes + +- When using the 'FastAPITransactionCase' class, allows to specify a specific override + of the 'authenticated_partner_impl' method into the list of overrides to apply. Before + this change, the 'authenticated_partner_impl' override given in the 'overrides' + parameter was always overridden in the '\_create_test_client' method of the + 'FastAPITransactionCase' class. It's now only overridden if the + 'authenticated_partner_impl' method is not already present in the list of overrides to + apply and no specific partner is given. If a specific partner is given at same time of + an override for the 'authenticated_partner_impl' method, an error is raised. + ([\#396](https://github.com/OCA/rest-framework/issues/396)) + +## 16.0.1.2.1 (2023-11-03) + +### Bugfixes + +- Fix a typo in the Field declaration of the 'count' attribute of the 'PagedCollection' + schema. + + Misspelt parameter was triggering a deprecation warning due to recent versions of + Pydantic seeing it as an arbitrary parameter. + ([\#389](https://github.com/OCA/rest-framework/issues/389)) + +## 16.0.1.2.0 (2023-10-13) + +### Features + +- The field _total_ in the _PagedCollection_ schema is replaced by the field _count_. + The field _total_ is now deprecated and will be removed in the next major version. + This change is backward compatible. The json document returned will now contain both + fields _total_ and _count_ with the same value. In your python code the field _total_, + if used, will fill the field _count_ with the same value. You are encouraged to use + the field _count_ instead of _total_ and adapt your code accordingly. + ([\#380](https://github.com/OCA/rest-framework/issues/380)) diff --git a/fastapi/readme/ROADMAP.md b/fastapi/readme/ROADMAP.md new file mode 100644 index 000000000..4541abb75 --- /dev/null +++ b/fastapi/readme/ROADMAP.md @@ -0,0 +1,13 @@ +The +[roadmap](https://github.com/OCA/rest-framework/issues?q=is%3Aopen+is%3Aissue+label%3Aenhancement+label%3Afastapi) +and [known +issues](https://github.com/OCA/rest-framework/issues?q=is%3Aopen+is%3Aissue+label%3Abug+label%3Afastapi) +can be found on GitHub. + +The **FastAPI** module provides an easy way to use WebSockets. +Unfortunately, this support is not 'yet' available in the **Odoo** +framework. The challenge is high because the integration of the fastapi +is based on the use of a specific middleware that convert the WSGI +request consumed by odoo to a ASGI request. The question is to know if +it is also possible to develop the same kind of bridge for the +WebSockets and to stream large responses. diff --git a/fastapi/readme/USAGE.md b/fastapi/readme/USAGE.md new file mode 100644 index 000000000..131d7f7b5 --- /dev/null +++ b/fastapi/readme/USAGE.md @@ -0,0 +1,1349 @@ +## What's building an API with fastapi? + +FastAPI is a modern, fast (high-performance), web framework for building +APIs with Python 3.7+ based on standard Python type hints. This addons +let's you keep advantage of the fastapi framework and use it with Odoo. + +Before you start, we must define some terms: + +- **App**: A FastAPI app is a collection of routes, dependencies, and + other components that can be used to build a web application. +- **Router**: A router is a collection of routes that can be mounted in + an app. +- **Route**: A route is a mapping between an HTTP method and a path, and + defines what should happen when the user requests that path. +- **Dependency**: A dependency is a callable that can be used to get + some information from the user request, or to perform some actions + before the request handler is called. +- **Request**: A request is an object that contains all the information + sent by the user's browser as part of an HTTP request. +- **Response**: A response is an object that contains all the + information that the user's browser needs to build the result page. +- **Handler**: A handler is a function that takes a request and returns + a response. +- **Middleware**: A middleware is a function that takes a request and a + handler, and returns a response. + +The FastAPI framework is based on the following principles: + +- **Fast**: Very high performance, on par with NodeJS and Go (thanks to + Starlette and Pydantic). \[One of the fastest Python frameworks + available\] +- **Fast to code**: Increase the speed to develop features by about 200% + to 300%. +- **Fewer bugs**: Reduce about 40% of human (developer) induced errors. +- **Intuitive**: Great editor support. Completion everywhere. Less time + debugging. +- **Easy**: Designed to be easy to use and learn. Less time reading + docs. +- **Short**: Minimize code duplication. Multiple features from each + parameter declaration. Fewer bugs. +- **Robust**: Get production-ready code. With automatic interactive + documentation. +- **Standards-based**: Based on (and fully compatible with) the open + standards for APIs: OpenAPI (previously known as Swagger) and JSON + Schema. +- **Open Source**: FastAPI is fully open-source, under the MIT license. + +The first step is to install the fastapi addon. You can do it with the +following command: + +> \$ pip install odoo-addon-fastapi + +Once the addon is installed, you can start building your API. The first +thing you need to do is to create a new addon that depends on 'fastapi'. +For example, let's create an addon called *my_demo_api*. + +Then, you need to declare your app by defining a model that inherits +from 'fastapi.endpoint' and add your app name into the app field. For +example: + +``` python +from odoo import fields, models + +class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + app: str = fields.Selection( + selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"} + ) +``` + +The **'fastapi.endpoint'** model is the base model for all the +endpoints. An endpoint instance is the mount point for a fastapi app +into Odoo. When you create a new endpoint, you can define the app that +you want to mount in the **'app'** field and the path where you want to +mount it in the **'path'** field. + +figure:: static/description/endpoint_create.png + +> FastAPI Endpoint + +Thanks to the **'fastapi.endpoint'** model, you can create as many +endpoints as you want and mount as many apps as you want in each +endpoint. The endpoint is also the place where you can define +configuration parameters for your app. A typical example is the +authentication method that you want to use for your app when accessed at +the endpoint path. + +Now, you can create your first router. For that, you need to define a +global variable into your fastapi_endpoint module called for example +'demo_api_router' + +``` python +from fastapi import APIRouter +from odoo import fields, models + +class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + app: str = fields.Selection( + selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"} + ) + +# create a router +demo_api_router = APIRouter() +``` + +To make your router available to your app, you need to add it to the +list of routers returned by the **\_get_fastapi_routers** method of your +fastapi_endpoint model. + +``` python +from fastapi import APIRouter +from odoo import api, fields, models + +class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + app: str = fields.Selection( + selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"} + ) + + def _get_fastapi_routers(self): + if self.app == "demo": + return [demo_api_router] + return super()._get_fastapi_routers() + +# create a router +demo_api_router = APIRouter() +``` + +Now, you can start adding routes to your router. For example, let's add +a route that returns a list of partners. + +``` python +from typing import Annotated + +from fastapi import APIRouter +from pydantic import BaseModel + +from odoo import api, fields, models +from odoo.api import Environment + +from odoo.addons.fastapi.dependencies import odoo_env + +class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + app: str = fields.Selection( + selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"} + ) + + def _get_fastapi_routers(self): + if self.app == "demo": + return [demo_api_router] + return super()._get_fastapi_routers() + +# create a router +demo_api_router = APIRouter() + +class PartnerInfo(BaseModel): + name: str + email: str + +@demo_api_router.get("/partners", response_model=list[PartnerInfo]) +def get_partners(env: Annotated[Environment, Depends(odoo_env)]) -> list[PartnerInfo]: + return [ + PartnerInfo(name=partner.name, email=partner.email) + for partner in env["res.partner"].search([]) + ] +``` + +Now, you can start your Odoo server, install your addon and create a new +endpoint instance for your app. Once it's done click on the docs url to +access the interactive documentation of your app. + +Before trying to test your app, you need to define on the endpoint +instance the user that will be used to run the app. You can do it by +setting the **'user_id'** field. This information is the most important +one because it's the basis for the security of your app. The user that +you define in the endpoint instance will be used to run the app and to +access the database. This means that the user will be able to access all +the data that he has access to in Odoo. To ensure the security of your +app, you should create a new user that will be used only to run your app +and that will have no access to the database. + +``` xml + + My Demo Endpoint User + my_demo_app_user + + +``` + +At the same time you should create a new group that will be used to +define the access rights of the user that will run your app. This group +should imply the predefined group **'FastAPI Endpoint Runner'**. This +group defines the minimum access rights that the user needs to: + +- access the endpoint instance it belongs to +- access to its own user record +- access to the partner record that is linked to its user record + +``` xml + + My Demo Endpoint Group + + + +``` + +Now, you can test your app. You can do it by clicking on the 'Try it +out' button of the route that you have defined. The result of the +request will be displayed in the 'Response' section and contains the +list of partners. + +Note + +The **'FastAPI Endpoint Runner'** group ensures that the user cannot +access any information others than the 3 ones mentioned above. This +means that for every information that you want to access from your app, +you need to create the proper ACLs and record rules. (see [Managing +security into the route +handlers](#managing-security-into-the-route-handlers)) It's a good +practice to use a dedicated user into a specific group from the +beginning of your project and in your tests. This will force you to +define the proper security rules for your endoints. + +## Dealing with the odoo environment + +The **'odoo.addons.fastapi.dependencies'** module provides a set of +functions that you can use to inject reusable dependencies into your +routes. For example, the **'odoo_env'** function returns the current +odoo environment. You can use it to access the odoo models and the +database from your route handlers. + +``` python +from typing import Annotated + +from odoo.api import Environment +from odoo.addons.fastapi.dependencies import odoo_env + +@demo_api_router.get("/partners", response_model=list[PartnerInfo]) +def get_partners(env: Annotated[Environment, Depends(odoo_env)]) -> list[PartnerInfo]: + return [ + PartnerInfo(name=partner.name, email=partner.email) + for partner in env["res.partner"].search([]) + ] +``` + +As you can see, you can use the **'Depends'** function to inject the +dependency into your route handler. The **'Depends'** function is +provided by the **'fastapi'** framework. You can use it to inject any +dependency into your route handler. As your handler is a python +function, the only way to get access to the odoo environment is to +inject it as a dependency. The fastapi addon provides a set of function +that can be used as dependencies: + +- **'odoo_env'**: Returns the current odoo environment. +- **'fastapi_endpoint'**: Returns the current fastapi endpoint model + instance. +- **'authenticated_partner'**: Returns the authenticated partner. +- **'authenticated_partner_env'**: Returns the current odoo environment + with the authenticated_partner_id into the context. + +By default, the **'odoo_env'** and **'fastapi_endpoint'** dependencies +are available without extra work. + +Note + +Even if 'odoo_env' and 'authenticated_partner_env' returns the current +odoo environment, they are not the same. The 'odoo_env' dependency +returns the environment without any modification while the +'authenticated_partner_env' adds the authenticated partner id into the +context of the environment. As it will be explained in the section +[Managing security into the route +handlers](#managing-security-into-the-route-handlers) dedicated to the +security, the presence of the authenticated partner id into the context +is the key information that will allow you to enforce the security of +your endpoint methods. As consequence, you should always use the +'authenticated_partner_env' dependency instead of the 'odoo_env' +dependency for all the methods that are not public. + +## The dependency injection mechanism + +The **'odoo_env'** dependency relies on a simple implementation that +retrieves the current odoo environment from ContextVar variable +initialized at the start of the request processing by the specific +request dispatcher processing the fastapi requests. + +The **'fastapi_endpoint'** dependency relies on the +'dependency_overrides' mechanism provided by the **'fastapi'** module. +(see the fastapi documentation for more details about the +dependency_overrides mechanism). If you take a look at the current +implementation of the **'fastapi_endpoint'** dependency, you will see +that the method depends of two parameters: **'endpoint_id'** and +**'env'**. Each of these parameters are dependencies themselves. + +``` python +def fastapi_endpoint_id() -> int: + """This method is overriden by default to make the fastapi.endpoint record + available for your endpoint method. To get the fastapi.endpoint record + in your method, you just need to add a dependency on the fastapi_endpoint method + defined below + """ + + +def fastapi_endpoint( + _id: Annotated[int, Depends(fastapi_endpoint_id)], + env: Annotated[Environment, Depends(odoo_env)], +) -> "FastapiEndpoint": + """Return the fastapi.endpoint record""" + return env["fastapi.endpoint"].browse(_id) +``` + +As you can see, one of these dependencies is the +**'fastapi_endpoint_id'** dependency and has no concrete implementation. +This method is used as a contract that must be implemented/provided at +the time the fastapi app is created. Here comes the power of the +dependency_overrides mechanism. + +If you take a look at the **'\_get_app'** method of the +**'FastapiEndpoint'** model, you will see that the +**'fastapi_endpoint_id'** dependency is overriden by registering a +specific method that returns the id of the current fastapi endpoint +model instance for the original method. + +``` python +def _get_app(self) -> FastAPI: + app = FastAPI(**self._prepare_fastapi_endpoint_params()) + for router in self._get_fastapi_routers(): + app.include_router(prefix=self.root_path, router=router) + app.dependency_overrides[dependencies.fastapi_endpoint_id] = partial( + lambda a: a, self.id + ) +``` + +This kind of mechanism is very powerful and allows you to inject any +dependency into your route handlers and moreover, define an abstract +dependency that can be used by any other addon and for which the +implementation could depend on the endpoint configuration. + +## The authentication mechanism + +To make our app not tightly coupled with a specific authentication +mechanism, we will use the **'authenticated_partner'** dependency. As +for the **'fastapi_endpoint'** this dependency depends on an abstract +dependency. + +When you define a route handler, you can inject the +**'authenticated_partner'** dependency as a parameter of your route +handler. + +``` python +from odoo.addons.base.models.res_partner import Partner + + +@demo_api_router.get("/partners", response_model=list[PartnerInfo]) +def get_partners( + env: Annotated[Environment, Depends(odoo_env)], partner: Annotated[Partner, Depends(authenticated_partner)] +) -> list[PartnerInfo]: + return [ + PartnerInfo(name=partner.name, email=partner.email) + for partner in env["res.partner"].search([]) + ] +``` + +At this stage, your handler is not tied to a specific authentication +mechanism but only expects to get a partner as a dependency. Depending +on your needs, you can implement different authentication mechanism +available for your app. The fastapi addon provides a default +authentication mechanism using the 'BasicAuth' method. This +authentication mechanism is implemented in the +**'odoo.addons.fastapi.dependencies'** module and relies on +functionalities provided by the **'fastapi.security'** module. + +``` python +def authenticated_partner( + env: Annotated[Environment, Depends(odoo_env)], + security: Annotated[HTTPBasicCredentials, Depends(HTTPBasic())], +) -> "res.partner": + """Return the authenticated partner""" + partner = env["res.partner"].search( + [("email", "=", security.username)], limit=1 + ) + if not partner: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid authentication credentials", + headers={"WWW-Authenticate": "Basic"}, + ) + if not partner.check_password(security.password): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid authentication credentials", + headers={"WWW-Authenticate": "Basic"}, + ) + return partner +``` + +As you can see, the **'authenticated_partner'** dependency relies on the +**'HTTPBasic'** dependency provided by the **'fastapi.security'** +module. In this dummy implementation, we just check that the provided +credentials can be used to authenticate a user in odoo. If the +authentication is successful, we return the partner record linked to the +authenticated user. + +In some cases you could want to implement a more complex authentication +mechanism that could rely on a token or a session. In this case, you can +override the **'authenticated_partner'** dependency by registering a +specific method that returns the authenticated partner. Moreover, you +can make it configurable on the fastapi endpoint model instance. + +To do it, you just need to implement a specific method for each of your +authentication mechanism and allows the user to select one of these +methods when he creates a new fastapi endpoint. Let's say that we want +to allow the authentication by using an api key or via basic auth. Since +basic auth is already implemented, we will only implement the api key +authentication mechanism. + +``` python +from fastapi.security import APIKeyHeader + +def api_key_based_authenticated_partner_impl( + api_key: Annotated[str, Depends( + APIKeyHeader( + name="api-key", + description="In this demo, you can use a user's login as api key.", + ) + )], + env: Annotated[Environment, Depends(odoo_env)], +) -> Partner: + """A dummy implementation that look for a user with the same login + as the provided api key + """ + partner = env["res.users"].search([("login", "=", api_key)], limit=1).partner_id + if not partner: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect API Key" + ) + return partner +``` + +As for the 'BasicAuth' authentication mechanism, we also rely on one of +the native security dependency provided by the **'fastapi.security'** +module. + +Now that we have an implementation for our two authentication +mechanisms, we can allows the user to select one of these authentication +mechanisms by adding a selection field on the fastapi endpoint model. + +``` python +from odoo import fields, models + +class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + app: str = fields.Selection( + selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"} + ) + demo_auth_method = fields.Selection( + selection=[("api_key", "Api Key"), ("http_basic", "HTTP Bacic")], + string="Authenciation method", + ) +``` + +Note + +A good practice is to prefix specific configuration fields of your app +with the name of your app. This will avoid conflicts with other app when +the 'fastapi.endpoint' model is extended for other 'app'. + +Now that we have a selection field that allows the user to select the +authentication method, we can use the dependency override mechanism to +provide the right implementation of the **'authenticated_partner'** +dependency when the app is instantiated. + +``` python +from odoo.addons.fastapi.dependencies import authenticated_partner +class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + app: str = fields.Selection( + selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"} + ) + demo_auth_method = fields.Selection( + selection=[("api_key", "Api Key"), ("http_basic", "HTTP Bacic")], + string="Authenciation method", + ) + + def _get_app(self) -> FastAPI: + app = super()._get_app() + if self.app == "demo": + # Here we add the overrides to the authenticated_partner_impl method + # according to the authentication method configured on the demo app + if self.demo_auth_method == "http_basic": + authenticated_partner_impl_override = ( + authenticated_partner_from_basic_auth_user + ) + else: + authenticated_partner_impl_override = ( + api_key_based_authenticated_partner_impl + ) + app.dependency_overrides[ + authenticated_partner_impl + ] = authenticated_partner_impl_override + return app +``` + +To see how the dependency override mechanism works, you can take a look +at the demo app provided by the fastapi addon. If you choose the app +'demo' in the fastapi endpoint form view, you will see that the +authentication method is configurable. You can also see that depending +on the authentication method configured on your fastapi endpoint, the +documentation will change. + +Note + +At time of writing, the dependency override mechanism is not supported +by the fastapi documentation generator. A fix has been proposed and is +waiting to be merged. You can follow the progress of the fix on +[github](https://github.com/tiangolo/fastapi/pull/5452) + +## Managing configuration parameters for your app + +As we have seen in the previous section, you can add configuration +fields on the fastapi endpoint model to allow the user to configure your +app (as for any odoo model you extend). When you need to access these +configuration fields in your route handlers, you can use the +**'odoo.addons.fastapi.dependencies.fastapi_endpoint'** dependency +method to retrieve the 'fastapi.endpoint' record associated to the +current request. + +``` python +from pydantic import BaseModel, Field +from odoo.addons.fastapi.dependencies import fastapi_endpoint + +class EndpointAppInfo(BaseModel): + id: str + name: str + app: str + auth_method: str = Field(alias="demo_auth_method") + root_path: str + model_config = ConfigDict(from_attributes=True) + + + @demo_api_router.get( + "/endpoint_app_info", + response_model=EndpointAppInfo, + dependencies=[Depends(authenticated_partner)], + ) + async def endpoint_app_info( + endpoint: Annotated[FastapiEndpoint, Depends(fastapi_endpoint)], + ) -> EndpointAppInfo: + """Returns the current endpoint configuration""" + # This method show you how to get access to current endpoint configuration + # It also show you how you can specify a dependency to force the security + # even if the method doesn't require the authenticated partner as parameter + return EndpointAppInfo.model_validate(endpoint) +``` + +Some of the configuration fields of the fastapi endpoint could impact +the way the app is instantiated. For example, in the previous section, +we have seen that the authentication method configured on the +'fastapi.endpoint' record is used in order to provide the right +implementation of the **'authenticated_partner'** when the app is +instantiated. To ensure that the app is re-instantiated when an element +of the configuration used in the instantiation of the app is modified, +you must override the **'\_fastapi_app_fields'** method to add the name +of the fields that impact the instantiation of the app into the returned +list. + +``` python +class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + app: str = fields.Selection( + selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"} + ) + demo_auth_method = fields.Selection( + selection=[("api_key", "Api Key"), ("http_basic", "HTTP Bacic")], + string="Authenciation method", + ) + + @api.model + def _fastapi_app_fields(self) -> List[str]: + fields = super()._fastapi_app_fields() + fields.append("demo_auth_method") + return fields +``` + +## Dealing with languages + +The fastapi addon parses the Accept-Language header of the request to +determine the language to use. This parsing is done by respecting the +[RFC 7231 +specification](https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.5). +That means that the language is determined by the first language found +in the header that is supported by odoo (with care of the priority +order). If no language is found in the header, the odoo default language +is used. This language is then used to initialize the Odoo's environment +context used by the route handlers. All this makes the management of +languages very easy. You don't have to worry about. This feature is also +documented by default into the generated openapi documentation of your +app to instruct the api consumers how to request a specific language. + +## How to extend an existing app + +When you develop a fastapi app, in a native python app it's not possible +to extend an existing one. This limitation doesn't apply to the fastapi +addon because the fastapi endpoint model is designed to be extended. +However, the way to extend an existing app is not the same as the way to +extend an odoo model. + +First of all, it's important to keep in mind that when you define a +route, you are actually defining a contract between the client and the +server. This contract is defined by the route path, the method (GET, +POST, PUT, DELETE, etc.), the parameters and the response. If you want +to extend an existing app, you must ensure that the contract is not +broken. Any change to the contract will respect the [Liskov substitution +principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle). +This means that the client should not be impacted by the change. + +What does it mean in practice? It means that you can't change the route +path or the method of an existing route. You can't change the name of a +parameter or the type of a response. You can't add a new parameter or a +new response. You can't remove a parameter or a response. If you want to +change the contract, you must create a new route. + +What can you change? + +- You can change the implementation of the route handler. +- You can override the dependencies of the route handler. +- You can add a new route handler. +- You can extend the model used as parameter or as response of the route + handler. + +Let's see how to do that. + +### Changing the implementation of the route handler + +Let's say that you want to change the implementation of the route +handler **'/demo/echo'**. Since a route handler is just a python method, +it could seems a tedious task since we are not into a model method and +therefore we can't take advantage of the Odoo inheritance mechanism. + +However, the fastapi addon provides a way to do that. Thanks to the +**'odoo_env'** dependency method, you can access the current odoo +environment. With this environment, you can access the registry and +therefore the model you want to delegate the implementation to. If you +want to change the implementation of the route handler **'/demo/echo'**, +the only thing you have to do is to inherit from the model where the +implementation is defined and override the method **'echo'**. + +``` python +from pydantic import BaseModel +from fastapi import Depends, APIRouter +from odoo import models +from odoo.addons.fastapi.dependencies import odoo_env + +class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + def _get_fastapi_routers(self) -> List[APIRouter]: + routers = super()._get_fastapi_routers() + routers.append(demo_api_router) + return routers + +demo_api_router = APIRouter() + +@demo_api_router.get( + "/echo", + response_model=EchoResponse, + dependencies=[Depends(odoo_env)], +) +async def echo( + message: str, + odoo_env: Annotated[Environment, Depends(odoo_env)], +) -> EchoResponse: + """Echo the message""" + return EchoResponse(message=odoo_env["demo.fastapi.endpoint"].echo(message)) + +class EchoResponse(BaseModel): + message: str + +class DemoEndpoint(models.AbstractModel): + + _name = "demo.fastapi.endpoint" + _description = "Demo Endpoint" + + def echo(self, message: str) -> str: + return message + +class DemoEndpointInherit(models.AbstractModel): + + _inherit = "demo.fastapi.endpoint" + + def echo(self, message: str) -> str: + return f"Hello {message}" +``` + +Note + +It's a good programming practice to implement the business logic outside +the route handler. This way, you can easily test your business logic +without having to test the route handler. In the example above, the +business logic is implemented in the method **'echo'** of the model +**'demo.fastapi.endpoint'**. The route handler just delegate the +implementation to this method. + +### Overriding the dependencies of the route handler + +As you've previously seen, the dependency injection mechanism of fastapi +is very powerful. By designing your route handler to rely on +dependencies with a specific functional scope, you can easily change the +implementation of the dependency without having to change the route +handler. With such a design, you can even define abstract dependencies +that must be implemented by the concrete application. This is the case +of the **'authenticated_partner'** dependency in our previous example. +(you can find the implementation of this dependency in the file +**'odoo/addons/fastapi/dependencies.py'** and it's usage in the file +**'odoo/addons/fastapi/models/fastapi_endpoint_demo.py'**) + +### Adding a new route handler + +Let's say that you want to add a new route handler **'/demo/echo2'**. +You could be tempted to add this new route handler in your new addons by +importing the router of the existing app and adding the new route +handler to it. + +``` python +from odoo.addons.fastapi.models.fastapi_endpoint_demo import demo_api_router + +@demo_api_router.get( + "/echo2", + response_model=EchoResponse, + dependencies=[Depends(odoo_env)], +) +async def echo2( + message: str, + odoo_env: Annotated[Environment, Depends(odoo_env)], +) -> EchoResponse: + """Echo the message""" + echo = odoo_env["demo.fastapi.endpoint"].echo2(message) + return EchoResponse(message=f"Echo2: {echo}") +``` + +The problem with this approach is that you unconditionally add the new +route handler to the existing app even if the app is called for a +different database where your new addon is not installed. + +The solution is to define a new router and to add it to the list of +routers returned by the method **'\_get_fastapi_routers'** of the model +**'fastapi.endpoint'** you are inheriting from into your new addon. + +``` python +class FastapiEndpoint(models.Model): + + _inherit = "fastapi.endpoint" + + def _get_fastapi_routers(self) -> List[APIRouter]: + routers = super()._get_fastapi_routers() + if self.app == "demo": + routers.append(additional_demo_api_router) + return routers + +additional_demo_api_router = APIRouter() + +@additional_demo_api_router.get( + "/echo2", + response_model=EchoResponse, + dependencies=[Depends(odoo_env)], +) +async def echo2( + message: str, + odoo_env: Annotated[Environment, Depends(odoo_env)], +) -> EchoResponse: + """Echo the message""" + echo = odoo_env["demo.fastapi.endpoint"].echo2(message) + return EchoResponse(message=f"Echo2: {echo}") +``` + +In this way, the new router is added to the list of routers of your app +only if the app is called for a database where your new addon is +installed. + +### Extending the model used as parameter or as response of the route handler + +The fastapi python library uses the pydantic library to define the +models. By default, once a model is defined, it's not possible to extend +it. However, a companion python library called +[extendable_pydantic](https://pypi.org/project/extendable_pydantic/) +provides a way to use inheritance with pydantic models to extend an +existing model. If used alone, it's your responsibility to instruct this +library the list of extensions to apply to a model and the order to +apply them. This is not very convenient. Fortunately, an dedicated odoo +addon exists to make this process complete transparent. This addon is +called +[odoo-addon-extendable-fastapi](https://pypi.org/project/odoo-addon-extendable-fastapi/). + +When you want to allow other addons to extend a pydantic model, you must +first define the model as an extendable model by using a dedicated +metaclass + +``` python +from pydantic import BaseModel +from extendable_pydantic import ExtendableModelMeta + +class Partner(BaseModel, metaclass=ExtendableModelMeta): + name = 0.1 + model_config = ConfigDict(from_attributes=True) +``` + +As any other pydantic model, you can now use this model as parameter or +as response of a route handler. You can also use all the features of +models defined with pydantic. + +``` python +@demo_api_router.get( + "/partner", + response_model=Location, + dependencies=[Depends(authenticated_partner)], +) +async def partner( + partner: Annotated[ResPartner, Depends(authenticated_partner)], +) -> Partner: + """Return the location""" + return Partner.model_validate(partner) +``` + +If you need to add a new field into the model **'Partner'**, you can +extend it in your new addon by defining a new model that inherits from +the model **'Partner'**. + +``` python +from typing import Optional +from odoo.addons.fastapi.models.fastapi_endpoint_demo import Partner + +class PartnerExtended(Partner, extends=Partner): + email: Optional[str] +``` + +If your new addon is installed in a database, a call to the route +handler **'/demo/partner'** will return a response with the new field +**'email'** if a value is provided by the odoo record. + +``` python +{ + "name": "John Doe", + "email": "jhon.doe@acsone.eu" +} +``` + +If your new addon is not installed in a database, a call to the route +handler **'/demo/partner'** will only return the name of the partner. + +``` python +{ + "name": "John Doe" +} +``` + +Note + +The liskov substitution principle has also to be respected. That means +that if you extend a model, you must add new required fields or you must +provide default values for the new optional fields. + +## Managing security into the route handlers + +By default the route handlers are processed using the user configured on +the **'fastapi.endpoint'** model instance. (default is the Public user). +You have seen previously how to define a dependency that will be used to +enforce the authentication of a partner. When a method depends on this +dependency, the 'authenticated_partner_id' key is added to the context +of the partner environment. (If you don't need the partner as dependency +but need to get an environment with the authenticated user, you can use +the dependency 'authenticated_partner_env' instead of +'authenticated_partner'.) + +The fastapi addon extends the 'ir.rule' model to add into the evaluation +context of the security rules the key 'authenticated_partner_id' that +contains the id of the authenticated partner. + +As briefly introduced in a previous section, a good practice when you +develop a fastapi app and you want to protect your data in an efficient +and traceable way is to: + +- create a new user specific to the app but with any access rights. +- create a security group specific to the app and add the user to this + group. (This group must implies the group 'AFastAPI Endpoint Runner' + that give the minimal access rights) +- for each model you want to protect: + - add a 'ir.model.access' record for the model to allow read access to + your model and add the group to the record. + - create a new 'ir.rule' record for the model that restricts the + access to the records of the model to the authenticated partner by + using the key 'authenticated_partner_id' in domain of the rule. (or + to the user defined on the 'fastapi.endpoint' model instance if the + method is public) +- add a dependency on the 'authenticated_partner' to your handlers when + you need to access the authenticated partner or ensure that the + service is called by an authenticated partner. + +``` xml + + My Demo Endpoint User + my_demo_app_user + + + + + My Demo Endpoint Group + + + + + + + My Demo App: access to sale.order + + + + + + + + + + + Sale Order Rule + + [('partner_id', '=', authenticated_partner_id)] + + +``` + +## How to test your fastapi app + +Thanks to the starlette test client, it's possible to test your fastapi +app in a very simple way. With the test client, you can call your route +handlers as if they were real http endpoints. The test client is +available in the **'fastapi.testclient'** module. + +Once again the dependency injection mechanism comes to the rescue by +allowing you to inject into the test client specific implementations of +the dependencies normally provided by the normal processing of the +request by the fastapi app. (for example, you can inject a mock of the +dependency 'authenticated_partner' to test the behavior of your route +handlers when the partner is not authenticated, you can also inject a +mock for the odoo_env etc...) + +The fastapi addon provides a base class for the test cases that you can +use to write your tests. This base class is +**'odoo.fastapi.tests.common.FastAPITransactionCase'**. This class +mainly provides the method **'\_create_test_client'** that you can use +to create a test client for your fastapi app. This method encapsulates +the creation of the test client and the injection of the dependencies. +It also ensures that the odoo environment is make available into the +context of the route handlers. This method is designed to be used when +you need to test your app or when you need to test a specific router +(It's therefore easy to defines tests for routers in an addon that +doesn't provide a fastapi endpoint). + +With this base class, writing a test for a route handler is as simple +as: + +``` python +from odoo.fastapi.tests.common import FastAPITransactionCase + +from odoo.addons.fastapi import dependencies +from odoo.addons.fastapi.routers import demo_router + +class FastAPIDemoCase(FastAPITransactionCase): + + @classmethod + def setUpClass(cls) -> None: + super().setUpClass() + cls.default_fastapi_running_user = cls.env.ref("fastapi.my_demo_app_user") + cls.default_fastapi_authenticated_partner = cls.env["res.partner"].create({"name": "FastAPI Demo"}) + + def test_hello_world(self) -> None: + with self._create_test_client(router=demo_router) as test_client: + response: Response = test_client.get("/demo/") + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertDictEqual(response.json(), {"Hello": "World"}) +``` + +In the previous example, we created a test client for the demo_router. +We could have created a test client for the whole app by not specifying +the router but the app instead. + +``` python +from odoo.fastapi.tests.common import FastAPITransactionCase + +from odoo.addons.fastapi import dependencies +from odoo.addons.fastapi.routers import demo_router + +class FastAPIDemoCase(FastAPITransactionCase): + + @classmethod + def setUpClass(cls) -> None: + super().setUpClass() + cls.default_fastapi_running_user = cls.env.ref("fastapi.my_demo_app_user") + cls.default_fastapi_authenticated_partner = cls.env["res.partner"].create({"name": "FastAPI Demo"}) + + def test_hello_world(self) -> None: + demo_endpoint = self.env.ref("fastapi.fastapi_endpoint_demo") + with self._create_test_client(app=demo_endpoint._get_app()) as test_client: + response: Response = test_client.get(f"{demo_endpoint.root_path}/demo/") + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertDictEqual(response.json(), {"Hello": "World"}) +``` + +## Overall considerations when you develop an fastapi app + +Developing a fastapi app requires to follow some good practices to +ensure that the app is robust and easy to maintain. Here are some of +them: + +- A route handler must be as simple as possible. It must not contain any + business logic. The business logic must be implemented into the + service layer. The route handler must only call the service layer and + return the result of the service layer. To ease extension on your + business logic, your service layer can be implemented as an odoo + abstract model that can be inherited by other addons. +- A route handler should not expose the internal data structure and api + of Odoo. It should provide the api that is needed by the client. More + widely, an app provides a set of services that address a set of use + cases specific to a well defined functional domain. You must always + keep in mind that your api will remain the same for a long time even + if you upgrade your odoo version of modify your business logic. +- A route handler is a transactional unit of work. When you design your + api you must ensure that the completeness of a use case is guaranteed + by a single transaction. If you need to perform several transactions + to complete a use case, you introduce a risk of inconsistency in your + data or extra complexity in your client code. +- Properly handle the errors. The route handler must return a proper + error response when an error occurs. The error response must be + consistent with the rest of the api. The error response must be + documented in the api documentation. By default, the + **'odoo-addon-fastapi'** module handles the common exception types + defined in the **'odoo.exceptions'** module and returns a proper error + response with the corresponding http status code. An error in the + route handler must always return an error response with a http status + code different from 200. The error response must contain a human + readable message that can be displayed to the user. The error response + can also contain a machine readable code that can be used by the + client to handle the error in a specific way. +- When you design your json document through the pydantic models, you + must use the appropriate data types. For example, you must use the + data type **'datetime.date'** to represent a date and not a string. + You must also properly define the constraints on the fields. For + example, if a field is optional, you must use the data type + **'typing.Optional'**. [pydantic](https://docs.pydantic.dev/) provides + everything you need to properly define your json document. +- Always use an appropriate pydantic model as request and/or response + for your route handler. Constraints on the fields of the pydantic + model must apply to the specific use case. For example, if your route + handler is used to create a sale order, the pydantic model must not + contain the field 'id' because the id of the sale order will be + generated by the route handler. But if the id is required afterwords, + the pydantic model for the response must contain the field 'id' as + required. +- Uses descriptive property names in your json documents. For example, + avoid the use of documents providing a flat list of key value pairs. +- Be consistent in the naming of your fields into your json documents. + For example, if you use 'id' to represent the id of a sale order, you + must use 'id' to represent the id of all the other objects. +- Be consistent in the naming style of your fields. Always prefer + underscore to camel case. +- Always use plural for the name of the fields that contain a list of + items. For example, if you have a field 'lines' that contains a list + of sale order lines, you must use 'lines' and not 'line'. +- You can't expect that a client will provide you the identifier of a + specific record in odoo (for example the id of a carrier) if you don't + provide a specific route handler to retrieve the list of available + records. Sometimes, the client must share with odoo the identity of a + specific record to be able to perform an appropriate action specific + to this record (for example, the processing of a payment is different + for each payment acquirer). In this case, you must provide a specific + attribute that allows both the client and odoo to identify the record. + The field 'provider' on a payment acquirer allows you to identify a + specific record in odoo. This kind of approach allows both the client + and odoo to identify the record without having to rely on the id of + the record. (This will ensure that the client will not break if the id + of the record is changed in odoo for example when tests are run on an + other database). +- Always use the same name for the same kind of object. For example, if + you have a field 'lines' that contains a list of sale order lines, you + must use the same name for the same kind of object in all the other + json documents. +- Manage relations between objects in your json documents the same way. + By default, you should return the id of the related object in the json + document. But this is not always possible or convenient, so you can + also return the related object in the json document. The main + advantage of returning the id of the related object is that it allows + you to avoid the [n+1 + problem](https://restfulapi.net/rest-api-n-1-problem/) . The main + advantage of returning the related object in the json document is that + it allows you to avoid an extra call to retrieve the related object. + By keeping in mind the pros and cons of each approach, you can choose + the best one for your use case. Once it's done, you must be consistent + in the way you manage the relations of the same object. +- It's not always a good idea to name your fields into your json + documents with the same name as the fields of the corresponding odoo + model. For example, in your document representing a sale order, you + must not use the name 'order_line' for the field that contains the + list of sale order lines. The name 'order_line' in addition to being + confusing and not consistent with the best practices, is not + auto-descriptive. The name 'lines' is much better. +- Keep a defensive programming approach. If you provide a route handler + that returns a list of records, you must ensure that the computation + of the list is not too long or will not drain your server resources. + For example, for search route handlers, you must ensure that the + search is limited to a reasonable number of records by default. +- As a corollary of the previous point, a search handler must always use + the pagination mechanism with a reasonable default page size. The + result list must be enclosed in a json document that contains the + count of records into the system matching your search criteria and the + list of records for the given page and size. +- Use plural for the name of a service. For example, if you provide a + service that allows you to manage the sale orders, you must use the + name 'sale_orders' and not 'sale_order'. +- ... and many more. + +We could write a book about the best practices to follow when you design +your api but we will stop here. This list is the result of our +experience at [ACSONE SA/NV](https://acsone.eu) and it evolves over +time. It's a kind of rescue kit that we would provide to a new developer +that starts to design an api. This kit must be accompanied with the +reading of some useful resources link like the [REST +Guidelines](https://www.belgif.be/specification/rest/api-guide/). On a +technical level, the [fastapi +documentation](https://fastapi.tiangolo.com/) provides a lot of useful +information as well, with a lot of examples. Last but not least, the +[pydantic](https://docs.pydantic.dev/) documentation is also very +useful. + +## Miscellaneous + +### Development of a search route handler + +The **'odoo-addon-fastapi'** module provides 2 useful piece of code to +help you be consistent when writing a route handler for a search route. + +1. A dependency method to use to specify the pagination parameters in + the same way for all the search route handlers: + **'odoo.addons.fastapi.paging'**. +2. A PagedCollection pydantic model to use to return the result of a + search route handler enclosed in a json document that contains the + count of records. + +``` python +from typing import Annotated +from pydantic import BaseModel + +from odoo.api import Environment +from odoo.addons.fastapi.dependencies import paging, authenticated_partner_env +from odoo.addons.fastapi.schemas import PagedCollection, Paging + +class SaleOrder(BaseModel): + id: int + name: str + model_config = ConfigDict(from_attributes=True) + + +@router.get( + "/sale_orders", + response_model=PagedCollection[SaleOrder], + response_model_exclude_unset=True, +) +def get_sale_orders( + paging: Annotated[Paging, Depends(paging)], + env: Annotated[Environment, Depends(authenticated_partner_env)], +) -> PagedCollection[SaleOrder]: + """Get the list of sale orders.""" + count = env["sale.order"].search_count([]) + orders = env["sale.order"].search([], limit=paging.limit, offset=paging.offset) + return PagedCollection[SaleOrder]( + count=count, + items=[SaleOrder.model_validate(order) for order in orders], + ) +``` + +Note + +The **'odoo.addons.fastapi.schemas.Paging'** and +**'odoo.addons.fastapi.schemas.PagedCollection'** pydantic models are +not designed to be extended to not introduce a dependency between the +**'odoo-addon-fastapi'** module and the **'odoo-addon-extendable'** + +### Error handling + +The error handling is a very important topic in the design of the fastapi integration +with odoo. By default, when instantiating the fastapi app, the fastapi library +declare a default exception handler that will catch any exception raised by the +route handlers and return a proper error response. This is done to ensure that +the serving of the app is not interrupted by an unhandled exception. If this +implementation makes sense for a native fastapi app, it's not the case for the +fastapi integration with odoo. The transactional nature of the calls to +odoo's api is implemented at the root of the request processing by odoo. To ensure +that the transaction is properly managed, the integration with odoo must ensure +that the exceptions raised by the route handlers properly bubble up to the +handling of the request by odoo. This is done by the monkey patching of the +registered exception handler of the fastapi app in the +**'odoo.addons.fastapi.models.error_handlers'** module. As a result, it's no +longer possible to define a custom exception handler in your fastapi app. If you +add a custom exception handler in your app, it will be ignored. + +### FastAPI addons directory structure + +When you develop a new addon to expose an api with fastapi, it's a good +practice to follow the same directory structure and naming convention +for the files related to the api. It will help you to easily find the +files related to the api and it will help the other developers to +understand your code. + +Here is the directory structure that we recommend. It's based on +practices that are used in the python community when developing a +fastapi app. + +``` +. +├── x_api +│   ├── data +│   │ ├── ... .xml +│   ├── demo +│   │ ├── ... .xml +│   ├── i18n +│   │ ├── ... .po +│   ├── models +│   │ ├── __init__.py +│   │ ├── fastapi_endpoint.py # your app +│   │ └── ... .py +│   └── routers +│   │ ├── __init__.py +│   │ ├── items.py +│   │ └── ... .py +│   ├── schemas | schemas.py +│   │ ├── __init__.py +│   │ ├── my_model.py # pydantic model +│   │ └── ... .py +│   ├── security +│   │ ├── ... .xml +│   ├── views +│   │ ├── ... .xml +│   ├── __init__.py +│   ├── __manifest__.py +│   ├── dependencies.py # custom dependencies +│   ├── error_handlers.py # custom error handlers +``` + +- The **'models'** directory contains the odoo models. When you define a + new app, as for the others addons, you will add your new model + inheriting from the **'fastapi.endpoint'** model in this directory. + +- The **'routers'** directory contains the fastapi routers. You will add + your new routers in this directory. Each route starting with the same + prefix should be grouped in the same file. For example, all the routes + starting with '/items' should be defined in the **'items.py'** file. + The **'\_\_init\_\_.py'** file in this directory is used to import all + the routers defined in the directory and create a global router that + can be used in an app. For example, in your **'items.py'** file, you + will define a router like this: + + ``` python + router = APIRouter(tags=["items"]) + + router.get("/items", response_model=List[Item]) + def list_items(): + pass + ``` + + In the **'\_\_init\_\_.py'** file, you will import the router and add + it to the global router or your addon. + + ``` python + from fastapi import APIRouter + + from .items import router as items_router + + router = APIRouter() + router.include_router(items_router) + ``` + +- The **'schemas.py'** will be used to define the pydantic models. For + complex APIs with a lot of models, it will be better to create a + **'schemas'** directory and split the models in different files. The + **'\_\_init\_\_.py'** file in this directory will be used to import + all the models defined in the directory. For example, in your + **'my_model.py'** file, you will define a model like this: + + ``` python + from pydantic import BaseModel + + class MyModel(BaseModel): + name: str + description: str = None + ``` + + In the **'\_\_init\_\_.py'** file, you will import the model's classes + from the files in the directory. + + ``` python + from .my_model import MyModel + ``` + + This will allow to always import the models from the schemas module + whatever the models are spread across different files or defined in + the **'schemas.py'** file. + + ``` python + from x_api_addon.schemas import MyModel + ``` + +- The **'dependencies.py'** file contains the custom dependencies that + you will use in your routers. For example, you can define a dependency + to check the access rights of the user. + +- The **'error_handlers.py'** file contains the custom error handlers + that you will use in your routers. The **'odoo-addon-fastapi'** module + provides the default error handlers for the common odoo exceptions. + Chance are that you will not need to define your own error handlers. + But if you need to do it, you can define them in this file. + +## What's next? + +The **'odoo-addon-fastapi'** module is still in its early stage of +development. It will evolve over time to integrate your feedback and to +provide the missing features. It's now up to you to try it and to +provide your feedback. + diff --git a/fastapi/readme/newsfragments/.gitignore b/fastapi/readme/newsfragments/.gitignore new file mode 100644 index 000000000..e69de29bb diff --git a/fastapi/routers/__init__.py b/fastapi/routers/__init__.py new file mode 100644 index 000000000..e955879e9 --- /dev/null +++ b/fastapi/routers/__init__.py @@ -0,0 +1,2 @@ +from .demo_router import router as demo_router +from .demo_router import __doc__ as demo_router_doc diff --git a/fastapi/routers/demo_router.py b/fastapi/routers/demo_router.py new file mode 100644 index 000000000..36450057a --- /dev/null +++ b/fastapi/routers/demo_router.py @@ -0,0 +1,144 @@ +# Copyright 2023 ACSONE SA/NV +# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL). +""" +The demo router is a router that demonstrates how to use the fastapi +integration with odoo. +""" + +from typing import Annotated + +from psycopg2 import errorcodes +from psycopg2.errors import SerializationFailure + +from odoo.api import Environment +from odoo.exceptions import AccessError, MissingError, UserError, ValidationError +from odoo.service.model import MAX_TRIES_ON_CONCURRENCY_FAILURE + +from odoo.addons.base.models.res_partner import Partner + +from fastapi import APIRouter, Depends, File, HTTPException, Query, status +from fastapi.responses import JSONResponse + +from ..dependencies import authenticated_partner, fastapi_endpoint, odoo_env +from ..models import FastapiEndpoint +from ..schemas import DemoEndpointAppInfo, DemoExceptionType, DemoUserInfo + +router = APIRouter(tags=["demo"]) + + +@router.get("/demo") +async def hello_word(): + """Hello World!""" + return {"Hello": "World"} + + +@router.get("/demo/exception") +async def exception(exception_type: DemoExceptionType, error_message: str): + """Raise an exception + + This method is used in the test suite to check that any exception + is correctly handled by the fastapi endpoint and that the transaction + is roll backed. + """ + exception_classes = { + DemoExceptionType.user_error: UserError, + DemoExceptionType.validation_error: ValidationError, + DemoExceptionType.access_error: AccessError, + DemoExceptionType.missing_error: MissingError, + DemoExceptionType.http_exception: HTTPException, + DemoExceptionType.bare_exception: NotImplementedError, + } + exception_cls = exception_classes[exception_type] + if exception_cls is HTTPException: + raise exception_cls(status_code=status.HTTP_409_CONFLICT, detail=error_message) + raise exception_classes[exception_type](error_message) + + +@router.get("/demo/lang") +async def get_lang(env: Annotated[Environment, Depends(odoo_env)]): + """Returns the language according to the available languages in Odoo and the + Accept-Language header. + + This method is used in the test suite to check that the language is correctly + set in the Odoo environment according to the Accept-Language header + """ + return env.context.get("lang") + + +@router.get("/demo/who_ami") +async def who_ami( + partner: Annotated[Partner, Depends(authenticated_partner)], +) -> DemoUserInfo: + """Who am I? + + Returns the authenticated partner + """ + # This method show you how you can rget the authenticated partner without + # depending on a specific implementation. + return DemoUserInfo(name=partner.name, display_name=partner.display_name) + + +@router.get( + "/demo/endpoint_app_info", + dependencies=[Depends(authenticated_partner)], +) +async def endpoint_app_info( + endpoint: Annotated[FastapiEndpoint, Depends(fastapi_endpoint)], +) -> DemoEndpointAppInfo: + """Returns the current endpoint configuration""" + # This method show you how to get access to current endpoint configuration + # It also show you how you can specify a dependency to force the security + # even if the method doesn't require the authenticated partner as parameter + return DemoEndpointAppInfo.model_validate(endpoint) + + +_CPT = 0 + + +@router.get("/demo/retrying") +async def retrying( + nbr_retries: Annotated[int, Query(gt=1, lt=MAX_TRIES_ON_CONCURRENCY_FAILURE)], +) -> int: + """This method is used in the test suite to check that the retrying + functionality in case of concurrency error on the database is working + correctly for retryable exceptions. + + The output will be the number of retries that have been done. + + This method is mainly used to test the retrying functionality + """ + global _CPT + if _CPT < nbr_retries: + _CPT += 1 + raise FakeConcurrentUpdateError("fake error") + tryno = _CPT + _CPT = 0 + return tryno + + +@router.post("/demo/retrying") +async def retrying_post( + nbr_retries: Annotated[int, Query(gt=1, lt=MAX_TRIES_ON_CONCURRENCY_FAILURE)], + file: Annotated[bytes, File()], +) -> JSONResponse: + """This method is used in the test suite to check that the retrying + functionality in case of concurrency error on the database is working + correctly for retryable exceptions. + + The output will be the number of retries that have been done. + + This method is mainly used to test the retrying functionality + """ + global _CPT + if _CPT < nbr_retries: + _CPT += 1 + raise FakeConcurrentUpdateError("fake error") + tryno = _CPT + _CPT = 0 + return JSONResponse(content={"retries": tryno, "file": file.decode("utf-8")}) + + +class FakeConcurrentUpdateError(SerializationFailure): + @property + def pgcode(self): + return errorcodes.SERIALIZATION_FAILURE diff --git a/fastapi/schemas.py b/fastapi/schemas.py new file mode 100644 index 000000000..e67f59afe --- /dev/null +++ b/fastapi/schemas.py @@ -0,0 +1,67 @@ +# Copyright 2022 ACSONE SA/NV +# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL). +import warnings +from enum import Enum +from typing import Annotated, Generic, TypeVar + +from pydantic import AliasChoices, BaseModel, ConfigDict, Field, computed_field + +T = TypeVar("T") + + +class PagedCollection(BaseModel, Generic[T]): + count: Annotated[ + int, + Field( + ..., + description="Count of items into the system.\n " + "Replaces the total field which is deprecated", + validation_alias=AliasChoices("count", "total"), + ), + ] + items: list[T] + + @computed_field() + @property + def total(self) -> int: + return self.count + + @total.setter + def total(self, value: int): + warnings.warn( + "The total field is deprecated, please use count instead", + DeprecationWarning, + stacklevel=2, + ) + self.count = value + + +class Paging(BaseModel): + limit: int | None + offset: int | None + + +############################################################# +# here above you can find models only used for the demo app # +############################################################# +class DemoUserInfo(BaseModel): + name: str + display_name: str + + +class DemoEndpointAppInfo(BaseModel): + id: int + name: str + app: str + auth_method: str = Field(alias="demo_auth_method") + root_path: str + model_config = ConfigDict(from_attributes=True) + + +class DemoExceptionType(str, Enum): + user_error = "UserError" + validation_error = "ValidationError" + access_error = "AccessError" + missing_error = "MissingError" + http_exception = "HTTPException" + bare_exception = "BareException" diff --git a/fastapi/security/fastapi_endpoint.xml b/fastapi/security/fastapi_endpoint.xml new file mode 100644 index 000000000..1bb23ac5d --- /dev/null +++ b/fastapi/security/fastapi_endpoint.xml @@ -0,0 +1,24 @@ + + + + + fastapi.endpoint view + + + + + + + + + + fastapi.endpoint manage + + + + + + + + diff --git a/fastapi/security/ir_rule+acl.xml b/fastapi/security/ir_rule+acl.xml new file mode 100644 index 000000000..2ba108bee --- /dev/null +++ b/fastapi/security/ir_rule+acl.xml @@ -0,0 +1,64 @@ + + + + + + Fastapi: Running user read users + + + + + + + + + + + Fastapi: Running user rule + + [('id', '=', user.id)] + + + + + + Fastapi: Running user read partners + + + + + + + + + + + Fastapi: Running user rule + + ['|', ('user_id', '=', user.id), ('id', '=', authenticated_partner_id)] + + + + + + Fastapi: Running user read endpoints + + + + + + + + + + + Fastapi: Running user rule + + [('user_id', '=', user.id)] + + + diff --git a/fastapi/security/res_groups.xml b/fastapi/security/res_groups.xml new file mode 100644 index 000000000..589cbcf97 --- /dev/null +++ b/fastapi/security/res_groups.xml @@ -0,0 +1,33 @@ + + + + + FastAPI + Helps you manage your Fastapi Endpoints + 99 + + + + User + + + + + + Administrator + + + + + + + + FastAPI Endpoint Runner + + + diff --git a/fastapi/static/description/endpoint_create.png b/fastapi/static/description/endpoint_create.png new file mode 100644 index 000000000..dc5806b14 Binary files /dev/null and b/fastapi/static/description/endpoint_create.png differ diff --git a/fastapi/static/description/icon.png b/fastapi/static/description/icon.png new file mode 100644 index 000000000..e09b3918c Binary files /dev/null and b/fastapi/static/description/icon.png differ diff --git a/fastapi/static/description/index.html b/fastapi/static/description/index.html new file mode 100644 index 000000000..3e6a17db3 --- /dev/null +++ b/fastapi/static/description/index.html @@ -0,0 +1,1966 @@ + + + + + +Odoo FastAPI + + + +
+

Odoo FastAPI

+ + +

Beta License: LGPL-3 OCA/rest-framework Translate me on Weblate Try me on Runboat

+

This addon provides the basis to smoothly integrate the +FastAPI framework into Odoo.

+

This integration allows you to use all the goodies from +FastAPI to build custom APIs for +your Odoo server based on standard Python type hints.

+

What is building an API?

+

An API is a set of functions that can be called from the outside world. +The goal of an API is to provide a way to interact with your application +from the outside world without having to know how it works internally. A +common mistake when you are building an API is to expose all the +internal functions of your application and therefore create a tight +coupling between the outside world and your internal datamodel and +business logic. This is not a good idea because it makes it very hard to +change your internal datamodel and business logic without breaking the +outside world.

+

When you are building an API, you define a contract between the outside +world and your application. This contract is defined by the functions +that you expose and the parameters that you accept. This contract is the +API. When you change your internal datamodel and business logic, you can +still keep the same API contract and therefore you don’t break the +outside world. Even if you change your implementation, as long as you +keep the same API contract, the outside world will still work. This is +the beauty of an API and this is why it is so important to design a good +API.

+

A good API is designed to be stable and to be easy to use. It’s designed +to provide high-level functions related to a specific use case. It’s +designed to be easy to use by hiding the complexity of the internal +datamodel and business logic. A common mistake when you are building an +API is to expose all the internal functions of your application and let +the oustide world deal with the complexity of your internal datamodel +and business logic. Don’t forget that on a transactional point of view, +each call to an API function is a transaction. This means that if a +specific use case requires multiple calls to your API, you should +provide a single function that does all the work in a single +transaction. This why APIs methods are called high-level and atomic +functions.

+

Table of contents

+ +
+

Usage

+
+

What’s building an API with fastapi?

+

FastAPI is a modern, fast (high-performance), web framework for building +APIs with Python 3.7+ based on standard Python type hints. This addons +let’s you keep advantage of the fastapi framework and use it with Odoo.

+

Before you start, we must define some terms:

+
    +
  • App: A FastAPI app is a collection of routes, dependencies, and +other components that can be used to build a web application.
  • +
  • Router: A router is a collection of routes that can be mounted in +an app.
  • +
  • Route: A route is a mapping between an HTTP method and a path, and +defines what should happen when the user requests that path.
  • +
  • Dependency: A dependency is a callable that can be used to get +some information from the user request, or to perform some actions +before the request handler is called.
  • +
  • Request: A request is an object that contains all the information +sent by the user’s browser as part of an HTTP request.
  • +
  • Response: A response is an object that contains all the +information that the user’s browser needs to build the result page.
  • +
  • Handler: A handler is a function that takes a request and returns +a response.
  • +
  • Middleware: A middleware is a function that takes a request and a +handler, and returns a response.
  • +
+

The FastAPI framework is based on the following principles:

+
    +
  • Fast: Very high performance, on par with NodeJS and Go (thanks to +Starlette and Pydantic). [One of the fastest Python frameworks +available]
  • +
  • Fast to code: Increase the speed to develop features by about 200% +to 300%.
  • +
  • Fewer bugs: Reduce about 40% of human (developer) induced errors.
  • +
  • Intuitive: Great editor support. Completion everywhere. Less time +debugging.
  • +
  • Easy: Designed to be easy to use and learn. Less time reading +docs.
  • +
  • Short: Minimize code duplication. Multiple features from each +parameter declaration. Fewer bugs.
  • +
  • Robust: Get production-ready code. With automatic interactive +documentation.
  • +
  • Standards-based: Based on (and fully compatible with) the open +standards for APIs: OpenAPI (previously known as Swagger) and JSON +Schema.
  • +
  • Open Source: FastAPI is fully open-source, under the MIT license.
  • +
+

The first step is to install the fastapi addon. You can do it with the +following command:

+
+$ pip install odoo-addon-fastapi
+

Once the addon is installed, you can start building your API. The first +thing you need to do is to create a new addon that depends on ‘fastapi’. +For example, let’s create an addon called my_demo_api.

+

Then, you need to declare your app by defining a model that inherits +from ‘fastapi.endpoint’ and add your app name into the app field. For +example:

+
+from odoo import fields, models
+
+class FastapiEndpoint(models.Model):
+
+    _inherit = "fastapi.endpoint"
+
+    app: str = fields.Selection(
+        selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"}
+    )
+
+

The ‘fastapi.endpoint’ model is the base model for all the +endpoints. An endpoint instance is the mount point for a fastapi app +into Odoo. When you create a new endpoint, you can define the app that +you want to mount in the ‘app’ field and the path where you want to +mount it in the ‘path’ field.

+

figure:: static/description/endpoint_create.png

+
+FastAPI Endpoint
+

Thanks to the ‘fastapi.endpoint’ model, you can create as many +endpoints as you want and mount as many apps as you want in each +endpoint. The endpoint is also the place where you can define +configuration parameters for your app. A typical example is the +authentication method that you want to use for your app when accessed at +the endpoint path.

+

Now, you can create your first router. For that, you need to define a +global variable into your fastapi_endpoint module called for example +‘demo_api_router’

+
+from fastapi import APIRouter
+from odoo import fields, models
+
+class FastapiEndpoint(models.Model):
+
+    _inherit = "fastapi.endpoint"
+
+    app: str = fields.Selection(
+        selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"}
+    )
+
+# create a router
+demo_api_router = APIRouter()
+
+

To make your router available to your app, you need to add it to the +list of routers returned by the _get_fastapi_routers method of your +fastapi_endpoint model.

+
+from fastapi import APIRouter
+from odoo import api, fields, models
+
+class FastapiEndpoint(models.Model):
+
+    _inherit = "fastapi.endpoint"
+
+    app: str = fields.Selection(
+        selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"}
+    )
+
+    def _get_fastapi_routers(self):
+        if self.app == "demo":
+            return [demo_api_router]
+        return super()._get_fastapi_routers()
+
+# create a router
+demo_api_router = APIRouter()
+
+

Now, you can start adding routes to your router. For example, let’s add +a route that returns a list of partners.

+
+from typing import Annotated
+
+from fastapi import APIRouter
+from pydantic import BaseModel
+
+from odoo import api, fields, models
+from odoo.api import Environment
+
+from odoo.addons.fastapi.dependencies import odoo_env
+
+class FastapiEndpoint(models.Model):
+
+    _inherit = "fastapi.endpoint"
+
+    app: str = fields.Selection(
+        selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"}
+    )
+
+    def _get_fastapi_routers(self):
+        if self.app == "demo":
+            return [demo_api_router]
+        return super()._get_fastapi_routers()
+
+# create a router
+demo_api_router = APIRouter()
+
+class PartnerInfo(BaseModel):
+    name: str
+    email: str
+
+@demo_api_router.get("/partners", response_model=list[PartnerInfo])
+def get_partners(env: Annotated[Environment, Depends(odoo_env)]) -> list[PartnerInfo]:
+    return [
+        PartnerInfo(name=partner.name, email=partner.email)
+        for partner in env["res.partner"].search([])
+    ]
+
+

Now, you can start your Odoo server, install your addon and create a new +endpoint instance for your app. Once it’s done click on the docs url to +access the interactive documentation of your app.

+

Before trying to test your app, you need to define on the endpoint +instance the user that will be used to run the app. You can do it by +setting the ‘user_id’ field. This information is the most important +one because it’s the basis for the security of your app. The user that +you define in the endpoint instance will be used to run the app and to +access the database. This means that the user will be able to access all +the data that he has access to in Odoo. To ensure the security of your +app, you should create a new user that will be used only to run your app +and that will have no access to the database.

+
+<record
+      id="my_demo_app_user"
+      model="res.users"
+      context="{'no_reset_password': True, 'no_reset_password': True}"
+  >
+  <field name="name">My Demo Endpoint User</field>
+  <field name="login">my_demo_app_user</field>
+  <field name="groups_id" eval="[(6, 0, [])]" />
+</record>
+
+

At the same time you should create a new group that will be used to +define the access rights of the user that will run your app. This group +should imply the predefined group ‘FastAPI Endpoint Runner’. This +group defines the minimum access rights that the user needs to:

+
    +
  • access the endpoint instance it belongs to
  • +
  • access to its own user record
  • +
  • access to the partner record that is linked to its user record
  • +
+
+<record id="my_demo_app_group" model="res.groups">
+  <field name="name">My Demo Endpoint Group</field>
+  <field name="users" eval="[(4, ref('my_demo_app_user'))]" />
+  <field name="implied_ids" eval="[(4, ref('fastapi.group_fastapi_endpoint_runner'))]" />
+</record>
+
+

Now, you can test your app. You can do it by clicking on the ‘Try it +out’ button of the route that you have defined. The result of the +request will be displayed in the ‘Response’ section and contains the +list of partners.

+

Note

+

The ‘FastAPI Endpoint Runner’ group ensures that the user cannot +access any information others than the 3 ones mentioned above. This +means that for every information that you want to access from your app, +you need to create the proper ACLs and record rules. (see Managing +security into the route +handlers) It’s a good +practice to use a dedicated user into a specific group from the +beginning of your project and in your tests. This will force you to +define the proper security rules for your endoints.

+
+
+

Dealing with the odoo environment

+

The ‘odoo.addons.fastapi.dependencies’ module provides a set of +functions that you can use to inject reusable dependencies into your +routes. For example, the ‘odoo_env’ function returns the current +odoo environment. You can use it to access the odoo models and the +database from your route handlers.

+
+from typing import Annotated
+
+from odoo.api import Environment
+from odoo.addons.fastapi.dependencies import odoo_env
+
+@demo_api_router.get("/partners", response_model=list[PartnerInfo])
+def get_partners(env: Annotated[Environment, Depends(odoo_env)]) -> list[PartnerInfo]:
+    return [
+        PartnerInfo(name=partner.name, email=partner.email)
+        for partner in env["res.partner"].search([])
+    ]
+
+

As you can see, you can use the ‘Depends’ function to inject the +dependency into your route handler. The ‘Depends’ function is +provided by the ‘fastapi’ framework. You can use it to inject any +dependency into your route handler. As your handler is a python +function, the only way to get access to the odoo environment is to +inject it as a dependency. The fastapi addon provides a set of function +that can be used as dependencies:

+
    +
  • ‘odoo_env’: Returns the current odoo environment.
  • +
  • ‘fastapi_endpoint’: Returns the current fastapi endpoint model +instance.
  • +
  • ‘authenticated_partner’: Returns the authenticated partner.
  • +
  • ‘authenticated_partner_env’: Returns the current odoo environment +with the authenticated_partner_id into the context.
  • +
+

By default, the ‘odoo_env’ and ‘fastapi_endpoint’ dependencies +are available without extra work.

+

Note

+

Even if ‘odoo_env’ and ‘authenticated_partner_env’ returns the current +odoo environment, they are not the same. The ‘odoo_env’ dependency +returns the environment without any modification while the +‘authenticated_partner_env’ adds the authenticated partner id into the +context of the environment. As it will be explained in the section +Managing security into the route +handlers dedicated to +the security, the presence of the authenticated partner id into the +context is the key information that will allow you to enforce the +security of your endpoint methods. As consequence, you should always use +the ‘authenticated_partner_env’ dependency instead of the ‘odoo_env’ +dependency for all the methods that are not public.

+
+
+

The dependency injection mechanism

+

The ‘odoo_env’ dependency relies on a simple implementation that +retrieves the current odoo environment from ContextVar variable +initialized at the start of the request processing by the specific +request dispatcher processing the fastapi requests.

+

The ‘fastapi_endpoint’ dependency relies on the +‘dependency_overrides’ mechanism provided by the ‘fastapi’ module. +(see the fastapi documentation for more details about the +dependency_overrides mechanism). If you take a look at the current +implementation of the ‘fastapi_endpoint’ dependency, you will see +that the method depends of two parameters: ‘endpoint_id’ and +‘env’. Each of these parameters are dependencies themselves.

+
+def fastapi_endpoint_id() -> int:
+    """This method is overriden by default to make the fastapi.endpoint record
+    available for your endpoint method. To get the fastapi.endpoint record
+    in your method, you just need to add a dependency on the fastapi_endpoint method
+    defined below
+    """
+
+
+def fastapi_endpoint(
+    _id: Annotated[int, Depends(fastapi_endpoint_id)],
+    env: Annotated[Environment, Depends(odoo_env)],
+) -> "FastapiEndpoint":
+    """Return the fastapi.endpoint record"""
+    return env["fastapi.endpoint"].browse(_id)
+
+

As you can see, one of these dependencies is the +‘fastapi_endpoint_id’ dependency and has no concrete implementation. +This method is used as a contract that must be implemented/provided at +the time the fastapi app is created. Here comes the power of the +dependency_overrides mechanism.

+

If you take a look at the ‘_get_app’ method of the +‘FastapiEndpoint’ model, you will see that the +‘fastapi_endpoint_id’ dependency is overriden by registering a +specific method that returns the id of the current fastapi endpoint +model instance for the original method.

+
+def _get_app(self) -> FastAPI:
+    app = FastAPI(**self._prepare_fastapi_endpoint_params())
+    for router in self._get_fastapi_routers():
+        app.include_router(prefix=self.root_path, router=router)
+    app.dependency_overrides[dependencies.fastapi_endpoint_id] = partial(
+        lambda a: a, self.id
+    )
+
+

This kind of mechanism is very powerful and allows you to inject any +dependency into your route handlers and moreover, define an abstract +dependency that can be used by any other addon and for which the +implementation could depend on the endpoint configuration.

+
+
+

The authentication mechanism

+

To make our app not tightly coupled with a specific authentication +mechanism, we will use the ‘authenticated_partner’ dependency. As +for the ‘fastapi_endpoint’ this dependency depends on an abstract +dependency.

+

When you define a route handler, you can inject the +‘authenticated_partner’ dependency as a parameter of your route +handler.

+
+from odoo.addons.base.models.res_partner import Partner
+
+
+@demo_api_router.get("/partners", response_model=list[PartnerInfo])
+def get_partners(
+    env: Annotated[Environment, Depends(odoo_env)], partner: Annotated[Partner, Depends(authenticated_partner)]
+) -> list[PartnerInfo]:
+    return [
+        PartnerInfo(name=partner.name, email=partner.email)
+        for partner in env["res.partner"].search([])
+    ]
+
+

At this stage, your handler is not tied to a specific authentication +mechanism but only expects to get a partner as a dependency. Depending +on your needs, you can implement different authentication mechanism +available for your app. The fastapi addon provides a default +authentication mechanism using the ‘BasicAuth’ method. This +authentication mechanism is implemented in the +‘odoo.addons.fastapi.dependencies’ module and relies on +functionalities provided by the ‘fastapi.security’ module.

+
+def authenticated_partner(
+    env: Annotated[Environment, Depends(odoo_env)],
+    security: Annotated[HTTPBasicCredentials, Depends(HTTPBasic())],
+) -> "res.partner":
+    """Return the authenticated partner"""
+    partner = env["res.partner"].search(
+        [("email", "=", security.username)], limit=1
+    )
+    if not partner:
+        raise HTTPException(
+            status_code=status.HTTP_401_UNAUTHORIZED,
+            detail="Invalid authentication credentials",
+            headers={"WWW-Authenticate": "Basic"},
+        )
+    if not partner.check_password(security.password):
+        raise HTTPException(
+            status_code=status.HTTP_401_UNAUTHORIZED,
+            detail="Invalid authentication credentials",
+            headers={"WWW-Authenticate": "Basic"},
+        )
+    return partner
+
+

As you can see, the ‘authenticated_partner’ dependency relies on the +‘HTTPBasic’ dependency provided by the ‘fastapi.security’ +module. In this dummy implementation, we just check that the provided +credentials can be used to authenticate a user in odoo. If the +authentication is successful, we return the partner record linked to the +authenticated user.

+

In some cases you could want to implement a more complex authentication +mechanism that could rely on a token or a session. In this case, you can +override the ‘authenticated_partner’ dependency by registering a +specific method that returns the authenticated partner. Moreover, you +can make it configurable on the fastapi endpoint model instance.

+

To do it, you just need to implement a specific method for each of your +authentication mechanism and allows the user to select one of these +methods when he creates a new fastapi endpoint. Let’s say that we want +to allow the authentication by using an api key or via basic auth. Since +basic auth is already implemented, we will only implement the api key +authentication mechanism.

+
+from fastapi.security import APIKeyHeader
+
+def api_key_based_authenticated_partner_impl(
+    api_key: Annotated[str, Depends(
+        APIKeyHeader(
+            name="api-key",
+            description="In this demo, you can use a user's login as api key.",
+        )
+    )],
+    env: Annotated[Environment, Depends(odoo_env)],
+) -> Partner:
+    """A dummy implementation that look for a user with the same login
+    as the provided api key
+    """
+    partner = env["res.users"].search([("login", "=", api_key)], limit=1).partner_id
+    if not partner:
+        raise HTTPException(
+            status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect API Key"
+        )
+    return partner
+
+

As for the ‘BasicAuth’ authentication mechanism, we also rely on one of +the native security dependency provided by the ‘fastapi.security’ +module.

+

Now that we have an implementation for our two authentication +mechanisms, we can allows the user to select one of these authentication +mechanisms by adding a selection field on the fastapi endpoint model.

+
+from odoo import fields, models
+
+class FastapiEndpoint(models.Model):
+
+    _inherit = "fastapi.endpoint"
+
+    app: str = fields.Selection(
+      selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"}
+    )
+    demo_auth_method = fields.Selection(
+        selection=[("api_key", "Api Key"), ("http_basic", "HTTP Bacic")],
+        string="Authenciation method",
+    )
+
+

Note

+

A good practice is to prefix specific configuration fields of your app +with the name of your app. This will avoid conflicts with other app when +the ‘fastapi.endpoint’ model is extended for other ‘app’.

+

Now that we have a selection field that allows the user to select the +authentication method, we can use the dependency override mechanism to +provide the right implementation of the ‘authenticated_partner’ +dependency when the app is instantiated.

+
+from odoo.addons.fastapi.dependencies import authenticated_partner
+class FastapiEndpoint(models.Model):
+
+    _inherit = "fastapi.endpoint"
+
+    app: str = fields.Selection(
+      selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"}
+    )
+    demo_auth_method = fields.Selection(
+        selection=[("api_key", "Api Key"), ("http_basic", "HTTP Bacic")],
+        string="Authenciation method",
+    )
+
+  def _get_app(self) -> FastAPI:
+      app = super()._get_app()
+      if self.app == "demo":
+          # Here we add the overrides to the authenticated_partner_impl method
+          # according to the authentication method configured on the demo app
+          if self.demo_auth_method == "http_basic":
+              authenticated_partner_impl_override = (
+                  authenticated_partner_from_basic_auth_user
+              )
+          else:
+              authenticated_partner_impl_override = (
+                  api_key_based_authenticated_partner_impl
+              )
+          app.dependency_overrides[
+              authenticated_partner_impl
+          ] = authenticated_partner_impl_override
+      return app
+
+

To see how the dependency override mechanism works, you can take a look +at the demo app provided by the fastapi addon. If you choose the app +‘demo’ in the fastapi endpoint form view, you will see that the +authentication method is configurable. You can also see that depending +on the authentication method configured on your fastapi endpoint, the +documentation will change.

+

Note

+

At time of writing, the dependency override mechanism is not supported +by the fastapi documentation generator. A fix has been proposed and is +waiting to be merged. You can follow the progress of the fix on +github

+
+
+

Managing configuration parameters for your app

+

As we have seen in the previous section, you can add configuration +fields on the fastapi endpoint model to allow the user to configure your +app (as for any odoo model you extend). When you need to access these +configuration fields in your route handlers, you can use the +‘odoo.addons.fastapi.dependencies.fastapi_endpoint’ dependency +method to retrieve the ‘fastapi.endpoint’ record associated to the +current request.

+
+from pydantic import BaseModel, Field
+from odoo.addons.fastapi.dependencies import fastapi_endpoint
+
+class EndpointAppInfo(BaseModel):
+  id: str
+  name: str
+  app: str
+  auth_method: str = Field(alias="demo_auth_method")
+  root_path: str
+  model_config = ConfigDict(from_attributes=True)
+
+
+  @demo_api_router.get(
+      "/endpoint_app_info",
+      response_model=EndpointAppInfo,
+      dependencies=[Depends(authenticated_partner)],
+  )
+  async def endpoint_app_info(
+      endpoint: Annotated[FastapiEndpoint, Depends(fastapi_endpoint)],
+  ) -> EndpointAppInfo:
+      """Returns the current endpoint configuration"""
+      # This method show you how to get access to current endpoint configuration
+      # It also show you how you can specify a dependency to force the security
+      # even if the method doesn't require the authenticated partner as parameter
+      return EndpointAppInfo.model_validate(endpoint)
+
+

Some of the configuration fields of the fastapi endpoint could impact +the way the app is instantiated. For example, in the previous section, +we have seen that the authentication method configured on the +‘fastapi.endpoint’ record is used in order to provide the right +implementation of the ‘authenticated_partner’ when the app is +instantiated. To ensure that the app is re-instantiated when an element +of the configuration used in the instantiation of the app is modified, +you must override the ‘_fastapi_app_fields’ method to add the name +of the fields that impact the instantiation of the app into the returned +list.

+
+class FastapiEndpoint(models.Model):
+
+    _inherit = "fastapi.endpoint"
+
+    app: str = fields.Selection(
+      selection_add=[("demo", "Demo Endpoint")], ondelete={"demo": "cascade"}
+    )
+    demo_auth_method = fields.Selection(
+        selection=[("api_key", "Api Key"), ("http_basic", "HTTP Bacic")],
+        string="Authenciation method",
+    )
+
+    @api.model
+    def _fastapi_app_fields(self) -> List[str]:
+        fields = super()._fastapi_app_fields()
+        fields.append("demo_auth_method")
+        return fields
+
+
+
+

Dealing with languages

+

The fastapi addon parses the Accept-Language header of the request to +determine the language to use. This parsing is done by respecting the +RFC 7231 +specification. +That means that the language is determined by the first language found +in the header that is supported by odoo (with care of the priority +order). If no language is found in the header, the odoo default language +is used. This language is then used to initialize the Odoo’s environment +context used by the route handlers. All this makes the management of +languages very easy. You don’t have to worry about. This feature is also +documented by default into the generated openapi documentation of your +app to instruct the api consumers how to request a specific language.

+
+
+

How to extend an existing app

+

When you develop a fastapi app, in a native python app it’s not possible +to extend an existing one. This limitation doesn’t apply to the fastapi +addon because the fastapi endpoint model is designed to be extended. +However, the way to extend an existing app is not the same as the way to +extend an odoo model.

+

First of all, it’s important to keep in mind that when you define a +route, you are actually defining a contract between the client and the +server. This contract is defined by the route path, the method (GET, +POST, PUT, DELETE, etc.), the parameters and the response. If you want +to extend an existing app, you must ensure that the contract is not +broken. Any change to the contract will respect the Liskov substitution +principle. +This means that the client should not be impacted by the change.

+

What does it mean in practice? It means that you can’t change the route +path or the method of an existing route. You can’t change the name of a +parameter or the type of a response. You can’t add a new parameter or a +new response. You can’t remove a parameter or a response. If you want to +change the contract, you must create a new route.

+

What can you change?

+
    +
  • You can change the implementation of the route handler.
  • +
  • You can override the dependencies of the route handler.
  • +
  • You can add a new route handler.
  • +
  • You can extend the model used as parameter or as response of the route +handler.
  • +
+

Let’s see how to do that.

+
+

Changing the implementation of the route handler

+

Let’s say that you want to change the implementation of the route +handler ‘/demo/echo’. Since a route handler is just a python method, +it could seems a tedious task since we are not into a model method and +therefore we can’t take advantage of the Odoo inheritance mechanism.

+

However, the fastapi addon provides a way to do that. Thanks to the +‘odoo_env’ dependency method, you can access the current odoo +environment. With this environment, you can access the registry and +therefore the model you want to delegate the implementation to. If you +want to change the implementation of the route handler ‘/demo/echo’, +the only thing you have to do is to inherit from the model where the +implementation is defined and override the method ‘echo’.

+
+from pydantic import BaseModel
+from fastapi import Depends, APIRouter
+from odoo import models
+from odoo.addons.fastapi.dependencies import odoo_env
+
+class FastapiEndpoint(models.Model):
+
+    _inherit = "fastapi.endpoint"
+
+    def _get_fastapi_routers(self) -> List[APIRouter]:
+        routers = super()._get_fastapi_routers()
+        routers.append(demo_api_router)
+        return routers
+
+demo_api_router = APIRouter()
+
+@demo_api_router.get(
+    "/echo",
+    response_model=EchoResponse,
+    dependencies=[Depends(odoo_env)],
+)
+async def echo(
+    message: str,
+    odoo_env: Annotated[Environment, Depends(odoo_env)],
+) -> EchoResponse:
+    """Echo the message"""
+    return EchoResponse(message=odoo_env["demo.fastapi.endpoint"].echo(message))
+
+class EchoResponse(BaseModel):
+    message: str
+
+class DemoEndpoint(models.AbstractModel):
+
+    _name = "demo.fastapi.endpoint"
+    _description = "Demo Endpoint"
+
+    def echo(self, message: str) -> str:
+        return message
+
+class DemoEndpointInherit(models.AbstractModel):
+
+    _inherit = "demo.fastapi.endpoint"
+
+    def echo(self, message: str) -> str:
+        return f"Hello {message}"
+
+

Note

+

It’s a good programming practice to implement the business logic outside +the route handler. This way, you can easily test your business logic +without having to test the route handler. In the example above, the +business logic is implemented in the method ‘echo’ of the model +‘demo.fastapi.endpoint’. The route handler just delegate the +implementation to this method.

+
+
+

Overriding the dependencies of the route handler

+

As you’ve previously seen, the dependency injection mechanism of fastapi +is very powerful. By designing your route handler to rely on +dependencies with a specific functional scope, you can easily change the +implementation of the dependency without having to change the route +handler. With such a design, you can even define abstract dependencies +that must be implemented by the concrete application. This is the case +of the ‘authenticated_partner’ dependency in our previous example. +(you can find the implementation of this dependency in the file +‘odoo/addons/fastapi/dependencies.py’ and it’s usage in the file +‘odoo/addons/fastapi/models/fastapi_endpoint_demo.py’)

+
+
+

Adding a new route handler

+

Let’s say that you want to add a new route handler ‘/demo/echo2’. +You could be tempted to add this new route handler in your new addons by +importing the router of the existing app and adding the new route +handler to it.

+
+from odoo.addons.fastapi.models.fastapi_endpoint_demo import demo_api_router
+
+@demo_api_router.get(
+    "/echo2",
+    response_model=EchoResponse,
+    dependencies=[Depends(odoo_env)],
+)
+async def echo2(
+    message: str,
+    odoo_env: Annotated[Environment, Depends(odoo_env)],
+) -> EchoResponse:
+    """Echo the message"""
+    echo = odoo_env["demo.fastapi.endpoint"].echo2(message)
+    return EchoResponse(message=f"Echo2: {echo}")
+
+

The problem with this approach is that you unconditionally add the new +route handler to the existing app even if the app is called for a +different database where your new addon is not installed.

+

The solution is to define a new router and to add it to the list of +routers returned by the method ‘_get_fastapi_routers’ of the model +‘fastapi.endpoint’ you are inheriting from into your new addon.

+
+class FastapiEndpoint(models.Model):
+
+    _inherit = "fastapi.endpoint"
+
+    def _get_fastapi_routers(self) -> List[APIRouter]:
+        routers = super()._get_fastapi_routers()
+        if self.app == "demo":
+            routers.append(additional_demo_api_router)
+        return routers
+
+additional_demo_api_router = APIRouter()
+
+@additional_demo_api_router.get(
+    "/echo2",
+    response_model=EchoResponse,
+    dependencies=[Depends(odoo_env)],
+)
+async def echo2(
+    message: str,
+    odoo_env: Annotated[Environment, Depends(odoo_env)],
+) -> EchoResponse:
+    """Echo the message"""
+    echo = odoo_env["demo.fastapi.endpoint"].echo2(message)
+    return EchoResponse(message=f"Echo2: {echo}")
+
+

In this way, the new router is added to the list of routers of your app +only if the app is called for a database where your new addon is +installed.

+
+
+

Extending the model used as parameter or as response of the route handler

+

The fastapi python library uses the pydantic library to define the +models. By default, once a model is defined, it’s not possible to extend +it. However, a companion python library called +extendable_pydantic +provides a way to use inheritance with pydantic models to extend an +existing model. If used alone, it’s your responsibility to instruct this +library the list of extensions to apply to a model and the order to +apply them. This is not very convenient. Fortunately, an dedicated odoo +addon exists to make this process complete transparent. This addon is +called +odoo-addon-extendable-fastapi.

+

When you want to allow other addons to extend a pydantic model, you must +first define the model as an extendable model by using a dedicated +metaclass

+
+from pydantic import BaseModel
+from extendable_pydantic import ExtendableModelMeta
+
+class Partner(BaseModel, metaclass=ExtendableModelMeta):
+  name = 0.1
+  model_config = ConfigDict(from_attributes=True)
+
+

As any other pydantic model, you can now use this model as parameter or +as response of a route handler. You can also use all the features of +models defined with pydantic.

+
+@demo_api_router.get(
+    "/partner",
+    response_model=Location,
+    dependencies=[Depends(authenticated_partner)],
+)
+async def partner(
+    partner: Annotated[ResPartner, Depends(authenticated_partner)],
+) -> Partner:
+    """Return the location"""
+    return Partner.model_validate(partner)
+
+

If you need to add a new field into the model ‘Partner’, you can +extend it in your new addon by defining a new model that inherits from +the model ‘Partner’.

+
+from typing import Optional
+from odoo.addons.fastapi.models.fastapi_endpoint_demo import Partner
+
+class PartnerExtended(Partner, extends=Partner):
+    email: Optional[str]
+
+

If your new addon is installed in a database, a call to the route +handler ‘/demo/partner’ will return a response with the new field +‘email’ if a value is provided by the odoo record.

+
+{
+  "name": "John Doe",
+  "email": "jhon.doe@acsone.eu"
+}
+
+

If your new addon is not installed in a database, a call to the route +handler ‘/demo/partner’ will only return the name of the partner.

+
+{
+  "name": "John Doe"
+}
+
+

Note

+

The liskov substitution principle has also to be respected. That means +that if you extend a model, you must add new required fields or you must +provide default values for the new optional fields.

+
+
+
+

Managing security into the route handlers

+

By default the route handlers are processed using the user configured on +the ‘fastapi.endpoint’ model instance. (default is the Public user). +You have seen previously how to define a dependency that will be used to +enforce the authentication of a partner. When a method depends on this +dependency, the ‘authenticated_partner_id’ key is added to the context +of the partner environment. (If you don’t need the partner as dependency +but need to get an environment with the authenticated user, you can use +the dependency ‘authenticated_partner_env’ instead of +‘authenticated_partner’.)

+

The fastapi addon extends the ‘ir.rule’ model to add into the evaluation +context of the security rules the key ‘authenticated_partner_id’ that +contains the id of the authenticated partner.

+

As briefly introduced in a previous section, a good practice when you +develop a fastapi app and you want to protect your data in an efficient +and traceable way is to:

+
    +
  • create a new user specific to the app but with any access rights.
  • +
  • create a security group specific to the app and add the user to this +group. (This group must implies the group ‘AFastAPI Endpoint Runner’ +that give the minimal access rights)
  • +
  • for each model you want to protect:
      +
    • add a ‘ir.model.access’ record for the model to allow read access to +your model and add the group to the record.
    • +
    • create a new ‘ir.rule’ record for the model that restricts the +access to the records of the model to the authenticated partner by +using the key ‘authenticated_partner_id’ in domain of the rule. (or +to the user defined on the ‘fastapi.endpoint’ model instance if the +method is public)
    • +
    +
  • +
  • add a dependency on the ‘authenticated_partner’ to your handlers when +you need to access the authenticated partner or ensure that the +service is called by an authenticated partner.
  • +
+
+<record
+      id="my_demo_app_user"
+      model="res.users"
+      context="{'no_reset_password': True, 'no_reset_password': True}"
+  >
+  <field name="name">My Demo Endpoint User</field>
+  <field name="login">my_demo_app_user</field>
+  <field name="groups_id" eval="[(6, 0, [])]" />
+</record>
+
+<record id="my_demo_app_group" model="res.groups">
+  <field name="name">My Demo Endpoint Group</field>
+  <field name="users" eval="[(4, ref('my_demo_app_user'))]" />
+  <field name="implied_ids" eval="[(4, ref('group_fastapi_endpoint_runner'))]" />
+</record>
+
+<!-- acl for the model 'sale.order' -->
+<record id="sale_order_demo_app_access" model="ir.model.access">
+  <field name="name">My Demo App: access to sale.order</field>
+  <field name="model_id" ref="model_sale_order"/>
+  <field name="group_id" ref="my_demo_app_group"/>
+  <field name="perm_read" eval="True"/>
+  <field name="perm_write" eval="False"/>
+  <field name="perm_create" eval="False"/>
+  <field name="perm_unlink" eval="False"/>
+</record>
+
+<!-- a record rule to allows the authenticated partner to access only its sale orders -->
+<record id="demo_app_sale_order_rule" model="ir.rule">
+  <field name="name">Sale Order Rule</field>
+  <field name="model_id" ref="model_sale_order"/>
+  <field name="domain_force">[('partner_id', '=', authenticated_partner_id)]</field>
+  <field name="groups" eval="[(4, ref('my_demo_app_group'))]"/>
+</record>
+
+
+
+

How to test your fastapi app

+

Thanks to the starlette test client, it’s possible to test your fastapi +app in a very simple way. With the test client, you can call your route +handlers as if they were real http endpoints. The test client is +available in the ‘fastapi.testclient’ module.

+

Once again the dependency injection mechanism comes to the rescue by +allowing you to inject into the test client specific implementations of +the dependencies normally provided by the normal processing of the +request by the fastapi app. (for example, you can inject a mock of the +dependency ‘authenticated_partner’ to test the behavior of your route +handlers when the partner is not authenticated, you can also inject a +mock for the odoo_env etc…)

+

The fastapi addon provides a base class for the test cases that you can +use to write your tests. This base class is +‘odoo.fastapi.tests.common.FastAPITransactionCase’. This class +mainly provides the method ‘_create_test_client’ that you can use +to create a test client for your fastapi app. This method encapsulates +the creation of the test client and the injection of the dependencies. +It also ensures that the odoo environment is make available into the +context of the route handlers. This method is designed to be used when +you need to test your app or when you need to test a specific router +(It’s therefore easy to defines tests for routers in an addon that +doesn’t provide a fastapi endpoint).

+

With this base class, writing a test for a route handler is as simple +as:

+
+from odoo.fastapi.tests.common import FastAPITransactionCase
+
+from odoo.addons.fastapi import dependencies
+from odoo.addons.fastapi.routers import demo_router
+
+class FastAPIDemoCase(FastAPITransactionCase):
+
+    @classmethod
+    def setUpClass(cls) -> None:
+        super().setUpClass()
+        cls.default_fastapi_running_user = cls.env.ref("fastapi.my_demo_app_user")
+        cls.default_fastapi_authenticated_partner = cls.env["res.partner"].create({"name": "FastAPI Demo"})
+
+    def test_hello_world(self) -> None:
+        with self._create_test_client(router=demo_router) as test_client:
+            response: Response = test_client.get("/demo/")
+        self.assertEqual(response.status_code, status.HTTP_200_OK)
+        self.assertDictEqual(response.json(), {"Hello": "World"})
+
+

In the previous example, we created a test client for the demo_router. +We could have created a test client for the whole app by not specifying +the router but the app instead.

+
+from odoo.fastapi.tests.common import FastAPITransactionCase
+
+from odoo.addons.fastapi import dependencies
+from odoo.addons.fastapi.routers import demo_router
+
+class FastAPIDemoCase(FastAPITransactionCase):
+
+    @classmethod
+    def setUpClass(cls) -> None:
+        super().setUpClass()
+        cls.default_fastapi_running_user = cls.env.ref("fastapi.my_demo_app_user")
+        cls.default_fastapi_authenticated_partner = cls.env["res.partner"].create({"name": "FastAPI Demo"})
+
+    def test_hello_world(self) -> None:
+        demo_endpoint = self.env.ref("fastapi.fastapi_endpoint_demo")
+        with self._create_test_client(app=demo_endpoint._get_app()) as test_client:
+            response: Response = test_client.get(f"{demo_endpoint.root_path}/demo/")
+        self.assertEqual(response.status_code, status.HTTP_200_OK)
+        self.assertDictEqual(response.json(), {"Hello": "World"})
+
+
+
+

Overall considerations when you develop an fastapi app

+

Developing a fastapi app requires to follow some good practices to +ensure that the app is robust and easy to maintain. Here are some of +them:

+
    +
  • A route handler must be as simple as possible. It must not contain any +business logic. The business logic must be implemented into the +service layer. The route handler must only call the service layer and +return the result of the service layer. To ease extension on your +business logic, your service layer can be implemented as an odoo +abstract model that can be inherited by other addons.
  • +
  • A route handler should not expose the internal data structure and api +of Odoo. It should provide the api that is needed by the client. More +widely, an app provides a set of services that address a set of use +cases specific to a well defined functional domain. You must always +keep in mind that your api will remain the same for a long time even +if you upgrade your odoo version of modify your business logic.
  • +
  • A route handler is a transactional unit of work. When you design your +api you must ensure that the completeness of a use case is guaranteed +by a single transaction. If you need to perform several transactions +to complete a use case, you introduce a risk of inconsistency in your +data or extra complexity in your client code.
  • +
  • Properly handle the errors. The route handler must return a proper +error response when an error occurs. The error response must be +consistent with the rest of the api. The error response must be +documented in the api documentation. By default, the +‘odoo-addon-fastapi’ module handles the common exception types +defined in the ‘odoo.exceptions’ module and returns a proper error +response with the corresponding http status code. An error in the +route handler must always return an error response with a http status +code different from 200. The error response must contain a human +readable message that can be displayed to the user. The error response +can also contain a machine readable code that can be used by the +client to handle the error in a specific way.
  • +
  • When you design your json document through the pydantic models, you +must use the appropriate data types. For example, you must use the +data type ‘datetime.date’ to represent a date and not a string. +You must also properly define the constraints on the fields. For +example, if a field is optional, you must use the data type +‘typing.Optional’. pydantic +provides everything you need to properly define your json document.
  • +
  • Always use an appropriate pydantic model as request and/or response +for your route handler. Constraints on the fields of the pydantic +model must apply to the specific use case. For example, if your route +handler is used to create a sale order, the pydantic model must not +contain the field ‘id’ because the id of the sale order will be +generated by the route handler. But if the id is required afterwords, +the pydantic model for the response must contain the field ‘id’ as +required.
  • +
  • Uses descriptive property names in your json documents. For example, +avoid the use of documents providing a flat list of key value pairs.
  • +
  • Be consistent in the naming of your fields into your json documents. +For example, if you use ‘id’ to represent the id of a sale order, you +must use ‘id’ to represent the id of all the other objects.
  • +
  • Be consistent in the naming style of your fields. Always prefer +underscore to camel case.
  • +
  • Always use plural for the name of the fields that contain a list of +items. For example, if you have a field ‘lines’ that contains a list +of sale order lines, you must use ‘lines’ and not ‘line’.
  • +
  • You can’t expect that a client will provide you the identifier of a +specific record in odoo (for example the id of a carrier) if you don’t +provide a specific route handler to retrieve the list of available +records. Sometimes, the client must share with odoo the identity of a +specific record to be able to perform an appropriate action specific +to this record (for example, the processing of a payment is different +for each payment acquirer). In this case, you must provide a specific +attribute that allows both the client and odoo to identify the record. +The field ‘provider’ on a payment acquirer allows you to identify a +specific record in odoo. This kind of approach allows both the client +and odoo to identify the record without having to rely on the id of +the record. (This will ensure that the client will not break if the id +of the record is changed in odoo for example when tests are run on an +other database).
  • +
  • Always use the same name for the same kind of object. For example, if +you have a field ‘lines’ that contains a list of sale order lines, you +must use the same name for the same kind of object in all the other +json documents.
  • +
  • Manage relations between objects in your json documents the same way. +By default, you should return the id of the related object in the json +document. But this is not always possible or convenient, so you can +also return the related object in the json document. The main +advantage of returning the id of the related object is that it allows +you to avoid the n+1 +problem . The main +advantage of returning the related object in the json document is that +it allows you to avoid an extra call to retrieve the related object. +By keeping in mind the pros and cons of each approach, you can choose +the best one for your use case. Once it’s done, you must be consistent +in the way you manage the relations of the same object.
  • +
  • It’s not always a good idea to name your fields into your json +documents with the same name as the fields of the corresponding odoo +model. For example, in your document representing a sale order, you +must not use the name ‘order_line’ for the field that contains the +list of sale order lines. The name ‘order_line’ in addition to being +confusing and not consistent with the best practices, is not +auto-descriptive. The name ‘lines’ is much better.
  • +
  • Keep a defensive programming approach. If you provide a route handler +that returns a list of records, you must ensure that the computation +of the list is not too long or will not drain your server resources. +For example, for search route handlers, you must ensure that the +search is limited to a reasonable number of records by default.
  • +
  • As a corollary of the previous point, a search handler must always use +the pagination mechanism with a reasonable default page size. The +result list must be enclosed in a json document that contains the +count of records into the system matching your search criteria and the +list of records for the given page and size.
  • +
  • Use plural for the name of a service. For example, if you provide a +service that allows you to manage the sale orders, you must use the +name ‘sale_orders’ and not ‘sale_order’.
  • +
  • … and many more.
  • +
+

We could write a book about the best practices to follow when you design +your api but we will stop here. This list is the result of our +experience at ACSONE SA/NV and it evolves over +time. It’s a kind of rescue kit that we would provide to a new developer +that starts to design an api. This kit must be accompanied with the +reading of some useful resources link like the REST +Guidelines. On +a technical level, the fastapi +documentation provides a lot of +useful information as well, with a lot of examples. Last but not least, +the pydantic documentation is also very +useful.

+
+
+

Miscellaneous

+
+

Development of a search route handler

+

The ‘odoo-addon-fastapi’ module provides 2 useful piece of code to +help you be consistent when writing a route handler for a search route.

+
    +
  1. A dependency method to use to specify the pagination parameters in +the same way for all the search route handlers: +‘odoo.addons.fastapi.paging’.
  2. +
  3. A PagedCollection pydantic model to use to return the result of a +search route handler enclosed in a json document that contains the +count of records.
  4. +
+
+from typing import Annotated
+from pydantic import BaseModel
+
+from odoo.api import Environment
+from odoo.addons.fastapi.dependencies import paging, authenticated_partner_env
+from odoo.addons.fastapi.schemas import PagedCollection, Paging
+
+class SaleOrder(BaseModel):
+    id: int
+    name: str
+    model_config = ConfigDict(from_attributes=True)
+
+
+@router.get(
+    "/sale_orders",
+    response_model=PagedCollection[SaleOrder],
+    response_model_exclude_unset=True,
+)
+def get_sale_orders(
+    paging: Annotated[Paging, Depends(paging)],
+    env: Annotated[Environment, Depends(authenticated_partner_env)],
+) -> PagedCollection[SaleOrder]:
+    """Get the list of sale orders."""
+    count = env["sale.order"].search_count([])
+    orders = env["sale.order"].search([], limit=paging.limit, offset=paging.offset)
+    return PagedCollection[SaleOrder](
+        count=count,
+        items=[SaleOrder.model_validate(order) for order in orders],
+    )
+
+

Note

+

The ‘odoo.addons.fastapi.schemas.Paging’ and +‘odoo.addons.fastapi.schemas.PagedCollection’ pydantic models are +not designed to be extended to not introduce a dependency between the +‘odoo-addon-fastapi’ module and the ‘odoo-addon-extendable’

+
+
+

Error handling

+

The error handling is a very important topic in the design of the +fastapi integration with odoo. By default, when instantiating the +fastapi app, the fastapi library declare a default exception handler +that will catch any exception raised by the route handlers and return a +proper error response. This is done to ensure that the serving of the +app is not interrupted by an unhandled exception. If this implementation +makes sense for a native fastapi app, it’s not the case for the fastapi +integration with odoo. The transactional nature of the calls to odoo’s +api is implemented at the root of the request processing by odoo. To +ensure that the transaction is properly managed, the integration with +odoo must ensure that the exceptions raised by the route handlers +properly bubble up to the handling of the request by odoo. This is done +by the monkey patching of the registered exception handler of the +fastapi app in the ‘odoo.addons.fastapi.models.error_handlers’ +module. As a result, it’s no longer possible to define a custom +exception handler in your fastapi app. If you add a custom exception +handler in your app, it will be ignored.

+
+
+

FastAPI addons directory structure

+

When you develop a new addon to expose an api with fastapi, it’s a good +practice to follow the same directory structure and naming convention +for the files related to the api. It will help you to easily find the +files related to the api and it will help the other developers to +understand your code.

+

Here is the directory structure that we recommend. It’s based on +practices that are used in the python community when developing a +fastapi app.

+
+.
+├── x_api
+│   ├── data
+│   │   ├── ... .xml
+│   ├── demo
+│   │   ├── ... .xml
+│   ├── i18n
+│   │   ├── ... .po
+│   ├── models
+│   │   ├── __init__.py
+│   │   ├── fastapi_endpoint.py  # your app
+│   │   └── ... .py
+│   └── routers
+│   │   ├── __init__.py
+│   │   ├── items.py
+│   │   └── ... .py
+│   ├── schemas | schemas.py
+│   │   ├── __init__.py
+│   │   ├── my_model.py  # pydantic model
+│   │   └── ... .py
+│   ├── security
+│   │   ├── ... .xml
+│   ├── views
+│   │   ├── ... .xml
+│   ├── __init__.py
+│   ├── __manifest__.py
+│   ├── dependencies.py  # custom dependencies
+│   ├── error_handlers.py  # custom error handlers
+
+
    +
  • The ‘models’ directory contains the odoo models. When you define a +new app, as for the others addons, you will add your new model +inheriting from the ‘fastapi.endpoint’ model in this directory.

    +
  • +
  • The ‘routers’ directory contains the fastapi routers. You will add +your new routers in this directory. Each route starting with the same +prefix should be grouped in the same file. For example, all the routes +starting with ‘/items’ should be defined in the ‘items.py’ file. +The ‘__init__.py’ file in this directory is used to import all +the routers defined in the directory and create a global router that +can be used in an app. For example, in your ‘items.py’ file, you +will define a router like this:

    +
    +router = APIRouter(tags=["items"])
    +
    +router.get("/items", response_model=List[Item])
    +def list_items():
    +    pass
    +
    +

    In the ‘__init__.py’ file, you will import the router and add +it to the global router or your addon.

    +
    +from fastapi import APIRouter
    +
    +from .items import router as items_router
    +
    +router = APIRouter()
    +router.include_router(items_router)
    +
    +
  • +
  • The ‘schemas.py’ will be used to define the pydantic models. For +complex APIs with a lot of models, it will be better to create a +‘schemas’ directory and split the models in different files. The +‘__init__.py’ file in this directory will be used to import all +the models defined in the directory. For example, in your +‘my_model.py’ file, you will define a model like this:

    +
    +from pydantic import BaseModel
    +
    +class MyModel(BaseModel):
    +    name: str
    +    description: str = None
    +
    +

    In the ‘__init__.py’ file, you will import the model’s classes +from the files in the directory.

    +
    +from .my_model import MyModel
    +
    +

    This will allow to always import the models from the schemas module +whatever the models are spread across different files or defined in +the ‘schemas.py’ file.

    +
    +from x_api_addon.schemas import MyModel
    +
    +
  • +
  • The ‘dependencies.py’ file contains the custom dependencies that +you will use in your routers. For example, you can define a dependency +to check the access rights of the user.

    +
  • +
  • The ‘error_handlers.py’ file contains the custom error handlers +that you will use in your routers. The ‘odoo-addon-fastapi’ module +provides the default error handlers for the common odoo exceptions. +Chance are that you will not need to define your own error handlers. +But if you need to do it, you can define them in this file.

    +
  • +
+
+
+
+

What’s next?

+

The ‘odoo-addon-fastapi’ module is still in its early stage of +development. It will evolve over time to integrate your feedback and to +provide the missing features. It’s now up to you to try it and to +provide your feedback.

+
+
+
+

Known issues / Roadmap

+

The +roadmap +and known +issues +can be found on GitHub.

+

The FastAPI module provides an easy way to use WebSockets. +Unfortunately, this support is not ‘yet’ available in the Odoo +framework. The challenge is high because the integration of the fastapi +is based on the use of a specific middleware that convert the WSGI +request consumed by odoo to a ASGI request. The question is to know if +it is also possible to develop the same kind of bridge for the +WebSockets and to stream large responses.

+
+
+

Changelog

+
+

17.0.3.0.0 (2024-10-03)

+
+

Features

+
    +
    • +
    • A new parameter is now available on the endpoint model to let you +disable the creation and the store of session files used by Odoo for +calls to your application endpoint. This is usefull to prevent disk +space consumption and IO operations if your application doesn’t need +to use this sessions files which are mainly used by Odoo by to store +the session info of logged in users. +(#442)
    • +
    +
  • +
+
+
+

Bugfixes

+
    +
  • Fix issue with the retry of a POST request with a body content.

    +

    Prior to this fix the retry of a POST request with a body content +would stuck in a loop and never complete. This was due to the fact +that the request input stream was not reset after a failed attempt to +process the request. +(#440)

    +
  • +
+
+
+
+

17.0.2.0.0 (2024-10-03)

+
+

Bugfixes

+
    +
  • This change is a complete rewrite of the way the transactions are +managed when integrating a fastapi application into Odoo.

    +

    In the previous implementation, specifics error handlers were put in +place to catch exception occurring in the handling of requests made to +a fastapi application and to rollback the transaction in case of +error. This was done by registering specifics error handlers methods +to the fastapi application using the ‘add_exception_handler’ method of +the fastapi application. In this implementation, the transaction was +rolled back in the error handler method.

    +

    This approach was not working as expected for several reasons:

    +
      +
    • The handling of the error at the fastapi level prevented the retry +mechanism to be triggered in case of a DB concurrency error. This is +because the error was catch at the fastapi level and never bubbled +up to the early stage of the processing of the request where the +retry mechanism is implemented.
    • +
    • The cleanup of the environment and the registry was not properly +done in case of error. In the ‘odoo.service.model.retrying’ +method, you can see that the cleanup process is different in case of +error raised by the database and in case of error raised by the +application.
    • +
    +

    This change fix these issues by ensuring that errors are no more catch +at the fastapi level and bubble up the fastapi processing stack +through the event loop required to transform WSGI to ASGI. As result +the transactional nature of the requests to the fastapi applications +is now properly managed by the Odoo framework.

    +

    (#422)

    +
  • +
+
+
+
+

17.0.1.0.1 (2024-10-02)

+
+

Bugfixes

+ +
+
+
+

16.0.1.2.5 (2024-01-17)

+
+

Bugfixes

+
    +
  • Odoo has done an update and now, it checks domains of ir.rule on +creation and modification.

    +

    The ir.rule ‘Fastapi: Running user rule’ uses a field +(authenticatepartner_id) that comes from the context. This field +wasn’t always set and this caused an error when Odoo checked the +domain. So now it is set to False by default. +(``#410 <https://github.com/OCA/rest-framework/issues/410>``)

    +
  • +
+
+
+
+

16.0.1.2.3 (2023-12-21)

+
+

Bugfixes

+
    +
  • In case of exception in endpoint execution, close the database cursor +after rollback.

    +

    This is to ensure that the retrying method in service/model.py +does not try to flush data to the database. +(#405)

    +
  • +
+
+
+
+

16.0.1.2.2 (2023-12-12)

+
+

Bugfixes

+
    +
  • When using the ‘FastAPITransactionCase’ class, allows to specify a +specific override of the ‘authenticated_partner_impl’ method into the +list of overrides to apply. Before this change, the +‘authenticated_partner_impl’ override given in the ‘overrides’ +parameter was always overridden in the ‘_create_test_client’ method +of the ‘FastAPITransactionCase’ class. It’s now only overridden if the +‘authenticated_partner_impl’ method is not already present in the list +of overrides to apply and no specific partner is given. If a specific +partner is given at same time of an override for the +‘authenticated_partner_impl’ method, an error is raised. +(#396)
  • +
+
+
+
+

16.0.1.2.1 (2023-11-03)

+
+

Bugfixes

+
    +
  • Fix a typo in the Field declaration of the ‘count’ attribute of the +‘PagedCollection’ schema.

    +

    Misspelt parameter was triggering a deprecation warning due to recent +versions of Pydantic seeing it as an arbitrary parameter. +(#389)

    +
  • +
+
+
+
+

16.0.1.2.0 (2023-10-13)

+
+

Features

+
    +
  • The field total in the PagedCollection schema is replaced by the +field count. The field total is now deprecated and will be removed +in the next major version. This change is backward compatible. The +json document returned will now contain both fields total and +count with the same value. In your python code the field total, if +used, will fill the field count with the same value. You are +encouraged to use the field count instead of total and adapt your +code accordingly. +(#380)
  • +
+
+
+
+
+

Bug Tracker

+

Bugs are tracked on GitHub Issues. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us to smash it by providing a detailed and welcomed +feedback.

+

Do not contact contributors directly about support or help with technical issues.

+
+
+

Credits

+
+

Authors

+
    +
  • ACSONE SA/NV
  • +
+
+
+

Contributors

+ +
+
+

Maintainers

+

This module is maintained by the OCA.

+Odoo Community Association +

OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use.

+

Current maintainer:

+

lmignon

+

This module is part of the OCA/rest-framework project on GitHub.

+

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.

+
+
+
+ + diff --git a/fastapi/tests/__init__.py b/fastapi/tests/__init__.py new file mode 100644 index 000000000..ea40c354c --- /dev/null +++ b/fastapi/tests/__init__.py @@ -0,0 +1,2 @@ +from . import test_fastapi +from . import test_fastapi_demo diff --git a/fastapi/tests/common.py b/fastapi/tests/common.py new file mode 100644 index 000000000..f9c05b67e --- /dev/null +++ b/fastapi/tests/common.py @@ -0,0 +1,166 @@ +# Copyright 2023 ACSONE SA/NV +# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL). +import logging +from collections.abc import Callable +from contextlib import contextmanager +from functools import partial +from typing import Any + +from starlette import status +from starlette.requests import Request +from starlette.responses import JSONResponse, Response + +from odoo.api import Environment +from odoo.tests import tagged +from odoo.tests.common import TransactionCase + +from odoo.addons.base.models.res_partner import Partner +from odoo.addons.base.models.res_users import Users + +from fastapi import APIRouter, FastAPI +from fastapi.testclient import TestClient + +from ..context import odoo_env_ctx +from ..dependencies import ( + authenticated_partner_impl, + optionally_authenticated_partner_impl, +) +from ..error_handlers import convert_exception_to_status_body + +_logger = logging.getLogger(__name__) + + +def default_exception_handler(request: Request, exc: Exception) -> Response: + """ + Default exception handler that returns a response with the exception details. + """ + status_code, body = convert_exception_to_status_body(exc) + + if status_code == status.HTTP_500_INTERNAL_SERVER_ERROR: + # In testing we want to see the exception details of 500 errors + _logger.error("[%d] Error occurred: %s", exc_info=exc) + + return JSONResponse( + status_code=status_code, + content=body, + ) + + +@tagged("post_install", "-at_install") +class FastAPITransactionCase(TransactionCase): + """ + This class is a base class for FastAPI tests. + + It defines default values for the attributes used to create the test client. + The default values can be overridden by setting the corresponding class attributes. + Default attributes are: + - default_fastapi_app: the FastAPI app to use to create the test client + - default_fastapi_router: the FastAPI router to use to create the test client + - default_fastapi_odoo_env: the Odoo environment that will be used to run + the endpoint implementation + - default_fastapi_running_user: the user that will be used to run the endpoint + implementation + - default_fastapi_authenticated_partner: the partner that will be used to run + to build the authenticated_partner and authenticated_partner_env dependencies + - default_fastapi_dependency_overrides: a dict of dependency overrides that will + be applied to the app when creating the test client + + The test client is created by calling the _create_test_client method. When + calling this method, the default values are used unless they are overridden by + passing the corresponding arguments. + + Even if you can provide a default value for the default_fastapi_app and + default_fastapi_router attributes, you should always provide only one of them. + """ + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) + cls.default_fastapi_app: FastAPI | None = None + cls.default_fastapi_router: APIRouter | None = None + cls.default_fastapi_odoo_env: Environment = cls.env + cls.default_fastapi_running_user: Users | None = None + cls.default_fastapi_authenticated_partner: Partner | None = None + cls.default_fastapi_dependency_overrides: dict[ + Callable[..., Any], Callable[..., Any] + ] = {} + + @contextmanager + def _create_test_client( + self, + app: FastAPI | None = None, + router: APIRouter | None = None, + user: Users | None = None, + partner: Partner | None = None, + env: Environment = None, + dependency_overrides: dict[Callable[..., Any], Callable[..., Any]] = None, + raise_server_exceptions: bool = True, + testclient_kwargs=None, + ): + """ + Create a test client for the given app or router. + + This method is a context manager that yields the test client. It + ensures that the Odoo environment is properly set up when running + the endpoint implementation, and cleaned up after the test client is + closed. + + Pay attention to the **'raise_server_exceptions'** argument. It's + default value is **True**. This means that if the endpoint implementation + raises an exception, the test client will raise it. That also means + that if you app includes specific exception handlers, they will not + be called. If you want to test your exception handlers, you should + set this argument to **False**. In this case, the test client will + not raise the exception, but will return it in the response and the + exception handlers will be called. + """ + env = env or self.default_fastapi_odoo_env + user = user or self.default_fastapi_running_user + dependencies = self.default_fastapi_dependency_overrides.copy() + if dependency_overrides: + dependencies.update(dependency_overrides) + if user: + env = env(user=user) + partner = ( + partner + or self.default_fastapi_authenticated_partner + or self.env["res.partner"] + ) + if partner and authenticated_partner_impl in dependencies: + raise ValueError( + "You cannot provide an override for the authenticated_partner_impl " + "dependency when creating a test client with a partner." + ) + if partner or authenticated_partner_impl not in dependencies: + dependencies[authenticated_partner_impl] = partial(lambda a: a, partner) + if partner and optionally_authenticated_partner_impl in dependencies: + raise ValueError( + "You cannot provide an override for the " + "optionally_authenticated_partner_impl " + "dependency when creating a test client with a partner." + ) + if partner or optionally_authenticated_partner_impl not in dependencies: + dependencies[optionally_authenticated_partner_impl] = partial( + lambda a: a, partner + ) + app = app or self.default_fastapi_app or FastAPI() + router = router or self.default_fastapi_router + if router: + app.include_router(router) + app.dependency_overrides = dependencies + + if not raise_server_exceptions: + # Handle exceptions as in FastAPIDispatcher + app.exception_handlers.setdefault(Exception, default_exception_handler) + + ctx_token = odoo_env_ctx.set(env) + testclient_kwargs = testclient_kwargs or {} + try: + yield TestClient( + app, + raise_server_exceptions=raise_server_exceptions, + **testclient_kwargs, + ) + finally: + odoo_env_ctx.reset(ctx_token) diff --git a/fastapi/tests/test_fastapi.py b/fastapi/tests/test_fastapi.py new file mode 100644 index 000000000..37b11a961 --- /dev/null +++ b/fastapi/tests/test_fastapi.py @@ -0,0 +1,171 @@ +# Copyright 2022 ACSONE SA/NV +# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL). + +import os +import unittest +from contextlib import contextmanager + +from odoo import sql_db +from odoo.tests.common import HttpCase +from odoo.tools import mute_logger + +from fastapi import status + +from ..schemas import DemoExceptionType + + +@unittest.skipIf(os.getenv("SKIP_HTTP_CASE"), "EndpointHttpCase skipped") +class FastAPIHttpCase(HttpCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.fastapi_demo_app = cls.env.ref("fastapi.fastapi_endpoint_demo") + cls.fastapi_demo_app._handle_registry_sync() + lang = ( + cls.env["res.lang"] + .with_context(active_test=False) + .search([("code", "=", "fr_BE")]) + ) + lang.active = True + + @contextmanager + def _mocked_commit(self): + with unittest.mock.patch.object( + sql_db.TestCursor, "commit", return_value=None + ) as mocked_commit: + yield mocked_commit + + def _assert_expected_lang(self, accept_language, expected_lang): + route = "/fastapi_demo/demo/lang" + response = self.url_open(route, headers={"Accept-language": accept_language}) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.content, expected_lang) + + def test_call(self): + route = "/fastapi_demo/demo/" + response = self.url_open(route) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.content, b'{"Hello":"World"}') + + def test_lang(self): + self._assert_expected_lang("fr,en;q=0.7,en-GB;q=0.3", b'"fr_BE"') + self._assert_expected_lang("en,fr;q=0.7,en-GB;q=0.3", b'"en_US"') + self._assert_expected_lang("fr-FR,en;q=0.7,en-GB;q=0.3", b'"fr_BE"') + self._assert_expected_lang("fr-FR;q=0.1,en;q=1.0,en-GB;q=0.8", b'"en_US"') + + def test_retrying(self): + """Test that the retrying mechanism is working as expected with the + FastAPI endpoints. + """ + nbr_retries = 3 + route = f"/fastapi_demo/demo/retrying?nbr_retries={nbr_retries}" + response = self.url_open(route, timeout=20) + self.assertEqual(response.status_code, 200) + self.assertEqual(int(response.content), nbr_retries) + + def test_retrying_post(self): + """Test that the retrying mechanism is working as expected with the + FastAPI endpoints in case of POST request with a file. + """ + nbr_retries = 3 + route = f"/fastapi_demo/demo/retrying?nbr_retries={nbr_retries}" + response = self.url_open( + route, timeout=20, files={"file": ("test.txt", b"test")} + ) + self.assertEqual(response.status_code, 200) + self.assertDictEqual(response.json(), {"retries": nbr_retries, "file": "test"}) + + @mute_logger("odoo.http") + def assert_exception_processed( + self, + exception_type: DemoExceptionType, + error_message: str, + expected_message: str, + expected_status_code: int, + ) -> None: + with self._mocked_commit() as mocked_commit: + route = ( + "/fastapi_demo/demo/exception?" + f"exception_type={exception_type.value}&error_message={error_message}" + ) + response = self.url_open(route, timeout=200) + mocked_commit.assert_not_called() + self.assertDictEqual( + response.json(), + { + "detail": expected_message, + }, + ) + self.assertEqual(response.status_code, expected_status_code) + + def test_user_error(self) -> None: + self.assert_exception_processed( + exception_type=DemoExceptionType.user_error, + error_message="test", + expected_message="test", + expected_status_code=status.HTTP_400_BAD_REQUEST, + ) + + def test_validation_error(self) -> None: + self.assert_exception_processed( + exception_type=DemoExceptionType.validation_error, + error_message="test", + expected_message="test", + expected_status_code=status.HTTP_400_BAD_REQUEST, + ) + + def test_bare_exception(self) -> None: + self.assert_exception_processed( + exception_type=DemoExceptionType.bare_exception, + error_message="test", + expected_message="Internal Server Error", + expected_status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + ) + + def test_access_error(self) -> None: + self.assert_exception_processed( + exception_type=DemoExceptionType.access_error, + error_message="test", + expected_message="AccessError", + expected_status_code=status.HTTP_403_FORBIDDEN, + ) + + def test_missing_error(self) -> None: + self.assert_exception_processed( + exception_type=DemoExceptionType.missing_error, + error_message="test", + expected_message="MissingError", + expected_status_code=status.HTTP_404_NOT_FOUND, + ) + + def test_http_exception(self) -> None: + self.assert_exception_processed( + exception_type=DemoExceptionType.http_exception, + error_message="test", + expected_message="test", + expected_status_code=status.HTTP_409_CONFLICT, + ) + + @mute_logger("odoo.http") + def test_request_validation_error(self) -> None: + with self._mocked_commit() as mocked_commit: + route = "/fastapi_demo/demo/exception?exception_type=BAD&error_message=" + response = self.url_open(route, timeout=200) + mocked_commit.assert_not_called() + self.assertEqual(response.status_code, status.HTTP_422_UNPROCESSABLE_ENTITY) + + def test_no_commit_on_exception(self) -> None: + # this test check that the way we mock the cursor is working as expected + # and that the transaction is rolled back in case of exception. + with self._mocked_commit() as mocked_commit: + url = "/fastapi_demo/demo" + response = self.url_open(url, timeout=600) + self.assertEqual(response.status_code, 200) + mocked_commit.assert_called_once() + + self.assert_exception_processed( + exception_type=DemoExceptionType.http_exception, + error_message="test", + expected_message="test", + expected_status_code=status.HTTP_409_CONFLICT, + ) diff --git a/fastapi/tests/test_fastapi_demo.py b/fastapi/tests/test_fastapi_demo.py new file mode 100644 index 000000000..152f560af --- /dev/null +++ b/fastapi/tests/test_fastapi_demo.py @@ -0,0 +1,111 @@ +# Copyright 2022 ACSONE SA/NV +# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL). + +from functools import partial + +from requests import Response + +from odoo.exceptions import UserError +from odoo.tools.misc import mute_logger + +from fastapi import status + +from ..dependencies import fastapi_endpoint +from ..routers import demo_router +from ..schemas import DemoEndpointAppInfo, DemoExceptionType +from .common import FastAPITransactionCase + + +class FastAPIDemoCase(FastAPITransactionCase): + """The fastapi lib comes with a useful testclient that let's you + easily test your endpoints. Moreover, the dependency overrides functionality + allows you to provide specific implementation for part of the code to avoid + to rely on some tricky http stuff for example: authentication + + This test class is an example on how you can test your own code + """ + + @classmethod + def setUpClass(cls) -> None: + super().setUpClass() + cls.default_fastapi_router = demo_router + cls.default_fastapi_running_user = cls.env.ref("fastapi.my_demo_app_user") + cls.default_fastapi_authenticated_partner = cls.env["res.partner"].create( + {"name": "FastAPI Demo"} + ) + + def test_hello_world(self) -> None: + with self._create_test_client() as test_client: + response: Response = test_client.get("/demo/") + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertDictEqual(response.json(), {"Hello": "World"}) + + def test_who_ami(self) -> None: + with self._create_test_client() as test_client: + response: Response = test_client.get("/demo/who_ami") + self.assertEqual(response.status_code, status.HTTP_200_OK) + partner = self.default_fastapi_authenticated_partner + self.assertDictEqual( + response.json(), + { + "name": partner.name, + "display_name": partner.display_name, + }, + ) + + def test_endpoint_info(self) -> None: + demo_app = self.env.ref("fastapi.fastapi_endpoint_demo") + with self._create_test_client( + dependency_overrides={fastapi_endpoint: partial(lambda a: a, demo_app)} + ) as test_client: + response: Response = test_client.get("/demo/endpoint_app_info") + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertDictEqual( + response.json(), + DemoEndpointAppInfo.model_validate(demo_app).model_dump(by_alias=True), + ) + + def test_exception_raised(self) -> None: + with self.assertRaisesRegex(UserError, "User Error"): + with self._create_test_client() as test_client: + test_client.get( + "/demo/exception", + params={ + "exception_type": DemoExceptionType.user_error.value, + "error_message": "User Error", + }, + ) + + with self.assertRaisesRegex(NotImplementedError, "Bare Exception"): + with self._create_test_client() as test_client: + test_client.get( + "/demo/exception", + params={ + "exception_type": DemoExceptionType.bare_exception.value, + "error_message": "Bare Exception", + }, + ) + + @mute_logger("odoo.addons.fastapi.tests.common") + def test_exception_not_raised(self) -> None: + with self._create_test_client(raise_server_exceptions=False) as test_client: + response: Response = test_client.get( + "/demo/exception", + params={ + "exception_type": DemoExceptionType.user_error.value, + "error_message": "User Error", + }, + ) + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertDictEqual(response.json(), {"detail": "User Error"}) + + with self._create_test_client(raise_server_exceptions=False) as test_client: + response: Response = test_client.get( + "/demo/exception", + params={ + "exception_type": DemoExceptionType.bare_exception.value, + "error_message": "Bare Exception", + }, + ) + self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR) + self.assertDictEqual(response.json(), {"detail": "Internal Server Error"}) diff --git a/fastapi/views/fastapi_endpoint.xml b/fastapi/views/fastapi_endpoint.xml new file mode 100644 index 000000000..77b04fd9b --- /dev/null +++ b/fastapi/views/fastapi_endpoint.xml @@ -0,0 +1,136 @@ + + + + + fastapi.endpoint.form (in fastapi) + fastapi.endpoint + +
+
+ + + +
+
+ + +
+
+ + + + + + + + + + + + + + + + +
+ + + + + + fastapi.endpoint.search (in fastapi) + fastapi.endpoint + + + + + + + + + + + + + + fastapi.endpoint.tree (in fastapi) + fastapi.endpoint + + + + + + + + + + +