LogoLogo
www.mikopbx.comTelegram communityForum
English
English
  • MikoPBX Manual
    • Quick start
    • Getting to know MikoPBX
    • System requirements
  • Installation
    • Standalone Computer
    • Virtual Machine
      • VMware ESXi
      • VMware Fusion
      • VirtualBOX
      • VMware Workstation Pro
      • Hyper-V
      • Proxmox
    • Cloud
      • AWS
        • AWS deployment guide
        • AWS Marketplace
      • Microsoft Azure
      • Google Cloud
        • Google Cloud deployment guide
        • Google Cloud Marketplace
      • Hetzner cloud (In dev)
      • Digital Ocean
      • Alibaba Cloud
      • Vultr
    • Docker container
      • Docker installation and creating a user and directories
      • Running MikoPBX in a container
      • Running MikoPBX using docker compose
  • User manual
    • Telephony
      • Extensions
      • Call queues
      • IVR Menu
      • Conferences
      • Sound files
      • Call detail records (CDR)
    • Call Routing
      • Telephony providers
      • Incoming routing
      • Outbound routing
      • Night and Holiday Switch
    • Modules
      • Registration in the modules marketplace
      • Module management
      • Application dialplans
    • Maintenance
      • PBX update
        • Updating from the web interface
        • Updating from the MikoPBX console
        • Updating the docker
      • System log entries
      • Reboot
    • Network and Firewall
      • Network interface
      • Firewall
      • Anti brute force
    • System
      • General settings
      • Time Settings
      • Mail settings
        • Setting up E-mail notifications for the Gmail mail service
      • Asterisk Manager Interface(AMI)
      • System files customisation
  • FAQ
    • Setup
      • Installation on MDADM RAID1
      • Fine-tuning the firewall
      • Migrating MikoPBX to Another Server
        • Transfer Using Backup
        • Transfer using scheduled backup (SFTP)
        • Transfer using rsync
      • Reset to factory settings
      • Monitoring Providers on MikoPBX
    • Management
      • Change the login name
      • The extra disk space has run out, the disk size has increased
      • Storing Recordings in a Shared Windows Folder
      • Resetting WEB Interface Credentials
      • Backup Internet and Provider Re-Registration
    • Troubleshooting
      • Connecting to the PBX using SSH
        • Connecting to PBX using SSH client (Putty)
        • Connecting via SSH (Windows)
        • Connecting via SSH (Linux/MacOS)
      • Connecting to a PBX using WinSCP
      • Getting logs using the tcpdump application
      • Capturing Logs from PBX using Wireshark
      • Traffic Analysis Using Sngrep
      • Adjusting the volume
      • Troubleshooting sound problems
      • Jitter Configuration
    • Incoming Routing
      • Choosing a provider when redirecting to a mobile
      • Notification of Employment, Call Waiting
      • Black and white lists
      • Allow additional dialing of the internal number in the queue
      • Output of information about the did number
      • Setting individual non-working hours for a provider account
      • An example of the implementation of a typical route of incoming calls
      • Routing by DID Number
      • Normalization of incoming phone number
      • Basic IVR example
    • Outbound routing
      • Add P-Preferred-Identity and Remote-Party-ID header
      • Conference with a regular external subscriber
      • Outgoing with internal number dialing
      • Remove all special characters from the dialed number
      • Prohibiting calls via a backup route
      • Calls to emergency numbers
      • Number Templates
        • Uniform distribution of outgoing
        • Sample template: calls to another country
        • How to prohibit the replacement of "+" with 00
        • Changing the number prefix from "+345" to "347"
        • Changing the number prefix from "345, 347" to "+345"
        • Removing the area code from the number
        • Adding the prefix "1" to the number
      • Making Calls Through a Specific Provider
    • Scenarios and cases
      • Generate extensions by REST API
      • Missed Call Telegram Notifications
      • Call the company from your mobile and dial an extension to call a third-party company
      • Sending an incoming fax to email
      • Customer's assessment of the quality of service
      • Simulation of external calls
      • Disabling "off-hours" for VIP numbers
      • Registering multiple accounts from one provider
      • Setting up individual non-working hours for several providers on one host
      • Disable forwarding to mobile for internal calls
      • Unique background music for the queue
      • Pause for Queue agent
      • Dynamic Queue Agents
      • Setting up the "Paging" function
      • Limit the number of authorizations per SIP account
      • Call Monitoring (ChanSpy)
      • Conversion of Call History FreePBX -> MikoPBX
      • SSL Certificate for MikoPBX Web Interface from OPNSense
      • Hiding the Caller’s Number from Employees
    • Interconnections
      • Merging two MikoPBX
      • Integration of MikoPBX and Grandstream UCM6202
      • MikoPBX and FreePBX (PJSIP)
      • MikoPBX and FreePBX (IAX)
    • VoIP providers
      • Mango
      • Zadarma
    • Softphones
      • Bria Solo
      • Sessiontalk
      • MicroSIP
      • Groundwire
      • Zoiper
      • Jitsi
      • PhonerLite
      • Linphone (MacOS)
      • Telephone(MacOS)
      • Configuring webRTC client SIMPL5
      • Softphone.pro
      • 3CX Softphone
      • PortSIP
    • IP telefones
      • Snom D120
      • Yealink T19
    • VoIP gateways
      • GoIP4
      • Grandstream HT503
      • Using a Huawei E173 USB Modem for Calls (chan_dongle)
  • Modules
    • MIKO modules
      • for 1C:Enterprise
        • Панель телефонии 4.0 для 1С
        • Панель телефонии 1.0 для 1С
        • Модуль умной маршрутизации
      • Users groups
      • CRM Bitrix24 integration
      • Autoprovision
      • Let's Encrypt
      • Access control management
      • Module auto dialer
      • Backup
      • Synchronization with LDAP/AD
      • Callback module
      • Extended call history
  • other
    • Changelog
      • MikoPBX 2024.1
      • MikoPBX 2023.2
      • MikoPBX 2023.1.223
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub
Export as PDF
  1. FAQ
  2. Scenarios and cases

