(API 设计)Top Seven Tips for Building an API

1 篇文章 0 订阅

 

引用地址:https://dzone.com/articles/7-tips-for-building-an-api?utm_source=Top%205&utm_medium=email&utm_campaign=Top%205%202018-06-153

 

 

Top Seven Tips for Building an API

Here are seven important tips for building an API, emphasizing the creation of a specification framework, and versioning strategy using REST and HATEOAS.

As of 2018, businesses are relying more and more on APIs to serve their clients. Microservices and serverless architectures are becoming increasingly prevalent.  This creates a higher number of required API integration points to ensure a competitive advantage and business visibility.

APIs should be designed from the ground up with these needs in mind. In this article, I will discuss seven design tips for APIs that can help to meet these goals (I should note that these insights are based on my experience building APIs for mobile clients, but the lessons apply more broadly to include API designs of any type).

1. Treat Your API as a Product

A key factor when starting with any sort of development is the notion of the product. It defines the stand-alone entity that exposes useful functionality and benefits to the market. It is no easy task to design and implement an API that is easily consumable, scalable, properly documented, and secured without having a strong sense of responsibility and ownership in the process.

Thus, it's only fair that your API is treated like one, complete with its own board, backlog, and sprint plan. In addition, a product owner needs to be assigned to convey the vision of the ideal API to the agile team. Developers and testers must devise a plan to work with the best API practices and also to avoid common mistakes. As a result, the end product needs to be production-ready from day one.

2. Use an API Specification Framework

API frameworks are an attempt to standardize development processes across industries. Typically, they consist of an arsenal of tools that cover the whole development lifecycle, from concept to production. While it's true that adhering to a specification like OpenAPI/Swagger while developing an API is more opinionated, it provides better tooling interoperability. Everyone loves automation. Having the ability to generate documentation, SDKs, and UI interaction points every time the code changes is very useful. If you care about standards and want to provide conventional tools when describing your APIs, then this is a very solid option that pays back in advance.

3. Use a Versioning Strategy

Your API is your product and it evolves over time as business requirements change. As a product, it has a specific version, so clients expect the right responses. Changing a published and used API interface is a ticking bomb. The last thing you want is to introduce breaking changes without clients knowing about it. This is especially true for mobile applications when users may still have old versions installed on their phones.

There are multiple ways to enforce versioning information upon your APIs. Most API designers opt for putting the version information in the URL, as it is practical. For example, the following URL represents a customer's resource endpoint:

 
/api/v1/customers
 

It is very important to stick to a version strategy that is suitable for the business and the available tooling. Later on, if you decide to change a version, it will be easier to provide warnings, updates, and other mechanisms.

4. Use Filtering and Pagination

One common mistake when developing an API is not offering a way to filter or paginate results. When you expose an API that returns a list of items that can change over time, you need to establish a pagination strategy. The reason is simple. Clients, especially mobile ones, cannot view hundreds of list items at once. For example, you can show the first 10. If your API returns the whole database listing for each request, then a lot of resources are being wasted and the performance degrades substantially.

Modern frameworks offer a way to paginate results, but you can also customize your own. A common approach is to use LIMIT and OFFSET statements on your queries. For example, see this MySQL statement for returning a slice of the total result:

 
SELECT * from customers LIMIT 5,10
 

This statement will retrieve rows 6-16 from the database so you can provide a JSON response that gives links to the first, next, previous, and last page of that query based on the LIMIT parameters:

 
// _links
 
{
 
  “first”: /api/v1/customers?page=1,
 
  “prev”: /api/v1/customers?page=1,
 
  “next”: /api/v1/customers?page=3,
 
  “last”: /api/v1/customers?page=9
 
}
 

5. Use REST and HATEOAS

REST is a proven and battle-tested architectural approach to designing Web services, and it is independent of any underlying protocol. Thus, it is very suitable for designing APIs. By using REST principles, you can apply some design considerations, such as:

  • Treating endpoints as resources that have a conventional naming scheme. For example, if you want to expose a list of orders, you expose the following endpoint:
 
GET /api/v1/orders
 

If you want to find a specific order, you’ll supply an ID parameter:

 
GET /api/v1/orders/1
 

This has several advantages, such as better uniformity, readability, and consistency.

  • Promoting stateless transactions. This helps make the services more scalable, as they won’t have the hard coupling constraints of keeping state between client and server communications.
  • Easier navigation within the entire set of resources without prior knowledge of the internal URI scheme with the help of HATEOAS. It enhances the response model of each resource by providing a set of relevant links so that it is easier to interact with the API, without looking up a specification or other metadata service. One good format of HATEOAS is the HAL specification. For example, here is a HAL response to a specific article resource, exposing the relevant links for the reporters:
 
{
 
  “_links”: {
 
    “Self”: {
 
        “href”: /api/v1/articles/1
 
    },
 
    /rels/reporters”: [
 
      {
 
        “href”: /api/v1/reporters/1121
 
        “fullName”: “John Doe”
 
      },
 
      {
 
        “href”: /api/v1/reporters/192
 
        “fullName”: “Alice Jansen”
 
      }
 
    ]
 
  }
 
}
 

6. Secure Your Endpoints

You should not neglect security. Any breach can have catastrophic consequences and lead to serious legal issues. Security controls need to be established early in the development process, and, ideally, your API needs to be assessed by an external vendor. The C.I.A. triad of security applies with the following:

  • Confidentiality is achieved by adding proper authentication controls that provide a means for your system to know who is accessing information or sites. OAuth2 and JWToffer a practical and secure means of authenticating controls. HTTPS must be used at all public endpoints to ensure secure communications.
  • Integrity is achieved by using access controls and authorization strategies to prevent the tampering of data from unauthorized users. Role-Based Authorization provides a good option.
  • Availability is achieved by establishing rate limits, partial responses and caching, in order to prevent extensive usage of API resources or even servers taken down by infinite loops.

7. Use Monitoring and Reporting

While developing and testing your API plays a big part in the process, the real work does not end here. You need to continue providing support, even before the code is deployed to production. If something goes wrong, the right people need to be notified with actionable information, in order to respond by any means necessary. This constitutes a proactive approach when developing your API. If you keep things at bay, when endpoint issues emerge, you can prevent any catastrophic failures. API monitoring tools like Runscope can also help you with that.

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值