FastAPI ( Python ) CRUD extensions

Status
Not open for further replies.

juca

New Member
Sep 28, 2024
4
0
1
20
Pessoal preciso de ajuda com um problema, ou tentar entender como eu posso implementar isso no FusionPBX.

Fiz uma API com Python ( FastAPI ) que gerencia o PostgreSQL do FusionPBX, API funciona, eu consigo cirar, editar, buscar e apagar ramais no FusionPBX, mas de alguma forma as funcionaliades parece que não se aplicam a API funciona apenas visualmente falando, por exemplo, se eu criar uma Ramal pela API eu consigo me conectar nesse ramal, mas não consigo fazer ligações, ai se eu acessar o painel do FusionPBX e fizer alguma alteração nesse ramal as funcionalidades funcionam.

Queria ver com vocês se alguém sabe alguma forma de usar uma API ( CRUD ) para gerenciar os ramais do FusionPBX, eu fiz uma que funciona mas parece que falta algo a mais para deixar tudo OK.

~~ en:


Guys, I need help with a problem, or trying to understand how I can implement this in FusionPBX.

I created an API with Python (FastAPI) that manages FusionPBX's PostgreSQL, the API works, I can create, edit, search and delete extensions in FusionPBX, but somehow the features don't seem to apply. The API only works visually speaking, so For example, if I create an Extension via the API I can connect to that extension, but I cannot make calls, then if I access the FusionPBX panel and make any changes to that extension, the features work.

I wanted to see if anyone knows any way to use an API (CRUD) to manage FusionPBX extensions, I made one that works but it seems like there's something else missing to make everything OK.


API: https://github.com/josuejuca/api-pbx
 

DigitalDaz

Administrator
Staff member
Sep 29, 2016
3,070
577
113
Hi Juca, at a guess, even without taken a look at the code, you need to flush the cache. This is what would be happening if you edit an extension in the gui.

