# I Want To Create An Api of notification In Django Rest API

**URL:** <https://forum.djangoproject.com/t/i-want-to-create-an-api-of-notification-in-django-rest-api/25775>\
**Category:** Async/Channels\
**Created:** [November 30, 2023, 10:36am UTC](https://forum.djangoproject.com/t/i-want-to-create-an-api-of-notification-in-django-rest-api/25775 "2023-11-30T10:36:39Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![hamzaabialal](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/hamzaabialal/32/15274_2.png) [@hamzaabialal](https://forum.djangoproject.com/u/hamzaabialal)\
**Post date:** [November 30, 2023, 10:36am UTC](https://forum.djangoproject.com/t/i-want-to-create-an-api-of-notification-in-django-rest-api/25775/1 "2023-11-30T10:36:39Z")

</div>

![Screenshot from 2023-11-30 03-30-39](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/3X/3/0/3019fca979e0f13ae93c92087f1275184277845d.png)  
I Created AN Notification App By Using The Django Channels, Websockt and Successfully Sending Notification To The `Webscoketking.com`, Now I Want To Create The API of This App For Sending The Notifications Of the Website  
models.py

```auto
from django.db import models
from django.contrib.auth.models import AbstractUser
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
import json
# Create your models here.

class CustomUser(AbstractUser):

    """Model class for users"""

    USER_CHOICES = [
        ('expert', 'Expert'),
        ('business', 'Business'),
        ('admin', 'Admin'),
    ]

    username = models.CharField(max_length=40, null=True, blank=True)
    full_name = models.CharField(max_length=40)
    email = models.EmailField(unique=True)
    password = models.CharField(max_length=40, null=False, blank=False)
    confirm_password = models.CharField(max_length=40, null=False, blank=False)
    user_choices = models.CharField(max_length=30, choices=USER_CHOICES, default='expert')

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    def __str__ (self) -> str:
        return f"{self.email}"

class Notification(models.Model):
    account_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    message = models.TextField()
    is_read = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def save(self, *args, **kwargs):
        print('saving notification')
        channel_layer = get_channel_layer()
        notification_objs = Notification.objects.filter(is_read=False).count()
        data = {'count': notification_objs, 'current_notification': self.message}
        async_to_sync(channel_layer.group_send)(
            "test_group", {
                "type": "send_notification",
                "value": json.dumps(data)
            }
        )
        super(Notification, self).save(*args, **kwargs)

class AccountApproval(models.Model):
    account_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    approved = models.BooleanField(default=False)
    approval_message = models.TextField(blank=True, null=True)

```

COnsumers.py

```auto
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
import json

class TestConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = "test"
        self.room_group_name = "test_group"
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name,
        )
        self.accept()
        print("connected")
        self.send(text_data=json.dumps({'status': 'connected Through Django Channels'}))

    def receive(self, text_data):
        print(text_data)
        self.send(text_data=json.dumps({'status': 'We Got You'}))

    def disconneted(self, *args, **kwargs):
        print("disconnected")

    def send_notification(self, event):
        print('Send Notification: ')
        data = json.loads(event.get('value'))
        self.send(text_data=json.dumps({'status': data}))

        print('Send Notification: ')

```

asgi.py

```auto
"""
ASGI config for hamza project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""
from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import path
from bilal.consumers import TestConsumer
import os
from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hamza.settings')

asgiapplication = get_asgi_application()

ws_pattern = [
    path('ws/test/', TestConsumer.as_asgi())
]

application = ProtocolTypeRouter({
    'http': get_asgi_application(),
    'websocket': URLRouter(ws_pattern)
})

```

---

<div class="post-metadata">

**Author:** ![hamzaabialal](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/hamzaabialal/32/15274_2.png) [@hamzaabialal](https://forum.djangoproject.com/u/hamzaabialal)\
**Post date:** [November 30, 2023, 10:37am UTC](https://forum.djangoproject.com/t/i-want-to-create-an-api-of-notification-in-django-rest-api/25775/2 "2023-11-30T10:37:32Z")

</div>

I Want To Create AN Api Or Serializer of This Notification App

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 30, 2023, 12:57pm UTC](https://forum.djangoproject.com/t/i-want-to-create-an-api-of-notification-in-django-rest-api/25775/3 "2023-11-30T12:57:45Z")

</div>

Please be more specific. What do you want this API to do? (Keep in mind that an API receives one request and returns one response, and that unlike a websocket, an API cannot initiate a response in the absence of a request.)

---

<div class="post-metadata">

**Author:** ![hamzaabialal](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/hamzaabialal/32/15274_2.png) [@hamzaabialal](https://forum.djangoproject.com/u/hamzaabialal)\
**Post date:** [December 1, 2023, 10:27am UTC](https://forum.djangoproject.com/t/i-want-to-create-an-api-of-notification-in-django-rest-api/25775/4 "2023-12-01T10:27:55Z")

</div>

i Want The To Create APi of the Functionality Of Notifications , WHich APi is Used By Front End Developer For Showing The Notifications on Front End

---

<div class="post-metadata">

**Author:** ![hamzaabialal](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/hamzaabialal/32/15274_2.png) [@hamzaabialal](https://forum.djangoproject.com/u/hamzaabialal)\
**Post date:** [December 1, 2023, 10:45am UTC](https://forum.djangoproject.com/t/i-want-to-create-an-api-of-notification-in-django-rest-api/25775/5 "2023-12-01T10:45:58Z")

</div>

Is You Have Any Youtube Link Where I learn How To Create APi of Notification Functionality

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 1, 2023, 12:50pm UTC](https://forum.djangoproject.com/t/i-want-to-create-an-api-of-notification-in-django-rest-api/25775/6 "2023-12-01T12:50:26Z")

</div>

> [@hamzaabialal](#):
>
> i Want The To Create APi of the Functionality Of Notifications

This doesn’t answer my question, so I’ll rephrase it this way.

Imagine you have this API.

Some JavaScript code in your browser calls this API at some point in time.

What do you want to have happen on the server?

- What do you want the server to return as data?
- How soon after the API call is made do you want this data returned?

> [@hamzaabialal](#):
>
> How To Create APi of Notification Functionality

I can’t, because from the description you’ve provided so far, this doesn’t make any sense to me.

A websocket allows the server to initiate the transfer of data as a “server push”, where an API exposed to the client is a “browser pull”. They’re fundamentally two different operations.

That’s why I’m asking you to define what it is that you want this API to do - and to provide this definition _without_ referring to the notification code shown above.
