in simple words about the API

Any modern IT company in one way or another has to work with data: it is used both in optimizing the performance of the company itself and in providing services to consumers. The task is often complicated by the need to manage and transfer large amounts of data, so APIs help organize work with them. We’ll talk about APIs today in this article: let’s figure out what they are, why they are needed and why they are so in demand.

The article is specifically written in simple languagewhere many things are explained through accessible examples so that the material is understandable to everyone and gives a general idea, and not just talks about the intricacies of development.

Let's get acquainted. My name is Alexander, I do web development, in particular, API development for a startup NFCKEY. In the past, I had a similar experience when creating a headhunting platform aimed at a fairly narrow target audience and partnerships. I learn from mistakes and like to understand the intricacies of my work, especially due to the specifics of a startup.

According to the plan, we will analyze the following:

What is an API and where is it used?

In the modern world, most companies strive transform your business processes and data into digital form. Such tasks often require a carefully designed database with provisions for scaling, as well as thoughtful security at the access control level. Databases can be located on remote servers, and work with them is carried out through the user interface provided by various applications. But how does the data get from the database to the device screen? One of the common solutions to this problem is an API.

API (from English application programming interface – “application programming interface”») is a software interface that describes how one program interacts with others. Its internal logic is hidden, but the focus is on the final result of the interaction and the rules by which it is organized. Continuing with the UI example, you click a button to tell the program what you want, and the program uses the API to request the data it needs.

Talking about application examples, one of the most popular and popular in our world is the API of map services (Google Maps, Yandex Maps). Thanks to them, anyone can use their functionality: create an interactive map and show, for example, the location of an office or store.
In addition, you have probably used the option of logging into any application or website using your Google, Apple, or VK account. This is possible thanks to the API. Weather forecasts, airline ticket information, bank payments – all these are examples of use that show the breadth of the range of tasks being solved.

In the field of IT and, in particular, IoT, an API is often necessary not only for working with databut also for the functioning of the product as a whole. There are many more subtleties and the complexity of development increases exponentially. Working with the server will be the foundation for such projects, the failure of which can lead to the collapse of the entire system and serious consequences.

Why do projects need an API?

Web APIs In our time, they have become a widely used technology, acting as a kind of highway. Many companies rely heavily on this kind of infrastructure to serve their customers. For example, any site from the top 100 Alexa internet ranking uses APIs and/or provides its own APIs, which is a fairly clear indicator of the enormous scale and influence of web interfaces in general.

Developing your own API allows you to implement all individual solutions for the needs of a specific project. Off-the-shelf products may offer general functionality, but may simply not match or fully satisfy the intricacies of your business logic. Accordingly, developing your own API you get more flexibility and scalability if necessary, modify or expand your solution as requirements change. Finally, you can avoid unnecessary worries about the security of your data and other confidential information, especially if you have your own server infrastructure.

In any case, the above does not mean that third-party APIs are a bad option. The main advantage is just saving resources, achieved by using already developed functions, rather than creating your own from scratch. For many purposes, there are services that can satisfy various needs: payment gateways, authorization systems, add-ons for CRM, etc. Where it will be more profitable to allocate time and budget depends on the tasks and requirements of the business.

Project to create a system of smart locks, which I am currently working on is IoT a startup for which the task of developing its own API is one of the key ones. Throughout the article, I will discuss and take as an example some solutions specific to it. I would like to note that one of the main problems of such projects is complex relationship between hardware and software components. In our case, all parts, including the physical lock, its built-in software and mobile application, need a reliable software solution that will ensure uninterrupted communication and data consistency. This responsibility can be taken on by the server part with web application programming interface (Web API).

How does the API work?

Web API consists of multiple endpoints for a specific request-response messaging system. It's worth clarifying that there are different types of APIs, but some of the most common are REST APIs, which use the JSON (JavaScript Object Notation) format to exchange data. You can find out more about other types in this article.
Here we can consider a common version of the client-server architecture:

Server — a remote node that stores and processes resources. Here we store the necessary data and also establish how it is processed and provided to clients.

Client – a program that initially does not store data and requests the same resources from the server. In our scheme, the client can be a mobile application that uses server resources. Otherwise, this could be, for example, some kind of payment service for online stores or website of a neural network that produces results based on your request. In general, most of the neural networks that you may have encountered previously on the Internet are built on working with APIs.