Generate extensions by REST API

Example of using REST API to generate employees

In release 2023.2, an API for quickly creating a large number of employees was implemented. During testing, we described the algorithm for generating new employees in ChatGPT and conducted stress testing for creating 700 random accounts in different languages. It took about 1 minute to complete the load test, and it was successful.

To perform this task, a request to ChatGPT was written with the following content.

{"jsonapi":{"version":"1.0"},
    "result":true,
    "data":
        {
            "type":"SIP",
            "show_in_phonebook":"1",
            "is_general_user_number":"1",
            "public_access":"0",
            "number":"275",
            "user_id":"",
            "user_avatar":"",
            "user_username":"",
            "user_email":"",
            "mobile_uniqid":"EXTERNAL-7870338E",
            "mobile_number":"",
            "mobile_dialstring":"",
            "sip_uniqid":"SIP-PHONE-5A230111",
            "sip_secret":"Nk9oOFI2ZXdDMEU9",
            "sip_type":"peer",
            "sip_qualify":"1",
            "sip_qualifyfreq":60,
            "sip_enableRecording":"1",
            "sip_dtmfmode":"auto",
            "sip_transport":" ",
            "sip_networkfilterid":"none",
            "sip_manualattributes":"",
            "fwd_ringlength":45,
            "fwd_forwarding":"",
            "fwd_forwardingonbusy":"",
            "fwd_forwardingonunavailable":""
        },
    "messages":[],
    "function":"getRecord",
    "processor":"MikoPBX\\PBXCoreREST\\Lib\\Extensions\\GetRecord::main",
    "pid":42448,
    "meta":{
        "timestamp":"2023-09-06T08:51:51+03:00",
        "hash":"a16f973985cb3d0cbe75abb2c10a7c39b2203a87"
        }
}

If the result parameter in the response is true, we will take the data for creating a new user from the data parameter and make a POST request to the address http://127.0.0.1:8081/pbxcore/api/extensions/saveRecord, using the modified array of form fields in x-www-form-urlencoded format.

The script should be written in Python without using NodeJS and should allow creating 100 different employees. In the user_username field, enter the name and surname of a random person so that national alphabets are used. In the user_email field, enter any email address. In the mobile_number field, enter random mobile phone numbers, only digits, without duplicates. In the fwd_forwarding and fwd_forwardingonbusy fields, fill in with mobile_number values.

When creating an employee, print user_username, user_email, and number to the console and report the result.

If the result of the saveRecord or getRecord request is false, also print the messages parameter from the received response. If the response results in an error of another type or cannot be parsed, print the complete text received from the API server to the console.

As a result, a Python script was generated that allowed us to perform this test.

CreateRandomExtensions.py
import requests
import random
from faker import Faker

def generate_random_mobile():
    return ''.join(random.choice("1234567890") for _ in range(11))

def main():
    faker_ru = Faker('ru_RU')
    faker_en = Faker('en_US')
    faker_zh = Faker('zh_CN')
    faker_ja = Faker('ja_JP')

    for number in range(1, 699):
        # Retrieving the data template for a new employee
        get_response = requests.get("http://127.0.0.1:8081/pbxcore/api/extensions/getRecord?id=")

        if get_response.json().get('result', False) == False:
            print(f"getRecord error: {get_response.json().get('messages', 'Unknown error')}")
            continue

        data = get_response.json().get('data', {})

        # Generating random data
        locale = random.choice(['ru_RU', 'en_US', 'zh_CN', 'ja_JP'])
        faker = locals()[f"faker_{locale.split('_')[0].lower()}"]
        data['user_username'] = faker.name()
        data['user_email'] = faker.email()
        data['mobile_number'] = generate_random_mobile()
        data['fwd_forwarding'] = data['mobile_number']
        data['fwd_forwardingonbusy'] = data['mobile_number']

        # Creating a new employee
        post_response = requests.post("http://127.0.0.1:8081/pbxcore/api/extensions/saveRecord", data=data, headers={'Content-Type': 'application/x-www-form-urlencoded'})

        if post_response.json().get('result', False):
            print(f"Created user {number} -> Username: {data['user_username']}, Email: {data['user_email']}, Mobile: {data['mobile_number']}")
        else:
            print(f"saveRecord error for user {number}: {post_response.json().get('messages', 'Unknown error')}")

        if post_response.status_code != 200 or not isinstance(post_response.json(), dict):
            print(f"Unknown error: {post_response.text}")

if __name__ == "__main__":
    main()

Save file content in /tmp/CreateRandomExtensions.py and run in with the following approach.

cd /tmp
python -m venv venv --without-pip
source venv/bin/activate
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
pip3 install faker requests
python CreateRandomExtensions.py

As a result of the script's execution, you will see a list of created employees in the console, and new user accounts will appear in the web interface.

It's important to note that since the system is read-only, you need to install Python libraries after each reboot, and the /tmp folder will be cleared. Development and refinement of the script should be done in an external system.

When making REST API requests from external addresses, it's necessary to authenticate with an administrative username and password or create a user with the necessary permissions in the employee rights management module and authenticate with it.

When making requests, as in this example, from the address 127.0.0.1, no authentication is required.

Last updated 4 months ago

Was this helpful?

MikoPBX stress testing process for the interface and REST API
MikoPBX result of the script for generating a random set of employees