How to set up smartphones and PCs. Informational portal
  • home
  • Security
  • What is working with api in VK. The correct approach to using the Vkontakte API

What is working with api in VK. The correct approach to using the Vkontakte API

Hello, Habr!

At one time, surfing the Internet for the rational use of the Vkontakte API, I could not find something intelligible, the only libraries that I found were implemented without using any generally accepted practices and without beautiful code. I decided to correct this misunderstanding and wrote my own library to work with the Vkontakte API.
Lively details and approaches under habrakat.

It just so happened that the Vk API is implemented quite well, with the exception of some not logical points, which I will mention later. But today we are not talking about quality, but about a specific application.

Immediately it is necessary to make a reservation, in addition to the description, I will bring pieces of working code to my library, a link to which I will give at the end of the article. The library works on the latest stable version 5.5, if you cut out the generators from the batch receipt, it should work on 5.4.

  • Server authorization (so-called site authorization)
  • Client authorization (Standalone)
  • Application server authorization
The most interesting for the developer are the first two. The first allows you to authorize a user on the site and get his access key, the second allows you to authorize your application, for example Dekstop or Mobile. Looking ahead, the second option provides us with tremendous opportunities, and the first, only a small part of them.

The algorithm for obtaining in the first case is reduced to the implementation of the following points:

  • We display a link for user authorization, which we format in accordance with the documentation
  • The user follows it and logs in
  • The user is redirected to the REDIRECT_URI of our application with the GET parameter code
  • Our application needs to make a request to the API containing the code to get the user's access token
  • The API responds with either an object containing the access token or an error.

An example of code with which you can crank up this is not a tricky business.

$ auth = getjump \ Vk \ Auth :: getInstance (); $ auth-> setAppId ("3470411") -> setScope ("SCOPE") -> setSecret ("SECRET CODE") -> setRedirectUri ("http: //localhost/test.php"); $ token = $ auth-> startCallback (); printf ("LINK", $ auth-> getUrl ());

It is assumed that our domain is localhost and the current file is test.php. If everything went well, then our $ token variable will contain the access key of the user who has passed the authorization.

From the moment we have an access key, we can perform API requests... The general request logic is simple, you pass a specially crafted request to the API URL. The request must contain the name of the method and arguments.

api.vk.com/method/METHOD_NAME?PARAMETERS&access_token=ACCESS_TOKEN

List of methods, this is one of the rich things in the API. In it, you can find methods that do not require an access key for their work, therefore you can call them without getting it.

When using a library, we need to create a base object, like this:
$ vk = getjump \ Vk \ Core :: getInstance () -> apiVersion ("5.5") -> setToken ($ token);

A couple of example queries using the library:

