REST API Generator ================== BESSER offers a code generator for `REST API `_ utilizing the `FastAPI framework `_. This tool automatically transforms classes and relationships defined in a :doc:`../buml_language/model_types/structural` into a RESTful service. Let's generate the code for the REST model of our :doc:`../examples/library_example` structural model example. You should create a ``RESTAPIGenerator`` object, provide the :doc:`../buml_language/model_types/structural`, and use the ``generate`` method as follows: .. code-block:: python from besser.generators.rest_api import RESTAPIGenerator rest_api = RESTAPIGenerator(model=library_model, http_methods=["GET", "POST", "PUT", "PATCH", "DELETE"], backend=False) rest_api.generate() Parameters ---------- - ``model``: The input B-UML structural model (required). - ``http_methods``: List of HTTP methods to generate (default: ``["GET", "POST", "PUT", "PATCH", "DELETE"]``). - ``backend``: When ``True``, generates ``main_api.py`` suitable for :doc:`BackendGenerator ` integration instead of standalone ``rest_api.py`` (default: ``False``). - ``port``: Port number for the generated FastAPI app (optional). - ``output_dir``: Output directory (default: ``output/`` in the current directory). .. note:: **REST API vs. Backend Generator**: The REST API generator produces API endpoints and Pydantic models only. The :doc:`Backend generator ` builds on top of this by also generating SQLAlchemy ORM models and database setup. Use the REST API generator when you only need API scaffolding; use the Backend generator when you need a complete backend with database. Output Files ------------ The generator creates two files in the output directory: - ``rest_api.py`` (or ``main_api.py`` when ``backend=True``): FastAPI application with CRUD endpoints for each class. - ``pydantic_classes.py``: Pydantic validation models generated by the :doc:`Pydantic generator `. The generated output for the library example is shown below. .. literalinclude:: ../../../tests/BUML/metamodel/structural/library/output/rest_api.py :language: python :linenos: When you run the code generated, the OpenAPI specifications will be generated: .. code-block:: json { "openapi": "3.1.0", "info": { "title": "FastAPI", "version": "0.1.0" }, "paths": { "/author/": { "get": { "tags": [ "author" ], "summary": "Get Author", "operationId": "get_author_author__get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "items": { "$ref": "#/components/schemas/Author" }, "type": "array", "title": "Response Get Author Author Get" }}}}}}}}} .. note:: The full OpenAPI specification is available at ``http://localhost:8000/docs`` when you run the generated FastAPI application with ``uvicorn rest_api:app``.