apipostrequestvk

How to send POST requests to the VK API


I have a VK bot that needs to send long messages. They do not fit in URI, if I try to send a GET request, API returns URI too long error. Sending requests with Content-Type: application/json and passing json as body doesn't work, neither is it possible to send a Content-Type: multipart/form-data request. Is it possible to send a POST request to VK API?


Solution

  • It is possible to send a POST request using Content-Type: application/x-www-form-urlencoded;charset=UTF-8. Also it's recommended to send access_token and v parameters in url and the rest in the body.

    Example in JavaScript:

    const TOKEN = '...'
    const VERSION = '5.126'
    
    fetch(`https://api.vk.com/method/messages.send?access_token=${TOKEN}&v=${VERSION}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({
        random_id: Math.round(Math.random()*100000),
        peer_id: 185014513,
        message: 'Hello world'
      }).toString()
    })
      .then((res) => res.json())
      .then(console.log)
    

    In PHP:

    const TOKEN = '...';
    const VERSION = '5.126';
    
    $query = http_build_query([
      'access_token' => TOKEN,
      'v' => VERSION,
    ]);
    $body = http_build_query([
      'random_id' => mt_rand(0, 100000),
      'message' => 'Hello world',
      'peer_id' => 185014513,
    ]);
    $url = "https://api.vk.com/method/messages.send?$query";
    
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
    curl_setopt($curl, CURLOPT_HTTPHEADER , [
      'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
    ]);
    $response = curl_exec($curl);
    curl_close($curl);
    
    $json = json_decode($response, true);
    

    Note that you cannot send messages over 4096 characters long