Платформа API Connect. Как оптимизация разработки сервисов упрощает бизнес
Расширение рынка, а, как следствие, спрос на более быструю разработку, дефицит по-настоящему квалифицированных кадров дополнительно обосновывают востребованность подобных платформ.
Nocode-платформы способны решить большую часть обусловленных кастомизацией сложностей. Так, платформа API Connect от IBM позволяет разместить API, не имея глубинных знаний в области разработки программного обеспечения. Но это не значит, что в случае кастомизации вы не сможете использовать нормальные языки программирования.
Как уже было сказано, платформа API Connect позволяет создавать API-интерфейсы без написания кода. В том случае если у вас есть определенное количество сервисов, которые вы хотите сделать доступными для внешних пользователей, используя простую оркестровку и минимальную трансформацию данных (например, из JSON в XML), вам действительно не нужно писать код. Встроенный визуальный редактор позволяет провести весь цикл работ от композиции API до его публикации, обеспечения безопасности и контроля использования.
Платформа предоставляет графические инструменты, с помощью которых можно подключать уже созданные внутренние сервисы (или микросервисы), настраивать защиту реализованных интерфейсов (от базовой проверки ключа в заголовке до аутентификации), разграничивать доступ к исходному коду на основе ролей, монетизировать API и анализировать собранную статистику. Повторюсь, все это производится без единой строчки кода.
Система поддерживает и свой язык программирования GatewayScript (который является по сути реализаций ECMAScript 2015 на Node.js с некоторыми специфичными модулями), благодаря которому возможна более гибкая реализация желаемой логики.
Кроме основной системы для разработки и управления API, в состав платформы входит веб-портал для потребителей API, который называется «порталом разработчиков». Здесь разработчики клиентских систем могут получать информацию об использовании API, подписываться на продукты и планы, создавать сообщества с помощью форумов и использовать другие инструменты. Портал поддерживает дизайн-шаблоны, тем самым предоставляя владельцу возможность настроить внешний вид платформы в соответствии с корпоративным стилем компании.
Область применения, какие задачи решает, какие выгоды приносит
API Connect широко применяется компаниями из различных индустрий. Так, в большей части проектов ведущей российской авиакомпании Аэрофлот данная платформа является «цифровым лицом», служащим для быстрой замены внутренних сервисов компании с возможностью сохранения их текущих URL-адресов. Кроме того, платформа реализует возможность прозрачного тестирования корректности запросов внешних систем к сервисам авиаперевозчика. Это делается с целью ограничения на входе и снижения нагрузки на сервисы компании. Но есть и более сложные решения со сложной логикой.
После завершения этапа разработки и публикации API, клиент нового сервиса сразу видит описание интерфейса и автоматически сгенерированную документацию на веб-портале для разработчиков. Здесь разработчик клиентской системы может запросить подписку (разрешение доступа) и получить необходимую документацию для работы.
Благодаря платформе существенно сокращается время, необходимое для подключения новых клиентов и снижается необходимость модификации ранее внедренных решений. Компании, использующие платформу, получают инструмент для быстрой доставки своим клиентам новых возможностей и снижения затрат на внедрение. Это происходит за счет упрощения и автоматизации процессов публикации, обеспечения безопасности и тестирования API.
Он работает как виртуальное устройство на виртуальной машине и использует устройства IBM WebSphere DataPower SOA в качестве шлюзов.
Он предоставляет портал разработчика для разработчиков приложений и для просмотра опубликованных API. Портал администрирования позволяет пользователям устанавливать политики для API, такие как саморегистрация, квоты, управление ключами и политики безопасности. Механизм аналитики предоставляет аналитику на основе ролей для владельцев API, администраторов решений и разработчиков приложений, чтобы управлять API и обеспечивать достижение уровней обслуживания. Существует также служба под названием Cloud Manager, в которой платформа настраивается с серверами, кластерами, шлюзами, пользовательскими репозиториями и т. Д.
Документы Swagger (теперь называемые OpenAPI) и WSDL можно загружать и анализировать в API. API-интерфейсы могут быть созданы путем описания ввода и вывода в пользовательском интерфейсе API Manager с помощью конфигурации. Затем API-интерфейсы могут быть украшены дополнительными данными в виде тегов, двоичной документации и URL-адресов документации. API-интерфейсы могут проксировать существующий API или использовать сборку, в которой создается поток. В таком потоке сборки можно вызывать другие службы, преобразовывать данные ответа, редактировать информацию и отображать данные ответа из внешних API-интерфейсов в ответ API.
Могут быть созданы планы, которые определяют ограничения скорости, необходимость утверждения регистрации и набор API-интерфейсов для предложения разработчикам. Планы могут быть опубликованы в определенной среде.
Шлюз API собирает метрики вызовов, которые доступны для анализа на портале разработчика и в пользовательских интерфейсах Менеджера API. Примеры собранных метрик: использование API, успехи и неудачи.
СОДЕРЖАНИЕ
В продукте есть API на основе REST для доступа и управления пользователями, организациями разработчиков, приложениями и подписками. В продукте есть API на основе REST для доступа к информации о планах, API и аналитике.
Точки расширения
Портал для опытных разработчиков может быть расширен за счет настраиваемого содержимого и тем.
История версий
Версия 4.0.3.0 (ноябрь 2015 г.)
Версия 4.0.3 представила следующие новые возможности:
Возможности перенаправления для аутентификации OAuth
Усовершенствования Advanced Developer Portal
Улучшения определяемой пользователем политики
Улучшения аудита и ведения журнала
Версия 4.0.2.0 (июль 2015 г.)
Версия 40 20 представила следующие новые возможности:
Расширенная поддержка Swagger 2.0
Версия 4.0.1.0 (май 2015 г.)
Версия 40 10 представила следующие новые возможности:
Определите тайм-аут аварийного переключения для базы данных конфигурации
Улучшения соответствия Swagger 2.0
Обновите REST API из файла определения Swagger
Новая роль пользователя системы в пользовательском интерфейсе Cloud Management Console
Кластеризация портала расширенного разработчика
Взаимная проверка подлинности SSL для внешнего подключения
Поддержка методов PATCH и HEAD
Путь URL-адреса API не обязательно должен быть уникальным.
Добавить несколько электронных ключей в приложение
В IBM API Management Version 4.0.1 внесены следующие изменения терминологии:
Версия 4.0.0.0 (март 2015 г.)
Версия 4 представила следующие новые возможности:
Жизненный цикл и управление
Портал для опытных разработчиков
Версия 3 (май 2014 г.)
В этом выпуске добавлены следующие улучшения:
Версия 2.0 (июнь 2013 г.)
Этот выпуск содержал следующие компоненты:
Консоль среды управления IBM API
Менеджер API IBM API Management
Портал разработчиков IBM API Management
Api connect что это
API Connect v5 Getting Started: Developer Toolkit Command Line Interface
Shane Claussen, Chief Architect, API Connect
The API Connect v5 developer toolkit delivers a command line interface named apic to augment the toolset developers use to create and test APIs to be run, managed, and secured by API Connect. The apic command set also provides capability to support devops oriented engineering tasks (e.g. continuous integration and delivery).
All the commands use a command:action syntax (e.g. apic apps:publish ). For the most popular commands, either the command or action portion is optional to simplify usage. For example:
API Designer is the graphical design tool provided by the toolkit to support most of the capablity available via the other command lines. Use the apic edit command to run the API Designer:
Although apic edit is likely the most important command in the toolkit, the intention of this article is to provide an overview of the entire apic command set. That said, if this is your first time using the toolkit, it’s good to know there’s a simple graphical alternative to the CLI.
APIs and Applications
The developer toolkit supports development of API proxies and API implementations. In this article we’ll use the term API when we’re referring to the API proxy and the term application when we’re referring to the API implementation. The developer toolkit provides a first class integrated development environment for developing APIs and applications using the LoopBack framework. LoopBack application projects can be created using the loopback command:
If you haven’t selected an interaction tier framework for developing APIs and Microservices we suggest you take a hard look at LoopBack which has a proven track record for enabling interaction tier applications to be built quickly and easily. However, the developer toolkit was designed with polyglot in mind. Thus, it can be used to create APIs in a language independent manner using OpenAPI (Swagger) to proxy to an existing backend implementation or it can be used to augment applications developed in other languages/frameworks such as Express.JS, Java, Swift, Go, et al.
When a developer is using LoopBack projects, the toolkit supports publishing the API to an API Connect Catalog which supports socialization via the developer portal and policy enforcement via the gateway, and the application to an API Connect App which provides Node.JS runtime capability.
Developers who want to proxy to existing backend services or who are developing their applications using other languages or frameworks use OpenAPI projects that support publishing the OpenAPI (Swagger) definitions to API Connect Catalogs.
Creating Development Artifact Definitions
Development artifacts (e.g. OpenAPI (Swagger) definitions, API product definitions, LoopBack models, and LoopBack data sources) can be created using the apic create command. Use the following CLIs to create the different definition types interactively:
Product and API definitions can also be created non-interactively by providing the —title option (several values get defaulted from the title that can be customized with additional options):
It is also convenient to create the API and product definitions at the same time:
Alternatively, you can create a couple APIs and then reference them when you create a new product:
Validating Development Artifact Definitions
Once you edit the development artifacts or right before you publish the artifacts it’s valuable to validate them:
Updating LoopBack Applications
Once you’ve created a LoopBack application using apic loopback there are a number of useful commands for updating the application. These should be run in the application’s project directory. Here’s an overview of those commands:
Note: These commands are annotated with Stability: prototype because we are looking for feedback on them before we certify them for production.
The services command can be used to manage running processes for testing APIs and applications. For example, the following commands can be used to create a LoopBack application project, start the Micro Gateway and the Node.JS server running the LoopBack application, and test the API and application using the endpoint exposed by the Micro Gateway:
By default, the actions for the services command work on the project or directory relative to where the command was executed enabling services for multiple projects to be managed concurrently and independently.
Here’s a sampling of some useful actions for the services command:
While running services and testing APIs and applications it’s typically useful to tail the Micro Gateway and Node.JS LoopBack logs using the apic logs command. Here’s a couple examples:
The props command provides a mechanism for managing service properties. Here’s a summary of how the props command can be used:
The apic config command provides global and project based configuration variables. These configuration variables will grow over time, but currently they are used to provide the target catalog and/or app for publishing APIs and applications. Global configuration is stored in
/.apiconnect/config and project/directory level configuration is stored in PROJECT_DIR/.apiconnect.
Let’s take a look at the catalog and app configuration variables:
The easiest way to determine the values for these configuration variables is to sign in to the API Manager application of your provisioned Bluemix API Connect service or your on premises cloud, and click on the link icon of the catalog or app you want to publish your API or application to. The dialog that appears will provide you with the identifier of the catalog or app along with the appropriate config:set command.
Below is an example of using apic publish with and without the catalog configuration variable begin set:
Don’t forget about global configuration variables. If you use the same catalog as the default target for multiple projects set the value globally:
API Connect Cloud Authentication
The apic login and apic logout (aliases for auth:login and auth:logout) commands are used to manage your authentication credentials for IBM API Connect clouds. Unlike many systems, API Connect enables you to be simultaneously logged into multiple clouds, enabling you to easily publish and manage APIs and Applications to disparate on premises and Bluemix targets.
Login supports both interactive and non-interactive modes. To login interactively:
Publishing APIs to API catalogs in API Connect clouds enables those APIs to be socialized via developer portals and secured by gateways.
API Connect defines the concept of an API product (or product for short) that’s used to compose APIs for publishing. The product enables API product managers to bundle one or more APIs together, control the visibility of that product in the developer portal (ie only allow partners x, y, and z view and subscribe to the product), and defines one or more plans to provide application developers a set of consumption options. The products that reference the APIs and define the consumption plans are also the primary unit of lifecycle management for APIs.
The apic publish (alias for apic products:publish ) command is used to publish API products to an API Connect cloud. The example below demonstrates creation of a couple APIs composed by a product and how to publish that product and its APIs to a catalog:
The —stage option can be tacked onto apic publish resulting in the product being staged into a catalog instead of published (products have the states of staged, published, deprecated, retired, or archived in the catalog):
Publishing LoopBack APIs and Applications
LoopBack application projects contain both APIs and applications. The same apic publish command described above is used to publish the LoopBack APIs and a new command named apic apps:publish is used to publish the LoopBack application.
When a LoopBack application project is created default API and product definitions are added to the PROJECT_DIR/definitions directory. Publishing the API and product artifacts is the same as any other set of API and product artifacts with the notable difference that these artifacts can be generated directly from the application’s LoopBack models. Here’s a sample CLI narrative for developing and publishing LoopBack APIs to illustrate that scenario:
In addition to the LoopBack APIs, the LoopBack application itself must also be published to an API Connect app which represents a Node.JS runtime. Adding the following two commands to the above set will result in publishing the LoopBack application (Note: apps:publish must be run from within the LoopBack application project directory structure):
Managing API Products
The apic products and apic apis command sets can be used to manage products and APIs that have been published to API Connect catalogs. Here’s a sample for how the products and apis commands can be used for a cradle to grave lifecycle example:
Here’s an example of a more complex lifecycle management scenario where a new version of a product and API hot replaces the original version:
In addition to the lifecycle management capabilities, products and apis in catalogs can be downloaded via the pull and clone actions:
It’s also sometimes useful to clear all products and their APIs from a catalog particularly for sandbox typed catalogs (this action requires the name of the catalog as a confirmation parameter):
We encourage developers to co-locate their APIs and applications in their local source code control systems to support the typical design time iterative lifecycle activities like commits, branching, merges, continuous integration, et al. We believe the developer toolkit provides the bridge from the developer’s environment and the API Connect runtime services.
That said, API Connect does provide an online development sandbox capability named Drafts where API and product definitions can be defined. The toolkit provides the apic drafts command set to enable synchronization of product and API artifacts between the developer’s local source code control systems and drafts.
Similar to the products and apis command sets, drafts can be used to push, pull, and clone artifacts as follows:
In addition to synchronizing data between the developer’s source code control systems and drafts, products that are in drafts can be published:
Again, although it’s possible to develop products and APIs in drafts, and to use the CLI or the drafts user experience to publish products from drafts to a catalog, our recommendation is to clone all your products and apis from drafts, check them into your local source code control system, and then publish directly from there to your catalogs using your source code control system, its tags, service branches, et al, as your master of record.
I hope you found the information above on the apic command useful! Feel free to contact me to ask questions or to provide feedback.
For additional resources pay close attention to the following:
About
API Connect v5 Getting Started: Developer Toolkit Command Line Interface
Что такое системы API Management
Зачем они нужны и какие функции они выполняют.
Всем привет! Меня зовут Антон, я – инженер команды, отвечающей за развитие централизованных IT-сервисов, которыми пользуются продуктовые команды в X5 Retail Group.
В этой статье я расскажу о системах класса API Management и в частности о APIM Gravitee (https://www.gravitee.io), том, что это за класс систем, как они используются для обеспечения потребностей команд разработки. Статья не погружает в технические аспекты, но может быть полезна архитекторам и менеджерам, которые думают о том, чтобы попробовать использовать данный класс систем, но не знают, подойдут ли они для их задач, а также разработчикам, которые могут открыть для себя новые инструменты для удобной работы с API.
Что такое системы API Management
Определение
В данных вариантах определения понятия «API Management» мы видим, что это процессы и системы позволяющие публиковать внутренние API сервисов, прописывать им определенные политики обработки запросов и ответов, контролировать доступ и анализировать статистику использования и производительности. Также рядом могут располагаться несколько подсистем, которые организуют выполнение необязательных функций, но интересных с точки зрения других подразделений, например монетизация API.
Зачем еще один огород городить?
Архитектура сервиса
В архитектуру сервиса API Management обычно входят (см. рис. 1):
Management Core: ядро системы, которое отвечает за формирование политик, планов, работу точками входа и выхода, настроек API Gateways и API, настройку CORS, Failover, Healthcheck, формирование запросов на отображение статистики использования API и логов.
Web/Development Portal: отвечает за UI, отображение настроек, статистики использования API, healthcheck и логов, а также позволяет общаться разработчикам, администраторам и владельцам API.
API Gateways: шлюзы или прокси, они отвечают за обработку запросов от клиентов сервиса согласно установленных настроек и политик, ведение логов запросов и ответов, а также запуск healthcheck по Backend API.
Backend API: отвечает за обработку запросов согласно бизнес-логике конечного сервиса.
Databases: в части сервиса API Management, хранят данные по настройке API, API Gateways, логи запросов клиентов и ответы backend, healthcheck, данные мониторинга практически всех компонентов API Management.
рис. 1 Архитектура сервиса API Management
Плюсы и минусы систем API Management
У данных систем есть несколько преимуществ:
Абстракция: система упрощает сложность сервисов под ним и предоставляет клиентам единый опыт.
Аутентификация: система позволяет пройти аутентификацию, в том числе и через сторонние службы, например Keycloak.
Управление трафиком: система регулирует входящий и исходящий трафик API.
Мониторинг API: система может помочь в мониторинге запросов/ответов клиента.
Преобразования: система позволяет преобразовать запросы/ответы API.
К минусам можно отнести:
Увеличение Latency: шлюзу необходимо время для обработки запросов/ответов согласно настроенным политикам.
TCO: Совокупная стоимость владения для всей цепочки поставки ценности, естественно будет больше, чем просто установить nginx и выставить его наружу.
API Gateways
API Gateways работают как единая точка входа в ЦОД (центр обработки данных), группу распределенных служб или сервисов (см. рис. 2). Также API Gateways могут использоваться для связи между двумя продуктами/сервисами, развернутыми в одном ЦОД. API Gateways принимают вызовы от клиентов, обрабатывают их согласно политикам/правилам и направляют их в соответствующие сервисы. Чтобы API Gateways могли максимально быстро обрабатывать запросы от клиентов их делают максимально легковесными, с использованием асинхронных фреймворков. API Gateways, как правило, работают только на седьмом уровне (L7) модели OSI.
рис. 2
Типы API Gateways
С точки зрения расположения есть два места установки API Gateways:
Local API Gateways работают как шлюз для сервисов внутри организации.
DMZ API Gateways работают как шлюз для внешних потребителей и клиентов сервисов.
Welcome to the IBM API Connect Proof of Technology!
Within, you will explore a series of hands-on labs designed to give you a high-level understanding of the IBM API Connect solution.
The labs will explore a fictional company called ThinkIBM, which sells rare historical IBM machinery. ThinkIBM wants to provide easier access to their inventory database through a collection of APIs.
Throughout the labs, you will take on the role of four key persona’s:
API Developer API Product Manager API Administrator API Consumer
Each section of the guide will identify the persona with which the next few steps relate to, as well as a summary of the tasks you will perform.
Keep an eye out for the tooltips below. These will help guide you through common mistakes, provide tips and helpful context to the task at hand.
Troubleshooting:
This is trouble.
The environment that you will be working in today utilizes IBM’s Bluemix Cloud to host your API Connect service, as well as back-end sample services and a microservice which you will create.
If you are participating in a scheduled Proof of Technology on an IBM-provided system, the prerequisite components have already been installed for you, so please proceed to the Bluemix Account Setup section.
However, if you are exploring these labs on from your own workstation, you will need to install the Developer Toolkit and it’s required components by following the Environment Setup instructions.