Each functionality in the system corresponds to a specific endpoint, which provides a clear and modular organization of functions. One practice is to use resource-based approachwhere objects such as users, logs, and other objects are treated as resources (or collections of resources) with unique endpoints for retrieving/creating/updating/deleting them. JSON in turn, serves as a format for data exchange and presentation of the mentioned resources, providing an easy and human-readable structure. In addition, for serializing and deserializing data (converting to/from) JSON, there are many tools that can help developers.

Thus, the client knows how to contact the server, and programmed to process the expected resultand the server knows how to respond to the client, and is programmed to process input data and generate responses. Conventionally, if we need to change the internal business logic, for example, numbers in the constraint system, then we can change them in the server part without having to update the client application. In addition, the API approach allows you to seamlessly onboard new clients. In our project, one of these clients we can consider is a website that complements the capabilities of a mobile application. Personal account, why not?

How are APIs developed?

Let's move on to the technologies used to develop APIs. Research related to the world of software development can certainly provide valuable information to start moving forward with. Among the most significant are Stack Overflow Developer Survey And JetBrains: Development Ecosystem. Such information allows you to assess trends in the world of software development and determine the initial list of candidates:

Programming language

Frameworks and technologies

Python

Django, Flask, FastAPI

PHP

Laravel, Symfony, CodeIgniter

Java

Spring Framework, Play Framework

Ruby

Ruby on Rails, Rack, Sinatra

C#

ASP.NET Core, Entity Framework

JavaScript

Express, Koa, Hapi, Nest

There are really a lot of technologies and they all have their own characteristics, advantages and disadvantages, so a reasonable solution is to conduct a comparative analysis taking into account the needs of the project.

How to conduct a comparative analysis of technologies for API development?

You can conduct a comparative analysis of solutions for developing the server part and, in particular, the API using a rating systembased on the following principles:

  1. Criteria are determined for evaluationwhich are weighted based on their importance, allowing certain factors to be given greater weight in the context of the project's requirements and objectives.

  2. The rating system uses a numerical scale from 1 to 5, where each value represents a qualitative rating (1 – “poor”, 5 – “excellent”). When evaluating, it is acceptable to use fractional numbers that provide detail to take into account the nuances of differences in performance and sufficiently allow the individual strengths and weaknesses of each candidate to be reflected.

  3. Each selected framework (technology) is evaluated according to pre-established criteria with assignment of points on a scale. A review of case studies, industry trends, and empirical data may be conducted to enhance the validity and reliability of the benchmarking analysis.

  4. The overall score for each technology is calculated by summing the scores of each criterion multiplied by its weight. This will ensure that the factors considered more important for the project make a proportionately greater contribution to the final estimate. The sum of the weighted scores provides an overall composite score that allows for quantitative comparisons between the technologies assessed.

  5. Recognizing the rather subjective nature of some criteria, the author's judgment is taken into account when assigning points, especially in areas where qualitative assessments are inherently subjective. Each rating can be accompanied by a commentary that states the rationale for the rating, which will ensure transparency and better interpretability of the results.

Definitely worth admittingthat the methodology has its drawbacks and, moreover, may seem too resource-intensive in modern realities, where the need to quickly develop an MVP simply does not leave time for such things.

Speaking about our project criteriawe decided to focus on scalability, performance, security, functionality (including for API development), and the learning curve.

The final option for us was the PHP framework Laravel. Considered by some developers to be a “dying” language, PHP is still actively used and is developing at a rapid pace. The corresponding web frameworks are freely used for project development and continue to occupy a niche in various surveys and infographics. Laravel is the most popular PHP framework in recent years, attracting attention with its architecture that implements many design patterns and provides a number of developer-friendly features. Laravel developer Taylor Otwell released the first version in 2011, and currently the framework continues to be actively developed and updated following its programming language.

I will not praise this framework too much and defend both its weaknesses and the PHP language as a whole, however combination of simplicity and flexibilityexpressive syntax, variety of functionality and scale of the ecosystem can present Laravel as an option that not only meets the requirements of many projects, but also adapts to future extensions.

Development path and difficulties encountered

I propose to pay a little attention to the technical details: the development process and emerging problems. I note that the description is based on working specifically with Laravel and may not convey the specifics of working with other technologies and frameworks. I will also note that some details are deliberately omitted in order to demonstrate general steps rather than an advanced guide.”How to…” However, I’m still waiting for comments about moving logic from controllers to services and repositories!