Exactly 100 objects containing user data from 1 to 100 will pass through the anonymous function in each. Note that if we remove the function call, no request will be made, all because an object will be returned that has the magic methods __call and __get overridden, that allows us to make a request when we really need it.
$ vk-> request ("users.get", ["user_ids" => range (1, 100)]) -> each (function ($ i, $ v) (if ($ v-> last_name == "" ) return; print $ v-> last_name. "
"; });

One of the things that reveals us using generators is batch fetching. That is, we receive data only when we need it. The following example will allow us to get ALL of our messages, requests for 100. Be careful, method requires you to have rights for messages, Standalone application, the same authorization and, accordingly, the transfer of the access key.
foreach ($ vk-> request ("messages.get") -> batch (100) as $ data) ($ data-> each (function ($ i, $ m) (if (isset ($ m-> body) ) print $ m-> body. PHP_EOL;));)

A good method to look for in the API is execute... It takes a code parameter as an argument, code is some kind of pseudo JavaScript that allows us to execute our code on the server side, and it also allows us to execute stored procedures that we can create when editing our application.

I could not ignore this thing and implemented it in the library. In a nutshell, it allows you to run multiple queries as one. See the following code example.

$ js1 = $ vk-> request ("messages.get", ["count" => 200, "offset" => 0 * 200]) -> toJs (); // Returns an object of type VkJs $ js2 = $ vk-> request ("messages.get", ["count" => 200, "offset" => 1 * 200]) -> toJs (); $ js3 = $ vk-> request ("messages.get", ["count" => 200, "offset" => 2 * 200]) -> toJs (); $ js4 = $ vk-> request ("messages.get", ["count" => 200, "offset" => 3 * 200]) -> toJs (); $ js1 -> append ($ js2) // We add js2 to js1 -> append ($ js3) -> append ($ js4) -> execute () // We want to do this (it actually returns RequestTransaction) - > response // The request will be executed only now -> each (function ($ i, $ v) // The first anonymous function is needed to traverse all the elements of the array received from execute (an array of 4 elements, 4 requests) ($ v-> each ( function ($ c, $ d) (// Next to loop through all 200 messages in each array if (isset ($ d-> body)) print $ d-> body; // Print a message if such a field is present));) );

As promised, one of those misunderstandings that you may encounter in the current version of the API (5.21) is the method

Social networks have become an indispensable tool for website promotion. For website promotion via social. network, you should create a group or page for this site. Gain subscribers, post news on the wall and much more (this is a topic for a separate article). Many of these processes can be automated using the API (Application Programming Interface) of the respective social network. In this post, I will analyze how to connect to the vk api (vkontakte), how to start working with the vk api, as well as give several examples of working with the vk api.

Creating a VKontakte application

And so let's get started. Vk api has many methods, but one of their main differences is that in order to make requests to Vk api through some methods, a special access key is required - a token (access_token). You can get it by creating your own application. We are offered several types of applications, but I choose the Standalone type. It's enough for me. To start creating an application, follow the link and get into the next window.


Here we choose the type and name of our application. We press connect the application and receive an SMS with a code on the phone number associated with the VK account from which we create the application. We enter it and go to the next window. In this window, go to the settings tab.


In the settings tab, we see fields with the name of the application ID and the security key. We write this data somewhere. I didn't do anything else in the tabs. Application state left in disabled position. We press to save the settings. That's it, we have created a VKontakte application.

Getting a token (access_token) api vk

Https://oauth.vk.com/authorize?client_id= & display = [window view]& redirect_uri = https: //oauth.vk.com/blank.html&scope= [application rights]& response_type = token & v = 5.52

  • client_id - the ID of our application obtained earlier.
  • display - view of the window in which authorization will take place. Can be page, popup, touch and wap
  • scope - the access rights of our application regarding user data. More details about the rights below.

The rights of the VK application relative to a given user can be set in text and digital form. In text it will look like scope = friends, messages, groups. With this line of code, we allowed the vk application to access the user's friends, messages and groups. The rights are also assigned in digital form. For each rule there is a bit mask and the sum of these masks and will allow the application to do certain things. For example, the right friends (+2), messages (+4096), groups (+262144), as a result, the sum of bit masks will be 266242 and the code scope = 266242 will be analogous to scope = friends, messages, groups. I would like to pay special attention to the law offline. Setting this right makes the token we receive infinite. If this right is not set after a certain time, the token will need to be received again. You can read more about the rights of the VK application here. As a result, let's compose an address for receiving a token for an application with access rights to friends, messages and user groups, as well as with an immortal token. Let the application id be 123456. This address will look like this:

Https://oauth.vk.com/authorize?client_id=123456&display=page&redirect_uri=https://oauth.vk.com/blank.html& scope = friends, messages, groups, offline & response_type = token & v = 5.52


We confirm the action and get to the warning page, we take our received token from the address bar of the browser. This will be after # access_token =, the expires_in = 0 code tells us that the (access_token) api vk is immortal. Accordingly, user_id = is the id of the user for whom we got the token.

Let's go to the account settings in the application settings tab and see our application.


Now we are ready to work with api vkontakte.

Examples of working with api vk

To work with the VK api, I use the php programming language. Therefore, I will give examples in php. In order to perform any action, we need to send a request to the api vk. We can also send a request through the address bar of the browser. That is, a request is a specific url address with specific parameters specified in it. The syntax for composing such url is described below.

Https://api.vkontakte.ru/method / [CALLED METHOD]? [CALLED METHOD PARAMETERS]

The list of api vk methods is here. We will not focus more on this for now, then on real examples everything will become clear. It remains only to figure out how to send a request to the VKontakte api using php. To do this, we will use the php function file_get_contents, as well as the json_decode function, since we will receive the response from the server in json format. Here is a template for making a request to VK in php.

$ result = json_decode (file_get_contents ("https://api.vkontakte.ru/ method / [CALLED METHOD]? [CALLED METHOD PARAMETERS]"));

well, now a few examples of working with api vk

$ userid = 12345; $ mytoken = 56789; / * will return an object with the gender and birthday of the user * / $ request_params = array ("user_id" => $ userid, "fields" => "sex", "fields" => "bdate"); $ get_params = http_build_query ($ request_params); $ result = json_decode (file_get_contents ("https://api.vk.com/method/users.get?". $ get_params)); / * checking the user for a VK ban * / $ request_params = array ("user_id" => $ user_id, "fields" => "deactivated"); $ get_params = http_build_query ($ request_params); $ result = json_decode (file_get_contents ("https://api.vk.com/method/users.get?". $ get_params)); if (isset ($ result-> response-> deactivated)) (echo "The page is frozen or deleted";) / * send a message to the user with user_id = 222222 * / $ mesage = "Hello, how are you?"; // encode the string $ msg = urlencode ($ mesage); $ result = json_decode (file_get_contents ("https://api.vkontakte.ru/method/ messages.send? user_id = 222222 & message =". $ msg. "& access_token =". $ mytoken)); / * invite a user with user_id = 222222 to be friends * / $ mesage = "Let's be friends"; $ msg = urlencode ($ mesage); $ result = json_decode (file_get_contents ("https://api.vkontakte.ru/ method / friends.adduser_id = 222222 & text =". $ msg. "& access_token =". $ mytoken));

Api has a lot of methods, so I advise you to read the documentation. Of course, queries do not always run correctly and return error codes. Errors can be viewed here. So just like that, you can simply connect to the vk api and automate your actions in contact.

Those who decided to start developing applications for VKontakte sooner or later will have to face such a concept as API (application programming interface), which literally means application programming interface.


More simply - API it is a whole complex of various ready-made functions, ready-made classes, constants, etc., which can be used in third-party. The VK API is constantly being improved and today it is already a fully functional set of add-ons that allows.

You can get acquainted with the documentation in detail here.
The last major transformation of this development environment was carried out back in April 2009. Of course, the site was constantly modified after that. Let's note the main features of the VKontakte API

  1. The API was used to implement access of applications to friends, their photos, videos. Applications can now independently create albums, place information in them... This was not the case before. What is important, when installing such an application, the user decides for himself whether to open access to his personal data or not.
  2. Sending notifications by applications. Yes, it is sometimes annoying pop-up notification at the bottom left of the screen is also implemented in API.
  3. It's also easier to invite friends to apps thanks to application programming interface that implemented this bulk invite feature. Subsequently, these invitations began to be used for advertising.
  4. Ads from VK disappeared from application pages. Now the developer of the game or program for VK decides for himself whether he needs advertising in his "flash drive". If so, he has the right to place his own and receive from it 100% profit.
  5. As the VK developers called it, users integrating applications gained access to the internal economy of the network. Simply put, an API has become available that allows use VKontakte as internal payments.
  6. Possibility run applications in full screen mode... The increase in the maximum frame size made it possible to place additional banners with advertising, so today the development of applications for VK is not just a pleasure, but a rather profitable activity when deciding to engage in advertising, selling banners from it.
  7. Third party apps are being distributed now and via news feed... This is one more step to popularize them. In addition (even though it was already a long time ago, a miniature icon has become available to the application).
  8. Application display order also implemented in API. Today, by default, those games that are launched most often are in your first positions. Which have not been used for a long time - you will find at the end of the list.
  9. Thanks to the API, it became available and detailed built-in statistics. Today you can easily count visitors, page views, gender, age, location of the application user. All information is presented in the most visual way, in the form of flash charts, which are built instantly. This is done primarily for advertising (sale of advertising space). You get statistics, you see that the application is used by tens of thousands of people. Show this to an advertiser who will probably want to pay for a banner in such an application.
  10. For the most popular applications, it became possible registration of short subdomains(for example chat.vk.com and similar) for easy memorization and quick access.
  11. And finally, there was an opportunity displaying information on personal pages of users.

I am often asked how to work with the API... The most popular task related to API, is an - work with the VK API... In this article I will show you how to work with the VK API, and, most importantly, I will show you that all APIs work according to the same principle.

Here procedure which you need to do to start working with any API:

  1. Find documentation according to the need API.
  2. Look API connection examples... There may be different options. For example, one service will require a secret key issued after registration. On the second service, all requests do not require private keys. On the third service, there are options for working with a secret key and without. Sometimes, the secret key is called token.
  3. Copy simple ready-made code from the documentation site and check it works. If it does not work, then look for the error in yourself, since the service is unlikely to have it.
  4. Find in the documentation method that solves your problem.
  5. Using examples and method description, send correct request to API.
  6. Depending on the format of the response, parse it into " components", and then do what is required - output to the user, save to a file, send to the database, and the like.

And as an example of following this instruction, we will analyze API VKontakte... So:

  1. Link to documentation.
  2. In this case, there are methods that are publicly available, and therefore do not require a token, but there are methods that require it.
  3. In this case, I did not find examples in a specific language. Perhaps they are, but clearly not in sight. Usually, at API there are examples in different languages ​​for each method.
  4. We want to withdraw 5 recent entries from the wall of a specific user, and then display them on your site... The method we need.

Now we must send a request to the API using the method description. We will do it through PHP:

$ wall = file_get_contents ("https://api.vk.com/method/wall.get?v=5.3&filter=others&domain=myrusakov&count=5");
print_r ($ wall);
?>

In this case, I am using API 5.3 (v = 5.3), I display all entries regardless of the author ( filter = others) from your page ( domain = myrusakov) in the amount 5 things ( count = 5). I think everything is very transparent here.

We received a response in the format Json, and now we need to move on to the last point - to parse the answer to " components". Next, we will display the entries from the wall in a more or less readable form on the page of our site. Php code:

$ wall = file_get_contents ("http://api.vk.com/method/wall.get?v=5.3&filter=others&domain=myrusakov&count=5"); // Send the request
$ wall = json_decode ($ wall); // Convert the JSON string to an array
$ wall = $ wall-> response-> items; // Get an array of comments
for ($ i = 0; $ i< count($wall); $i++) {
echo "

". ($ i + 1).". ". $ wall [$ i] -> text."
".date (" Y-m-d H: i: s ", $ wall [$ i] -> date)."

"; // Display records
}
?>

As you can see, everything is very simple. The hardest part is disassembling it into its constituent elements. I prefer to output the output from API across print_r, and only then write the handling of this. Although you can see an example of an answer in the description of the method, and then write a parser.

We have released a new book, “Content Marketing on Social Media: How to Get Into the Heads of Subscribers and Fall in Love with Your Brand”.

Subscribe to

API is an external programming interface for an application, referring to sites using a specific protocol to obtain information and simplify the development of programs related to internal services.

What does API mean

The simplest analogy for using the API would be the process of working on a calculator for complex calculations. Let's say you have a problem, you can understand its essence, build equations and graphs, but you do not know how to perform arithmetic operations with numbers. Next to you is a calculator that can do these operations with ease. You don’t know what is going on inside the computer, and you don’t need to know it. You give information in one form, and receive in another, necessary for your purposes.

Any API works by this principle. You do not care how the program receives the answer, what path the request goes through within it, how the calculations are performed. You are sure of only one thing - in response, you will receive standardized information about the success of the operation or its error.

The API interface allows you not to waste your time, money and effort on buying a "new bike". You get a working data port that receives and sends the necessary amounts of data for your development.

Pros:

  • Saving on the development of your interface.
  • There is no need to understand the nuances of the issue.
  • APIs are developed by professionals and take into account all the factors of internal processes that you may not be aware of when creating your solution.
  • Allows you to communicate with services that are closed through other protocols.

Minuses:

  • If the target service is updated, the API does not always get full functionality instantly.
  • You cannot catch errors and do not know how the process goes in someone else's code.
  • The API does not always give the most optimized result in terms of time, since it is designed to handle general cases, not private ones.

API examples

API integration is the process of connecting an application to an external data interface. Working with the API begins with studying the documentation and the protocols used, and then directly integrating your program into the interface. Let's consider the most popular services that have their own API.

VKAPI

The external interface of interaction of the popular social network VKontakte with clients, as well as with browser and server applications. Allows you to manage messages from communities, group covers, user pages if you have the appropriate access keys.

All requests are made to the address https://api.vk.com/method/

The slash is followed by the name of the API method used and the GET request parameters are passed. The response also comes over HTTPS in JSON format.

TELEGRAM BOT API

One of the most popular APIs. It is used to control bots in the Telegram messenger. After creating a bot via @botfather and obtaining the required access keys, you can start interacting with the backend.

Requests are made at https://api.telegram.org/bot0000000:token/

Where, instead of bot0000000, the unique identifier of your bot is put, and the token expresses the secret key.

Requests are sent over HTTPS connections, the method name is indicated through a slash to the main address. The response comes in JSON format.

OPEN WEATHER MAP API

It is often necessary to get weather information without using third-party widgets and paid applications. The OpenWeatherMap service comes to the rescue with an open and free API. After registering and obtaining identification data, you can send requests for weather around the world from server-side scripts. In response to the city ID, the resource returns the most detailed information about the current weather and gives a forecast for the near future.

Work format: HTTP transfer via api.openweathermap.org/data/2.5/weather?id= indicating the identification number of the desired city. Server response: JSON.

GOOGLE MAPS API

What could be nicer than an interactive world map on the website? Especially if this is not a template insert from Google Maps, but your personal edition of a popular map with personal marker clusters. The map will interact with other scripts on the site, sending information about clicks and coordinates.

Similar capabilities are offered by the JavaScript API Google Maps. The module is completely scripted and works on the browser side, so we don't need HTTP requests from PHP and the formation of headers on the server side, as it was in other APIs.

For example, placing a label on a map would look like this:

var mark = new google.maps.Marker ((
position: myPOS,
map: map,
title: "Hello!"
});

What is the use of the API for and why is it useful?

There are quite a few useful functions.

The first aspect

You can establish an interactive user interaction with social networks and instant messengers, use the capabilities of third-party computing systems to display exchange rates, weather and other important information.

Using the API, you can instantly connect to servers of other resources and software solutions, which in a normal implementation would take weeks of development. An API makes life easier where you don't need a unique implementation and prioritize reliability and security.

Second aspect

If you are the owner of complex computing power, a popular service, or a data warehouse for open or semi-private access, then it is a good idea to raise your own API. What will it give:

  • Large flow of clients.
  • Simplified access to your services for partners.
  • Convenience of statistical analysis of the use of the service.

Third aspect

Almost the same as the second. But without having to implement an open source API. If you have a portal and want to create a mobile application for it on Android / IOS, then rewriting the system for a single API is the best solution. The entire data structure is systematized. The site and the application will work through the same data channels.

Top related articles