django view - apiview decorator (urls.py config)

The @api_view decorator in Django is used to define API views. It is typically used in the views.py file to specify that a function-based view is an API view.

Here's a step-by-step explanation of how to use the @api_view decorator in the urls.py configuration:

  1. Import the api_view decorator from the rest_framework.decorators module. This can be done by adding the following line at the top of the urls.py file:

python from rest_framework.decorators import api_view

  1. Define a function-based view that will handle the API request. This function will contain the logic for processing the request and returning a response. For example:

python @api_view(['GET']) def my_api_view(request): # Handle the GET request and return a response return Response({'message': 'Hello, World!'})

In this example, the my_api_view function is decorated with the @api_view(['GET']) decorator, indicating that it will handle only GET requests.

Note that the api_view decorator takes a list of HTTP methods as an argument. This allows you to specify which HTTP methods the view should handle. For example, @api_view(['GET', 'POST']) would indicate that the view can handle both GET and POST requests.

  1. In the urls.py file, define a URL pattern that maps the API endpoint to the corresponding view function. This can be done using the path or re_path functions provided by Django. For example:

```python from .views import my_api_view

urlpatterns = [ path('api/my-endpoint/', my_api_view), ] ```

In this example, the my_api_view function is mapped to the /api/my-endpoint/ URL. Any requests made to this URL will be handled by the my_api_view function.

That's it! With these steps, you can use the @api_view decorator to define API views in Django and map them to URL patterns in the urls.py configuration.