Code:
rm /var/cache/fusionpbx/*
 

pbxgeek

Active Member
Jan 19, 2021
183
63
28
37
Flushing cache is the first step but there is a lot more happening behind the scenes when you use GUI to create extensions, voicemails, phone numbers, IVRs and such. Some of these create XML files. The bottom line is that managing database through API is not enough to successfully manage FusionPBX. What are you actually trying to achieve here and why are you not using the GUI?
 

Adrian Fretwell

Well-Known Member
Aug 13, 2017
1,498
413
83
I think for extension creating, you may need a hook to create the voicemail record as well. If you are editing an existing extension then you almost certainly will need to flush the cache as pointed out above.

If you are creating your own API, then you may learn a little by looking at the API available in DjangoPBX. We have organisations here in the UK who interact with DjangoPBX only by using the API. Creating domains, extensions etc.

For you convenience I include here, a python code that creates the extension API endpoint and also a screenshot of using the browsable API, note the "Extra Actions" which allow the API to flush the cache when required and also the "perform_create" function calls for the creation of the voicemail record.

extension_api.jpg

Python:
class ExtensionViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows Extensions to be viewed or edited.
    """
    queryset = Extension.objects.all().order_by('domain_id', 'extension')
    serializer_class = ExtensionSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['domain_id', 'toll_allow', 'call_group', 'user_context', 'enabled']
    permission_classes = [
        permissions.IsAuthenticated,
        AdminApiAccessPermission,
    ]

    def perform_update(self, serializer):
        serializer.save(updated_by=self.request.user.username)

    def perform_create(self, serializer):
        obj = serializer.save(updated_by=self.request.user.username)
        VoicemailFunctions().create_vm_record(obj, self.request.user.username)

    @action(detail=False)
    def flush_cache_all_directories(self, request):
        i = 0
        qs = Domain.objects.filter(enabled='true')
        for d in qs:
            ClearCache().directory(d.name)
            i += 1
        return Response({'status': 'directory cache flushed', 'count': i})

    @action(detail=True)
    def flush_cache_directory(self, request, pk=None):
        obj = self.get_object()
        ClearCache().directory(obj.domain_id.name)
        return Response({'status': 'directory cache flushed'})
 

juca

New Member
Sep 28, 2024
4
0
1
20
Flushing cache is the first step but there is a lot more happening behind the scenes when you use GUI to create extensions, voicemails, phone numbers, IVRs and such. Some of these create XML files. The bottom line is that managing database through API is not enough to successfully manage FusionPBX. What are you actually trying to achieve here and why are you not using the GUI?
~~ en
I understand that my idea of creating this API for FusionPBX is to integrate the functionality currently available in the GUI (to create, delete, edit, and remove extensions) into a system we have for condominiums. With this API, we want to integrate some of the CRUD functionalities of extensions into certain automations.

From what I understand, there’s more to it than just editing the database. Can you help me with some ideas on what to do? We really need this to work, but we’re not sure where to start. I saw that there’s an API Key in the FusionPBX GUI; how do I use this API, and what is it for?
~~ pt
Entendi, a minha ideia de criar essa API para o FusionPBX é para conseguir integrar a funcionalidade que tem hoje em dia no GUI ( de criar, apagar, editar e remover os ramais ) em uma sistema que possuímos para condomínios. Com essa API queríamos conseguir colocar algumas funcionalidades do CRUD do ramal em algumas automações. Pelo que entendi tem muito mais do que apenas editar o banco de dados, consegue me ajudar com alguma ideia do que fazer? Realmente precisamos que isso funcione, mas não sabemos por onde começar, vi que no GUI do Fusion tem um API Key, essa API como uso ela, ela serve para que?



Captura de tela 2024-10-19 152244.png
 

juca

New Member
Sep 28, 2024
4
0
1
20
I think for extension creating, you may need a hook to create the voicemail record as well. If you are editing an existing extension then you almost certainly will need to flush the cache as pointed out above.

If you are creating your own API, then you may learn a little by looking at the API available in DjangoPBX. We have organisations here in the UK who interact with DjangoPBX only by using the API. Creating domains, extensions etc.

For you convenience I include here, a python code that creates the extension API endpoint and also a screenshot of using the browsable API, note the "Extra Actions" which allow the API to flush the cache when required and also the "perform_create" function calls for the creation of the voicemail record.

View attachment 4336

Python:
class ExtensionViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows Extensions to be viewed or edited.
    """
    queryset = Extension.objects.all().order_by('domain_id', 'extension')
    serializer_class = ExtensionSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['domain_id', 'toll_allow', 'call_group', 'user_context', 'enabled']
    permission_classes = [
        permissions.IsAuthenticated,
        AdminApiAccessPermission,
    ]

    def perform_update(self, serializer):
        serializer.save(updated_by=self.request.user.username)

    def perform_create(self, serializer):
        obj = serializer.save(updated_by=self.request.user.username)
        VoicemailFunctions().create_vm_record(obj, self.request.user.username)

    @action(detail=False)
    def flush_cache_all_directories(self, request):
        i = 0
        qs = Domain.objects.filter(enabled='true')
        for d in qs:
            ClearCache().directory(d.name)
            i += 1
        return Response({'status': 'directory cache flushed', 'count': i})

    @action(detail=True)
    def flush_cache_directory(self, request, pk=None):
        obj = self.get_object()
        ClearCache().directory(obj.domain_id.name)
        return Response({'status': 'directory cache flushed'})
~~en
I understand, how does DjangoPBX work? My need is to be able to create extensions, and I thought of using FusionPBX for this, but then another need arose to manage the extensions (CRUD) through a different interface. That's why I'm trying to create this API. Can you help me build this API, or do you know of an alternative system where I can create extensions and that has a management API?
~~ pt
Entendi, o DjangoPBX funciona de que maneira? a minha necessidade é conseguir criar ramais pensei em usar o FusionPBX para isso, mas ai surgiu outra necessidade necessidade de conseguir fazer a gestão dos ramais (CRUD) por uma outra interface, por isso estou tentando faze essa API. Consegue me ajudar a fazer essa API, ou sabe alguma alternativa de sistema aonde posso criar ramais e que tenha uma API de gestão.
 

Adrian Fretwell

Well-Known Member
Aug 13, 2017
1,498
413
83
I understand, how does DjangoPBX work?
As shown above.
The API endpoint has a perform create function and this causes both the creation of the extension record (serializer.save) and an associated voicemail record (VoicemailFunctions().create_vm_record).

Python:
    def perform_create(self, serializer):
        obj = serializer.save(updated_by=self.request.user.username)
        VoicemailFunctions().create_vm_record(obj, self.request.user.username)
 
Status
Not open for further replies.