API technology. API Basics. Creating your own API. How to use the API: practical examples
Let's start with the basics: what is an API? The abbreviation stands for Application Programming Interface, or application programming interface. The name seems to speak for itself, but it’s better to consider a more detailed explanation.
As already mentioned, an API is, first of all, an interface. An interface that allows developers to use ready-made blocks to build an application. In the case of developing mobile applications, a library for working with a smart home can act as an API - all the nuances are implemented in the library and you only access this API in your code.
In the case of web applications, the API may return data differently from the standard HTML format, making it convenient to use when writing your own applications. Third-party public APIs most often serve data in one of two formats: XML or JSON. In case you decide to make an API for your application, remember that JSON is much more concise and easier to read than XML, and services that provide access to data in XML format are gradually abandoning the latter.
API in web applications with examples
An application - for example, Github - has its own API that other developers can use. How they will use it depends on the capabilities that the API provides and on how well the developers’ imagination works. The GitHub API allows, for example, to obtain information about the user, his avatar, readers, repositories and many other useful and interesting information.
In this way, you can send a request in any language, including Ruby. The response to the request will be approximately the following information:
( "login" : "Freika" , "id" : 3738638, "avatar_url" : "https://avatars.githubusercontent.com/u/3738638?v=3", "gravatar_id" : "" , "url" : "https://api.github.com/users/Freika", "html_url" : "https://github.com/Freika" , "followers_url" : "https://api.github.com/users/Freika/followers", "following_url" : "https://api.github.com/users/Freika/following(/other_user)", "gists_url" : "https://api.github.com/users/Freika/gists(/gist_id)", "starred_url" : "https://api.github.com/users/Freika/starred(/owner)(/repo)", "subscriptions_url" : "https://api.github.com/users/Freika/subscriptions", "organizations_url" : "https://api.github.com/users/Freika/orgs", "repos_url" : "https://api.github.com/users/Freika/repos", "events_url" : "https://api.github.com/users/Freika/events(/privacy)", "received_events_url" : "https://api.github.com/users/Freika/received_events", "type" : "User" , "site_admin" : false , "name" : "Evgeniy" , "company" : "" , "blog" : "http://frey.su/" , "location" : " Barnaul" , "email" : "" , "hireable" : true , "bio" : null, "public_repos" : 39, "public_gists" : 13, "followers" : 15, "following" : 21, "created_at" : "2013-03-01T13:48:52Z" , "updated_at" : "2014-12-15T13:55:03Z" )
As can be seen from the block above, the response contains the login, avatar, link to the profile on the site and in the API, user status, number of public repositories and other useful and interesting information.
API alone is not enough
Creating a full-fledged API for your application is only half the battle. How are you supposed to access the API? How will your users access it?
The first thing that comes to mind is the usual series of HTTP requests in order to receive necessary information, and this is the wrong answer. The most obvious method in this case is not the most convenient and simple. It would be much wiser to create special library for working with the interface, which will describe all the necessary ways to receive and send information using the API.
Let’s use Github once again to give an example: to work with the API of this excellent service (and its interface provides extensive capabilities), several libraries have been created in various languages, for example the Octokit gem. In the documentation for such libraries (and the gem given as an example), any interested developer will be able to find all the necessary ways to receive information from Github and send it back through the service API.
Thus, if you are creating your own API, consider perhaps creating libraries to work with it in the most common languages. And be prepared that at a certain level of demand for your application, someone else may create their own library to work with your API. This is fine.
Useful links
In subsequent articles we will talk about how to correctly create an API, ensure its security and limit access to some information.
API(English) Application Programming Interface) - this is the application programming interface. API specific application or service provides a set of ready-made procedures, functions and variables with which third-party developers can create their own applications and scripts to work with this service.
When working through API application sends a request to the service and receives a response containing the requested data, regardless of what programming language it was created in.
Owners of online stores, using third-party services and their own applications, have the opportunity to access via API:
Information about placed orders
Available actions (methods) for processing order information:
- Selecting order information by ID
- Selecting order information by filter
- Number of orders by filter
- Create an order
- Deleting an order
- Mass deletion of orders
- Selecting all available statuses for orders
- Update order status
- Adding a comment to an order
Subscriber information
- Adding a subscriber
- Delete a subscriber
- Mass deletion of subscribers
- Selecting subscriber data by filter
- Number of subscribers by filter
Information about registered users
Available actions (methods) for processing information about subscribers:
- Selecting information about registered users by ID
- Selecting information about all registered users
- Selecting information about all data specified by the user during registration:
- Last name, first name, patronymic;
- Contact address email;
- Contact number telephone;
- Specified address delivery: zip code, name of the locality, street name, house number, building number, apartment number, floor;
Pay attention! When registering, the user may not complete all of the above fields.
API development plans
In the near future, we plan to open interfaces to support the interaction of stores with third-party applications and services for working with:
- Catalog sections.
- Goods.
- A basket.
- With discounts.
- Delivery methods.
- Payment methods.
To test interaction with the beseller platform API, a test store beseller-api.shop.by has been created.
To access the test store, you must provide a login and password. You can obtain them upon request from your personal manager.
Before testing interaction with the API, we recommend that you:
- place several orders yourself;
- subscribe to the newsletter;
- see how information about placed orders and subscribers is displayed in the store administration panel.
The store control panel is available at: beseller-api.shop.by/manager/. The login and password when entering the control panel are similar to the login and password for accessing the store.
How to connect via API to your store?
To connect the application with your store, you need to specify an API access URL of the form:
http://your_site_address:8082/graphql?token=your_personal_secret_key
You can obtain the secret key upon request from your personal manager.
GraphQL functions and variables for working with the beseller platform API
How to connect to an API using the PHP programming language
To make it easier to work with the beseller platform API, you can use:
- Classes developed by us for PHP.
- GraphqlClient- receives and transmits data to the server;
- GraphQlHelper- contains implemented query and mutation APIs;
- Examples of using classes to make selections and changes in the online store database.
Setting up your local environment
In order to clearly demonstrate sending requests to the API and the responses received, you can use the local environment.
GraphiQL Feen is used as the local environment, this is a browser extension Google Chrome which allows you to create requests to the API.
After installing the application, an application icon will appear in your browser near the address bar.
Open the GraphiQL Feen application and go to the “SERVERS” tab, select the POST sending method, and then specify the API access url.
The following address should be used as a test url:
The local environment is configured, you can generate requests to the API. To do this, you need to open the “QUERIES” tab
Forming a request to the beseller API using GraphiQL Feen and the response received
Explanations for the screenshot:
- Saved queries
- Field for entering requests
- Variable input field
- Response received
- Start button
An example of a request to obtain a list of placed orders for a specified period of time
query ($first:Int, $offset:Int, $filter: OrdersFilterType)(
orders(first:$first, offset:$offset, filter:$filter)(
comment
status(
id
description
name
}
create_date
update_date
total (
suffix
value
}
payment (
name
description
cost (
suffix
value
}
}
delivery(
name
description
cost (
suffix
value
}
}
currencies (
bank_code
course
suffix
}
user_data(
name
description
value
}
}
}
Specifying the time period for retrieving data about placed orders
{
"filter": (
"date_after": "2017-11-16T00:00:01Z",
"date_before": "2017-11-23T00:00:01Z"
}
}
Example response from API
{{
"data": (
"orders": [
{
"comment": "Culpa officiis vel ut.",
"create_date": "2017-11-22 16:23:28",
"currencies": [
{
"bank_code": "BYN",
"course": 10000,
"suffix": "rub."
}
],
"delivery": (
"cost": [
{
"suffix": "rub.",
"value": 0
}
],
"description": "Courier",
"name": "custom"
},
"payment": (
"cost": [
{
"suffix": "rub.",
"value": 0
}
],
"description": "Plastic cards",
"name": "custom"
},
"status": (
"description": "New",
"id": 1,
"name": "new"
},
"total": [
{
"suffix": "rub.",
"value": 4450
}
],
"update_date": "2017-11-22 16:23:28",
"user_data": [
{
"description": "Email address",
"name": "email",
"value": " [email protected]"
},
{
"description": "Phone",
"name": "phone",
"value": "784.392.3949 x69329"
},
{
"description": "Address",
"name": "registration",
"value": "607 Erik Station Suite 057\nReynaberg, WY 83542-0037"
},
{
"description": "Comment",
"name": "comment",
"value": "Id nam illo optio."
},
{
"description": "Name",
"name": "fio",
"value": "Jordi Mann MD"
}
]
}
This short term is well-known to everyone who has had any experience with development. But not everyone understands what exactly it means and why it is needed. Developer Peter Gazarov talked about the API in simple words on your blog.
The abbreviation API stands for "Application Programming Interface" software interface applications). Most large companies at some stage develop APIs for clients or for internal use. To understand how and how APIs are used in development and business, you first need to understand how the World Wide Web works.
World Wide Web and remote servers
The WWW can be thought of as a huge network of interconnected servers on which every page is stored. An ordinary laptop can be turned into a server capable of serving an entire website on the network, and local servers developers use it to create websites before making them available to the public.
When entered into the address bar of the browser www.facebook.com A corresponding request is sent to the remote Facebook server. Once the browser receives the response, it interprets the code and displays the page.
Every time a user visits any page on the web, he interacts with the API remote server. The API is the component part of the server that receives requests and sends responses.
API as a way to serve clients
Many companies offer APIs as a ready-made product. For example, Weather Underground sells access to its weather data API.
Usage scenario: On the website of a small company there is a form for making appointments for clients. The company wants to integrate Google Calendar into it to allow customers to automatically create an event and enter details about an upcoming meeting.
API Application: The goal is for the site server to directly contact the Google server with a request to create an event with the specified details, receive Google's response, process it, and send the appropriate information to the browser, for example, a confirmation message to the user.
Alternatively, the browser can make a request to Google's server API without going through the company's server.
How is the Google Calendar API different from the API of any other remote server on the network?
Technically, the difference is in the format of the request and response. To generate a complete web page, the browser expects a response in the language HTML markup, while the Google Calendar API will simply return data in a format like JSON.
If a request to the API is made by the server of a company's website, then it is the client (just as the browser is the client when the user opens the website).
Thanks to the API, the user gets the opportunity to perform an action without leaving the company’s website.
Most modern websites use at least a few third-party APIs. Many tasks already have ready-made solutions offered by third-party developers, be it a library or a service. It is often easier and more reliable to resort to a ready-made solution.
Many developers distribute the application to several servers, which interact with each other using the API. Servers that perform a supporting function to the main application server are called microservices.
So, when a company offers an API to its users, it simply means that it has created a series of special URLs that return only data as a response.
Such requests can often be sent through a browser. Since data transfer via the HTTP protocol occurs in text form, the browser will always be able to display the response. For example, through a browser you can directly access the GitHub API (https://api.github.com/users/petrgazarov), without an access token, and receive this response in JSON format:
The browser perfectly displays the JSON response, which can be inserted into the code. It is easy enough to extract data from such text to use it at your discretion.
Some more API examples
The word "application" can be used in different meanings. In the context of the API, this means:
- fragment software with a specific function,
- the entire server, the entire application, or just a separate part of the application.
Any piece of software that can be clearly distinguished from the environment can replace the letter “A” in an English abbreviation, and can also have some kind of API. For example, when a developer implements a third-party library into the code, it becomes part of the entire application. As a standalone piece of software, the library will have some kind of API that allows it to interact with the rest of the application code.
In object-oriented design, code is represented as a collection of objects. In an application, there can be hundreds of such objects interacting with each other. Each of them has its own API set public properties and methods for interacting with other objects in the application. Objects may also have private, internal logic that is hidden from the environment and is not an API.
Sooner or later, any programmer is faced with such a concept as API. However, when such a meeting occurs, not everyone knows what it is, why it is needed and how to use it. And in this article I am going to fill this gap in the knowledge of some of you, and also give an example from my practice.
API (application programming interface) - This application programming interface. In simpler terms, this is a set of various functions, constants, classes, and query formats that can be used in other programs.
It can be considered that API- this is an object whose implementation we do not know, however, we can use it. For example, a computer is an object whose implementation very few people know, however, almost everyone can use it to perform some actions: watching videos, surfing the Internet, printing text, etc. Few people know how it all works, but almost everyone can do it.
Example API is Windows API, OpenGL API, Direct3D API and so on.
For example, not long ago I also encountered directly API. I registered on the service mailing lists "SmartResponder.ru" and started a newsletter, which people began to subscribe to. The task was as follows: within 24 hours after subscribing, a person can purchase my paid video course at a discount. Since all information about subscribers is stored on the server " SmartResponder.ru", then normal access (for example, through DB) I did not have access to this data, but it was necessary to implement it. Thankfully, " SmartResponder.ru"have your own API, which I used.
I found in them API request format to get the subscription date as a result. Further through cURL I sent the corresponding request and received the required subscription date for a specific e-mail addresses . Next is standard processing and output of the result.
An API is an external interface for programming an application, accessing sites using a specific protocol to obtain information and simplified development of programs associated with internal services.
What does API mean?
The simplest analogy for using an API would be to use a calculator to perform complex calculations. Let's say you have a task, you can understand its essence, build equations and graphs, but you do not know how to perform arithmetic operations with numbers. There is a calculator next to you that can do these operations with ease. You don't know what's going on inside computer, and you don’t need to know this. You give information in one form, and receive it in another, necessary for your purposes.
Any API works on this principle. You don’t care how the program gets the answer, what path the request takes inside it, how the calculations are performed. You are sure of only one thing - in response, standardized information will be given 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 information port that receives and sends the necessary amounts of data for the purposes of your development.
Pros:
- Saving on developing your own 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.
Cons:
- If the target service is updated, the API does not always immediately receive full functionality.
- You can't catch errors and don't know how the process works 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 specific 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 protocols used, and then directly integrating your program into the interface. Let's look at the most popular services that have their own API.
VKAPI
External interface for interaction of the popular social network VKontakte with clients, as well as with browser and server applications. Allows you to manage community messages, group covers, user pages if you have the appropriate access keys.
All requests are made to the address https://api.vk.com/method/
After the slash comes the name of the API method used and the GET parameters of the request are transmitted. The response also comes via 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 necessary access keys, you can begin interacting with the backend.
Requests can be made to: https://api.telegram.org/bot0000000:token/
Where instead of bot0000000 the unique identifier of your bot is put, and token expresses the secret key.
Requests are sent via HTTPS connections, the method name is indicated via a slash to the main address. The response comes in JSON format.
OPEN WEATHER MAP API
It is often necessary to obtain weather information without using third-party widgets and paid applications. The OpenWeatherMap service comes to the rescue with open and free API. After registering and receiving identification data, you can send weather requests from server scripts around the world. In response to the city ID, the resource returns the maximum detailed information about the current weather and gives a forecast for the near future.
Format: HTTP transmission 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 interactive map peace on the site? Especially if this is not a template insert from Google Maps, but your personal edition of a popular map with personal clusters of markers. The map will interact with other scripts on the site, sending information about clicks and coordinates.
The Google Maps JavaScript API offers similar capabilities. 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 was the case in other APIs.
For example, placing a marker on a map will look like this:
var mark = new google.maps.Marker((
position: myPOS,
map: map,
title:"Hello!"
});
What is the need and benefits of using the API?
There are quite a lot of useful functions.
First aspect
You can establish interactive user interaction with social networks and 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. The API simplifies life where a unique implementation is not needed, and reliability and security are a priority.
Second aspect
If you are the owner of complex computing power, a popular service or data warehouse for public or semi-private access, then a good move would be 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 service use.
Third aspect
Almost the same as the second one. But without having to implement an API for open access. If you have a portal and want to create one for it mobile application on Android/IOS, then rewrite the system under a single API - best solution. The entire data structure is systematized. The site and application will operate through single data channels.