I try to keep everything standardized and thoughtful, so the path from designing an ER diagram to releasing an API endpoint looks something like this:

  1. Migrations for the database are created, model classes and their associated relationships are described. Relations, in particular with Eloquent ORM, are a very convenient tool that helps save dozens of extra lines of code and hours of time spent on them. The other day I was faced with the task of grouping some data and representing their collection in the form of the desired JSON schema. I solved it in 2 hours by scouring StackOverflow and using the trial and error method. The very next day, an insight came to me and, having described the new relationship in literally 5 lines of code, I deleted and rewrote all of yesterday’s code. It was possible to achieve the same result, but faster, more accurately and without crutches.

  2. Resource and collection classes are described based on what result should be returned in JSON. This also includes the preliminary logic of who can see what data.

  3. The data structure on the basis of which all internal logic will work is thought through, and Request classes are created. They can conveniently group all the validation and data preprocessing logic, leaving “fresh air” to the controller classes.

  4. Routes (endpoints) and methods by which they will be accessible are determined. Here it is important to think about the same security and use API intermediaries. The same intermediary Laravel Sanctum allows you to limit the availability of routes for unauthorized users and take into account the powers of tokens.

  5. Go to main part – developing the logic of controller classes. Here we work with previously created models and relationships to obtain results in accordance with the intended business logic.

  6. Testing changes on the local serverwhat they can help with Laravel Sail and software by type Postman. Modified as necessary Request-, Resource-classes and adjustments are made to the routes and logic of the controllers. Each controller is unique, so in some places you additionally have to create events (for example, to send a notification), somewhere you need to provide filtering capabilities by query parameters, for example, through Pipeline.

Returning to business logic and controllers, I can share a few basic but useful things that I came to over time. Some may find them absurdly funny, but those new to Laravel may find them useful.

Firstly, A very practical move is to put any identifiers, values ​​or messages into constants. This allows you to avoid having to correct the code in several places.

<?php
// ...
private const USERS_LIMIT = 20, 
    		  ROLE_LANDLORD = 'Арендодатель',
			  MSG_USER_NOT_FOUND = 'Пользователь не найден';

SecondlyLaravel has automatic model-to-route binding, which eliminates the need for additional model fetching.

<?php
// Определение маршрута ...
Route::get('/users/{user}', [UserController::class, 'show']);

// Определение метода контроллера ...
public function show(User $user): JsonResponse
{
	return response()->json($user, 200);
}

Third, I can share the method I use to wrap HTTP responses. It allows you to ensure the response structure is consistent regardless of the endpoint:

<?php
// Определение метода для обертки ресурса ...
private function wrapResponse(int $code, string $message, ?array $resource = []): JsonResponse
{
	$result = [
		'code' => $code,
		'message' => $message
	];
	
	if (count($resource)) {
		$result = array_merge($result, ['data' => $resource['data']]);
	}
	
	return response()->json($result, $code);
}

// Определение метода контроллера ...
public function show(User $user): JsonResponse
{
	$userResource = (new UserResource($user))->response()->getData(true);
    
	return $this->wrapResponse(Response::HTTP_OK, 'Success', $userResource);
}

Laravel's comprehensive documentation is a developer's best assistant, but the GitHub repositories can also help you better understand some concepts and solutions:

A short story from life. At the moment when the development of the project had just begun, I thought I could handle MVP in 1-2 months. Theoretically this is possible, but in practice it often turns out differently. In one place you find duplication of code, in the second – the possibility of using built-in helper methods instead of reinventing the wheel, in the third – the obvious need to separate program logic into classes. So it turns out that the deadlines for completing tasks are slowly shifting. At the same time you try don't forget about other developersbecause, for example, it is much easier to collect some data in one resource through Eloquent ORM on the server side than it would have to be done on the client application side by accessing several API endpoints.

Should you consider an API for your project?

My answer is simple – Yes, it is definitely worth considering options for creation or integration. Even if your project does not relate to IT or IoT, working with the information that is generated in the project is the main thing for developing the success of this project. If you are developing your own solution, then thanks to the API you can improve the quality of your products or services, and in the future it will be relatively easy to scale the existing functionality, create a mobile application for clients, and so on. But it should be understood that the API must be deeply thought out, and the ability to scale must be built in from the very beginning. In this case, reliability is a critically important aspect, since here the weakest points of the system as a whole can be detected.

So, developing your own API or integrating external services can pose some serious questions for you, but without such a tool project stagnation becomes more likely.

Information is the oxygen of the modern world.
Ronald Reagan

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *