Skip to content

API

What is it ?

This folder containes the code that is responsible for the REST API paired with OpenCVE. An API is a set of functions that are usable via API requests.

Info

If you want to learn more about what is an API and REST API, you can check it here

How does it work ?

The init.py file

This file allows us to bind the API functions to API routes in the following way:

# Example
# Import of the functions declared in the API files
from opencve.api.cves import CveListResource, CveResource

api_bp = Blueprint("api", __name__)
api = Api(api_bp)

# Bindings
api.add_resource(CveListResource, "/cve")
api.add_resource(CveResource, "/cve/<string:id>")

The base.py file

This file defines the base functions that are used by the API.

The fields.py file

This file allows us to define the API response field structure in the following way:

# Example
class VendorsListField(fields.Raw):
    """
    Returns a list of vendors.
    """

    def format(self, vendors):
        return sorted([vendor.name for vendor in vendors])

The API object files

Those files allow us to define the functions that allow us to interact with the database objects.

# Example
# Definition of the different fields structure
category_list_fields = {
    "name": fields.String(attribute="name"),
    "human_name": HumanizedNameField(attribute="name"),
}

category_fields = dict(
    category_list_fields,
    **{
        "products": ProductsListField(attribute="products"),
        "vendors": VendorsListField(attribute="vendors"),
    },
)

# Example of function that returns a list of categories
class CategoryListResource(BaseResource):
    @marshal_with(category_list_fields)
    def get(self):
        return CategoryController.list_items(request.args)