53 lines
2.2 KiB
Markdown
Raw Normal View History

2022-01-25 13:53:31 -05:00
# REST API
2022-03-08 14:15:22 -05:00
Plugins can declare custom endpoints on NetBox's REST API to retrieve or manipulate models or other data. These behave very similarly to views, except that instead of rendering arbitrary content using a template, data is returned in JSON format using a serializer.
2022-01-25 13:53:31 -05:00
2022-03-08 14:15:22 -05:00
Generally speaking, there aren't many NetBox-specific components to implementing REST API functionality in a plugin. NetBox employs the [Django REST Framework](https://www.django-rest-framework.org/) (DRF) for its REST API, and plugin authors will find that they can largely replicate the same patterns found in NetBox's implementation. Some brief examples are included here for reference.
## Serializers
First, create a serializer for the plugin model, in `api/serializers.py`. Specify its model class and the fields to include within the serializer's `Meta` class.
2022-01-25 13:53:31 -05:00
```python
from rest_framework.serializers import ModelSerializer
2022-03-08 14:15:22 -05:00
from my_plugin.models import MyModel
2022-01-25 13:53:31 -05:00
2022-03-08 14:15:22 -05:00
class MyModelSerializer(ModelSerializer):
2022-01-25 13:53:31 -05:00
class Meta:
2022-03-08 14:15:22 -05:00
model = MyModel
fields = ('id', 'foo', 'bar')
2022-01-25 13:53:31 -05:00
```
2022-03-08 14:15:22 -05:00
## Views
Next, create a generic API view set that allows basic CRUD (create, read, update, and delete) operations for objects. This is defined in `api/views.py`. Specify the `queryset` and `serializer_class` attributes under the view set.
2022-01-25 13:53:31 -05:00
```python
from rest_framework.viewsets import ModelViewSet
2022-03-08 14:15:22 -05:00
from my_plugin.models import MyModel
from .serializers import MyModelSerializer
2022-01-25 13:53:31 -05:00
2022-03-08 14:15:22 -05:00
class MyModelViewSet(ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
2022-01-25 13:53:31 -05:00
```
2022-03-08 14:15:22 -05:00
## URLs
2022-01-25 13:53:31 -05:00
Finally, we'll register a URL for our endpoint in `api/urls.py`. This file **must** define a variable named `urlpatterns`.
```python
from rest_framework import routers
2022-03-08 14:15:22 -05:00
from .views import MyModelViewSet
2022-01-25 13:53:31 -05:00
router = routers.DefaultRouter()
2022-03-08 14:15:22 -05:00
router.register('my-model', MyModelViewSet)
2022-01-25 13:53:31 -05:00
urlpatterns = router.urls
```
2022-03-08 14:15:22 -05:00
With these three components in place, we can request `/api/plugins/my-plugin/my-model/` to retrieve a list of all MyModel instances.
2022-01-25 13:53:31 -05:00
!!! warning
2022-03-08 14:15:22 -05:00
This example is provided as a minimal reference implementation only. It does not address authentication, performance, or myriad other concerns that plugin authors may need to address.