Dzone Refcard 303 Api Integration Patterns 2022
Dzone Refcard 303 Api Integration Patterns 2022
CONTENTS
API Integration
• About API Integration
− Error Codes
Patterns
− Granularity and KISS Principle
− URLs
− Authentication
− Querying
− Pagination
− Bulk
− SDKs
UPDATED BY THOMAS JARDINET
IT ARCHITECT AT MANPOWER • Additional Resources
ABOUT API INTEGRATION vs. REST, XML vs. JSON, different auth mechanisms, workarounds for
APIs can be deployed from anywhere — from your on-premise and SaaS migrations, webhooks vs. polling for eventing, unique error codes,
applications to third parties. You first need a solid idea of which APIs limited search and discovery mechanisms, etc. Further, every data
you will use, allowing you to then go in depth into design and usage model is unique, requiring developers to solve complex data mapping
patterns from that perspective. The deployment architecture for your and transformation problems for each integration.
API management solution depends on this as well. Are the majority
With these challenges in mind, let's review key patterns to follow as you
of your exchanges on-premise? Your API management will have to be
build and maintain your API integrations.
on-premise. Or are they in the cloud? Same logic! And if it's both? The
deployment architecture can be in the cloud, or it can be a hybrid of ERROR CODES
cloud and on-premise.
PATTERN Respect HTTP error codes.
Opportunities for third-party APIs are not always considered at the
beginning of an API management project, which pushes the focus When creating integrations, it's important to understand what error
of deployment to the cloud. However, the diversity of APIs already codes you might be getting from the application provider. As you start
available is extensive and can easily bring differentiating functionality sending requests, it's helpful to understand when things work, but it
to your business. These third-party APIs can either be called directly becomes equally important to understand why they don't.
from a browser, from your corporate website, or from your API
management solution, including for API composition. For third-
party APIs in particular, it's important to consider both the pricing
model as well as the service-level agreement (SLA), seeing as if you
require an SLA of 99.9% for an API, you cannot depend on an API with
an SLA of 99.5%.
Trip Tracking
By the numbers
With integrations, error codes resulting from a lack of access to size And of course, at least for debugging reasons, you should add an error
limitations help guide your application's business logic as well. structure — i.e., with a dynamic error message and code contained in a
dedicated structure:
As the majority of HTTP error codes are standardized by RFCs, it is
important to respect them and to have an exhaustive, precise list Responses:
at your disposal. The following table describes the main HTTP error 400':
description: Bad request
codes, but it's advisable to rely on a complete and up-to-date list, such
content:
as the one from Mozilla:
application/json:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status schema:
$ref: '#/components/schemas/Error'
Table 1
3XX Redirection 304 Not Modified 412 Precondition Granularity and KISS principles work together hand in hand. KISS, for
"Keep it simple st*!" will drive you to define one granularity policy —
4XX Client Error 307 Temp. Redirect 413 Entity Too Big
one that will be the simplest for the end user: the developer who will
5XX Server Error 400 Bad Request 414 URI Too Long consume it! Below is an overview of design paradigms under KISS:
• Design your API with your clients and developers in mind; do not
200 Executed 401 Unauthorized 415 No Media Type
copy/paste your own data model (at least for security reasons...).
201 Created 403 Forbidden 417 Failed
• Design your main use cases first, then others after.
202 Accepted 404 Not Found 500 Internal Error • Design using common terms, not business verbiage.
204 No Content 405 Not a Method 501 Not Implemented • Design with the idea in mind that developers should have only
one way to implement functionalities.
301 Permanent Move 406 Not Accepted 503 Unavailable
With this mindset, fine- and coarse-grained APIs do not align well.
Fine-grained APIs will give you extra effort for no gain, as you’ll need
However, simply mastering the error codes is not enough. Consumers
to discuss how a resource should be categorized, regarding all the
do not have to guess all the error codes you implement in your API.
others resources you have or should expose — all of this just to get a
It is advisable to document the errors implemented directly in the
longer URL.
definition of your swagger description file.
Meanwhile, coarse-grained APIs will give the impression that your API
Here's an example of describing responses, which shows how to
is a mess because you’ll have resources at the same level, even if there
document your error codes:
are no relations between all those resources. To demonstrate these
responses: differences, let see some examples for a pet shop.
'200':
description: OK. Don't:
'400':
//Fine grained
description: Bad request. Parameter should be
Get /animals/mammals/omnivores/cats
a string.
'401': //Coarse grained
description: Authorization failed. Get /cats
'404': Get /payments
description: Not found.
'5XX': You must then aim for medium-grained APIs. Typically, an API resource
description: Internal error. whose structure contains no more than two levels, for example, is a
suitable level of granularity.
For a pet shop, do: programming, you would have a customer class containing addresses
classes — you handle API resources the same way. So based on our
Get /animals/cats
example, to get a customer's addresses, you call the customer number
"id" and then addresses:
Or:
Get /customers/042/addresses
Get /animals/42
{
"id":"42", CONSISTENT CASE
"animalType":"cat" You must define your naming conventions — in particular, a "case
"cat": policy" that determines a consistent letter case across all resources,
{ as users shouldn't have to read your documentation every five minutes
"mustacheSize":"7",
to know which case is required for a specific resource. For parameters,
"cuteness":"maximum"
snake_case and camelCase are often used. While there’s no true reason
}
to favor one over another, developers often prefer camelCase because
}
it is deeply used in Java, while snake_case is easier to read by non-
techies. Meanwhile, spinal-case is preferred for URLs as some servers
With all of this in mind, anyone should be able to use your API without
don't respect case.
having to refer to the documentation, which should be one of your
ultimate goals.
Here are examples of each case:
VERSIONING
SINGULAR AND PLUR AL NOUNS Version must be contained in URLs in order to help developers migrate
Contrary to the SOAP philosophy, REST principles are designed around easily from one version to another. For those who didn't have the time
resources, and nouns should be used in most cases. to migrate, you also risk breaking client integrations for their
applications. Versioning is crucial, and the simplest method is to
Do:
include it in the URL. This way, API calls are logged on your servers, so
Get /orders
you’ll be able to see easily which version of the API was called, even if
you don’t have access to the consuming application.
Don’t:
You cannot be sure that everyone is able to migrate quickly to the latest
Get /Getorders
version, so maintain backward compatibility and support at least two
previous versions:
Finally, using plural nouns instead of singular allows you to handle
collections of resources and single resources at the same time. Get /v1/customers
Get /v2/customers
Do:
Get /customers
HIER ARCHICAL STRUCTURE
200 OK
Your resources should have a structure, and you should use the URL [{"id":"42", "name":"John Doe"},
path to get the details you need. For example, let's say a customer is {"id":"43", "name":"Elisa Re"}]
defined by their own ID, name, and address. As done in object-oriented
For a single instance: application, and the service provider. In this flow, the user grants the
consumer (i.e., the application you want to be integrated) access to the
Get /customers/42
200 OK
service provider by an exchange of tokens through the OAuth endpoint
PATCH /customers/42 {"countryCode":"UK"} Open ID Connect is a standardization of OAuth 2.0 that adds a layer
200 OK of normalized third-party identification and user identity. Not all API
providers need it, but it is recommended if you want fine-grained
DELETE deletes any existing resource. For a single instance: authorization controls and manage several identity providers.
API KEYS For example, Marketo's polling framework is 239 lines of code compared
The use of API keys is still pervasive and very common for API access. to just five lines for a similar webhook.
GET /customers/first
We've automated the movement of data so that our integration is live
200 OK
and fluid, but now it's flowing in like a river when all we really need is
{"name":"John Doe", "status":"VIP"}
a small piece of the data that is useful to what our application is doing.
We need to set query parameters to filter out all the data that we don't GET /customers/last
need. Querying is the last part of the API endpoint, or path, that directs 200 OK
the call to pull only the data you want: {"name":"Johnny Doe", "status":"VIP"}
GET /widgets?query_parameter_here
GET /customers/count
200 OK
The ability to search against databases as well as the target applications {"5"}
is a crucial step. This allows you to test and confirm responses and see
any difference in the data structure between what is returned and what SORTING AND ORDERING
is in the documentation. Querying allows you to modify the key-value An important piece to getting the information you need is how the data
pairs of the request. At the end of the URL path, the query starts with a will be presented at first glance, which becomes especially helpful in
question mark (?) and is separated with an ampersand (&). For example: testing and presenting data through a UI. Many APIs will support sort,
sort_by, or order parameters in the URL to change the ascending
GET /widgets?type=best&date=yesterday
or descending nature of the data you're working with. For example, a
To test an endpoint, there are multiple options depending on which GET /widgets?sort_by=desc(created) can give us the freshest
language you prefer, but the majority of API documentation will widgets in inventory.
reference commands in curl. To test an API, open your Terminal and
PAGINATION
copy/paste the curl command to see what response you get. Now try
adjusting the key-value pairs and fine tune to just the information your Use pagination methods for web front ends and
PATTERN
mobile usage.
application needs from the target endpoint. When adding parameters
to a curl command directly, be sure to include a backslash (/) before
Pagination requires some implied order by a field, or fields, like unique
the question mark of the query as ? and & are special characters.
id, created date, and modified date. There are a few different types of
Tweaking these pairs will decrease the size and overhead your
pagination you can implement based on your needs.
application might expect. You can always increase the amount of data
— especially in testing — to see where you might run into errors.
PARTIAL RESPONSE
In some cases, you don't need to get all fields that define your object.
FILTERS
Partial responses are especially useful in mobile use cases, for example,
To filter, you must use ? to filter resources and use & as separator
where bandwidth optimization is a priority. Use the fields keyword to
between parameters:
get the specific fields you want:
GET /widgets?type=best&date=yesterday
GET /customers/42?fields=name,status
200 OK
SEARCH
{"name":"John Doe", "status":"VIP"
Using the way Google Search works (i.e., with the search keyword) is
}
often the preferred pattern for searching resources — for example,
when you search the word test: www.google.com/search?q=test.
OFFSET
To search a specific resource: This is easiest to implement and is therefore very common. The
LIMIT is the number of rows that will be returned, and OFFSET is the
GET /customers/search?type=vip
starting point of results. For example, a path of /widgets?limit=10
would return 10 rows for the first page. Then the second page could be
To search multiple resources:
/widgets?limit=10&offset=10, which would return 10 rows,
GET /search?q=customers+vip starting with the 10th row, and so on.
The downside of using offset pagination is it becomes less performant Figure 3: Bulk data transfer
with large data sets. For example, if the offset is 1M rows, it will still have
to run through 1M rows before returning the limit requested.
KEYSET
A keyset is helpful to get around large data sets and uses the filter
value of the last page of results as the starting point for the next page
of results using an additional limit URL parameter. For example, the
first call could be GET /widgets?limit=10 with either a unique
identifier such as date created or modified. The second call would be
GET /widgets?limit=10&created:lte:2019-09, the next would be
GET /widgets?limit=10&created:lte:2019-10, and so on.
you're building a UI and need the results to be a certain size. requirements (e.g., for storing passwords). For the medical and
financial sectors in particular, SDKs can help enforce user compliance
BULK with relevant regulations.
ADDITIONAL RESOURCES
• Richardson, L. & Amundsen, M. (2015). RESTful Web APIs. WRITTEN BY THOMAS JARDINET,
IT ARCHITECT AT MANPOWER
O'Reilly.
As an IT architect with seventeen years of
• Biehl, M. (2016). RESTful API Design. CreateSpace.
experience, I oversee business projects by defining
their architectures, whether functional, applicational,
• Louvel, J. (2013). Restlet in Action: Developing RESTful Web
or technical, studying the best path forward. As a supporter
APIs in Java. Manning. of flattened organizations, I also accompany them on the
organizational side, and above all, I seek both an intellectual and
• Kalali, M. & Mehta, B. (2013). Developing RESTful Services With human exchange.
JAX-RS 2.0, WebSockets, and JSON. Packt Publishing.
Copyright © 2022 DZone, Inc. All rights reserved. No part of this publication
may be reproduced, stored in a retrieval system, or transmitted, in any form or
by means of electronic, mechanical, photocopying, or otherwise, without prior
written permission of the publisher.