This article was originally published on the Treblle website, with the permission of the original author Vedran Cindrić, translated and shared by InfoQ Chinese station.
One of the core things I’ve been working on over the past decade is APIs: from simple APIs used by a single client, to APIs for multiple devices and multiple purposes. Over the years, I’ve also had the opportunity to work with many third-party APIs, such as Stripe, Twilio, and others that are less popular but attractive. Almost all of these APIs are based on REST, and some are unique .
There are many reasons for the popularity of REST. It’s easy to understand, flexible, suitable for all sizes, has a large community, and a variety of tools built around it. But, beyond that, I’d say a lot of the reason for its popularity stems from its oldest competitor, SOAP, which is horrible. If you’ve ever used or worked with SOAP, you’ll understand why I say this! Its client side is terrible. The client is terrible, people can use XML as they want, it’s cumbersome, and sometimes the authorization is weird… Fortunately, JSON and REST APIs win this battle.
On the other hand, there are newer, more modern players trying to gain some traction from REST-based APIs. Of course, I’m referring to GraphQL. GraphQL is also based on JSON and shares the benefits of REST such as flexibility, performance, scalability, etc. For me personally, the two main downsides of GraphQL are that it was built by Facebook and that it offloads the API design process to the client. I mean, this puts the onus on mobile developers and front-end developers to create their own special API that can be queried through the database. I don’t know your idea, but I don’t think this idea is the best idea. Don’t get me wrong, I love mobile and front-end development, but they may not have much experience in database design, writing queries, and building APIs. You probably wouldn’t ask your back-end developer to design an app that asks a car mechanic to fix a plane, or a veterinarian to perform an operation on a human. Can they do it? Perhaps, they could. Should they do this? No, I don’t think so.
In my opinion, REST is still the king of the jungle and won’t be easily defeated . The only problem with REST is that, at the end of the day, it’s neither a standard nor a protocol. Rather, it is a set of “architectural constraints”. It’s a gimmicky way that can’t be called a standard, but it captures the imagination of many people. They tend to do what they think, or implement those constraints according to their (mis)understanding. To avoid such misunderstandings, I decided to write down what I think are the ten commandments of REST APIs. Follow these commandments and you’ll get love from your mobile developers, admiration from your back-end dev partners, and rock star status on Twitter.
So, as the lyrics sing: “ Won’t you follow me into the jungle? “
1. Be pragmatic
It’s actually quite simple. If you are building a REST API, you should accept and respond with JSON . Don’t use XML. Don’t use anything else. Just JSON.
True, JSON isn’t “must have” because REST isn’t a standard, but it’s one of the things you’re going to do. It’s as if you have to dress, sleep, or drink a cup of coffee every day. Well, maybe not the last part, but you get what I mean. The sooner we get people out of XML and into JSON, the better for everyone. If you don’t know why JSON is better, let me list some reasons at random:
-
JSON is easier to use, easier to write, easier to read: anyone, even your grandmother, can read it.
-
JSON is faster and takes up less memory space.
-
JSON doesn’t need specialized dependencies or packages to parse it.
-
Every meaningful programming language provides good support for JSON.
If you think this is still too abstract, then I suggest you download a random XML file from the internet and try to parse it. I’ve been through this many times in the 2000s, and I can assure you, you’ll go back to JSON in tears. You have absolutely no reason to use XML instead of JSON in 2021. Of course, if you have a legacy enterprise system, then I share your pain, but even then things are changing. A growing number of older, larger companies are continually upgrading their internal and external APIs, including XML, SOAP, JSON, REST, and more.
JSON should not be used only on the response side, but also on the request side. So, don’t use form-data
or x-www-form-urlencoded
to send data, but use JSON to send it. This makes it easier to read, write, test and manage.
Remember to use JSON when in doubt . All of our developers here would like to express our heartfelt thanks to you.
2. Be organized
You won’t believe it, I’ve seen many times APIs use only the GET method for everything from data storage to filtering. As a developer, you must always strive to understand the tools you use, so when you’re developing an API, it’s important to know how HTTP works. Each HTTP method is designed for a specific situation. Let’s take a look at each before deciding when we should use them.
A small but interesting clarification before we start. Words like “safe” and “idempotent” are often used when describing HTTP methods. These words sound good and mysterious, but they are not that complicated. In plain English, safe means just be ready. You can send requests to this endpoint without worrying about updating, destroying, or changing values. And idempotent means you can send multiple requests to the same endpoint without changing anything or getting different results. In general, all safe methods are also idempotents, but not all idempotents are safe. I know you’ll be confused at first, but we’ll get to that later.
GET method
When wishing to read data, you should use the GET method. This method is not storing, not updating, nor changing data. It only reads data. This is a very simple concept that should not be confusing to anyone. We know that the GET method can only be used to read data, and will return the same data every time. We can say that GET requests are safe and executable.
POST method
Everyone in the world wants you to store some information when you make a POST request. This means you will create a new row in the database, write something somewhere, or create something from scratch. If you want, you can send data to the POST method using multiple content types: multipart/form-data
or x-www-form-urlencoded
or raw ( application/json
, text/plain
, etc.). When building a REST API, I recommend that clients send data in the form of application/json. This way we’re consistent, in the spirit of JSON, and sending JSON data allows you to make really complex requests with ease. Finally, POST operations are unsafe because they do change something on the server side, and they’re not omnipotent because making two requests to the same endpoint results in different resources.
PUT method
PUT requests are most often used for updates. It can also be used to create new records, but the assumption at the time was that the client had to be an ID, defining an ID for the new resource. So, to make your job easier, when you need to update a resource, simply use PUT. PUT is obviously not a safe operation because it makes changes on the server side, but you’ll love it, it’s an idempotent operation.
DELETE method
What I’m trying to say is that there is no need to say anything about this operation. If you want to delete a resource, use the DELETE method directly. This operation is definitely not safe, but some people say it’s idempotent and some people say it’s not.
PATCH method
The PATCH request is used to update the resource again, but unlike PUT, it only needs to update the changed data, whereas PUT can and should update all resources. This is unsafe and not feasible.
Now that we know the basics, what follows is what happens in real life. Most people use GET, POST, and some people use PUT and DELETE. I’ve hardly seen anyone using PATCH. I recommend that you use all available HTTP methods, because that’s what they are for. You can map all CRUD operations to POST, GET, UPDATE and DELETE. I just want you to not use GET to create or update data. Please don’t do this!
3. Heavy semantics
This may be the only time you’ll hear me advise someone to pay attention to semantics. However, in this case, the question is important and involves the issue of proper naming. I often find horrible naming conventions in API documentation. In my opinion, every good REST API should be easy for the average person to understand. From endpoint names to input parameters to JSON keys.
So let’s start with the API endpoint. The rules are also very simple :
The reason for using nouns is because when you make HTTP requests, like we mentioned earlier, you are using verbs. Every HTTP method (GET, POST, PUT, PATCH) is a verb in English. So, it doesn’t make any sense to use double verbs, right! If you named your API endpoint /getUsers
, and you were making a GET request to see all the users, it would be interesting to read this statement. GET /getUsers
. Pointless.
Another common situation I see often is using singular rather than plural endpoint names. This is of course terribly wrong. You need the endpoints of your API to be consistent, simple, and logical. If you use plurals, you can provide the same URI for each HTTP method. If you do GET /users
then you will have all users listed, and when you do POST /users
you will create a user. Therefore, the same URI, uses a different HTTP method (verb). What’s even cooler is that you can request GET /users/:id
to get information for more details. So, as you can see: it’s still the same starting resource name, just with more depth. If you use singular, then GET /user
means you want to have a user, and you also need to use more URIs in other cases. The plural makes more sense.
Going back, let’s look at some good examples and bad examples so we can get 100% of it.
Good example:
-
GET /users
-
POST /users
-
GET /users/23
-
PUT /users/23
-
DELETE /users/23
-
GET /users/23/comments
Bad example:
-
GET /user/23
-
GET /listAllUsers
-
POST /user/create
-
PUT /updateUser/23
-
GET /userComments/23
I think you have some understanding of this point of view. It’s really simple, and the examples above give you an idea of what sounds good and makes more sense.
One more note on endpoint naming: try to use a single word instead of multiple words . If you must use multiple words, use a hyphen between them. For heaven’s sake, use all lowercase letters in the URI.
To wrap up this section, I’ll briefly describe the naming conventions for JSON keys in request and response data. There is a lot of debate on this issue, especially considering that there are three possible cases: camelCase (camel case), snake_case (snake case), and spinal-case ( spine case). Again, no one can stop you from using either, and in theory, you can’t go wrong. However, I recommend snake_case . Why? Stripe uses it. PayPal uses it. Facebook also uses it. do you know? Personally, I find this way we can figure it out 100%: because it’s easier to read, that’s why all our APIs use snake_case . There are some similar studies showing snake_case is better than camelCase in terms of readability.
4. Security
I’ll just say it straight: shame on you if you’re not using HTTPs in 2021 . Your REST API should run over HTTPs without any issues. Using HTTPs simply provides an element of security that HTTP does not. It protects your users from man-in-the-middle attacks and encrypts the communication between the client and the API. Apple, Google and other big companies will soon force you to enable HTTPs. Best of all, today you can get an SSL certificate for free. This can be done through services like Amazon Cloud Technologies and Rout 53, or through services like Azure or Let’s encrypt. They all work great, and I can personally attest to that. You can also purchase a premium SSL certificate at any time. Whatever you do, just use HTTPs for your next API. You will thank me later.
Another thing that really saddens me is that I found out that an API doesn’t require any kind of authorization. If you create an API, you can simply control who can access it. It’s very easy, but many people don’t do it because they find it very cumbersome to implement, use, and maintain. Actually it is not necessary. You can start with a bearer token, this setup should only take 2 minutes to complete. You don’t have to connect it to the database even if you don’t want to. If you want, you can switch to a more mature solution like JWT or oAuth. There are many reasons why you should need some sort of authentication solution. First, you can control the access rights of the API and the number of users that can access it. If there is a problem, such as your API being spammed, hacked, or something else, you just turn off the exposed key. You can also use API keys to track API integrations to see if users are making excessive calls to the API, or if the client is behaving erratically. Finally, you can also collect client, user, and API statistics through API calls.
My point is: treat APIs like your own house . I’m sure you have a couple of doors with keys, and you just gave those keys to someone important. Treat your API the same way.
Also, you need to be careful about sending super sensitive data over the network. We discussed this issue and discussed the importance of SSL for encryption of communications. This will be the first step. The second step is to not pass back sensitive data that may not be used in your app or your website. I’m referring to user addresses, phone numbers, SSNs, or other forms of identification. If not, don’t return it. If you do, then make sure that the person accessing the API and getting the response is the real user you’re sending back the data. I know, it sounds simple, but in reality, people do a lot of crazy things. It’s mostly that they feel like “oh, nothing’s going to happen, it’s just a tiny API that no one knows about.” Trust me at this point. People will find that as long as you ask others to do it, others will do it. So please don’t do it.
Before we wrap up, I want to talk about the debate between UUIDs and IDs. I’m a longtime fan of IDs because it’s shorter and faster, but I think UUIDs are more important in terms of security and privacy benefits. UUIDs are more secure . You can add auto-incrementing ID columns in the database, but if you expose your model to an API, you can use UUIDs. These tips are short, but can save you a lot of trouble.
The last thing I want to say is basic infrastructure security. If you’re using Amazon Cloud Technologies or Azure, then this is to your advantage. API Gateway gives you more security to pass firewalls and detect DDoS attacks. Use it if you can. As long as you can block a specific IP or user, you’ll be looking for something like this. If you’re running Apache on a traditional server, here are two very quick suggestions that will save you a lot of trouble in the days to come.
The first piece of advice is simple: keep updating your software. Apache, PHP, Composer packages, NPM packages. All software must be updated. Make sure you are using the latest and greatest software.
The second suggestion, Apache by default sends a response header to every request, which will tell a potential attacker which version of Apache you are using . The key for this response header is called server
, and its default value may look like this: Apache/2.4.1(Unix)
. All you have to do now is quickly hide the Apache version.
Just open: /etc/apache2/conf-enabled/security.conf
and set the value of ServerTokens
to Prod
. After that, run sudo systemctl restart apache2
and you will make your server more secure. Congratulations.
Another thing you can do when you open etc/apache2/conf-enabled/security.conf
is to turn off ServerSignature
. Just set it to ” Off
” and you’ll be much safer.
Typically, a quarterly security meeting should be held to discuss how to improve security, how to improve, and how to ensure security. You don’t want to be attacked by hackers, DDoS, etc. You have to believe me.
5. Organized
What better way to stay organized than to change the version of the API? I know you’ve read a lot of articles on this subject and thought “My API is too small and only used by one user, so I’m not going to use versioning.” I was like you, and I was did so. I said that too. Be smart, and using versioning in your API is the best decision you can make early on .
The reason I’m holding off on versioning is because, in my opinion, the jump from V1 to V2 happens very rarely at the API level. I’m talking very little about the technical side: so once a year I learn that version management doesn’t make sense to me. However, my idea is wrong. Of course, big version jumps don’t happen very often, but when you have a platform or an application in use or development, you do small upgrades, but more often. I’m referring to weekly updates to schemas, data types, structures or processes, or monthly updates, which are dangerous for people who aren’t updating applications or anything. To do all this, you’ll be sweating every time you make a GIT commit without enabling version management. Not only do you want to be sure that your code isn’t breaking anything or anyone, but you also need to understand how a certain version of your application will behave. Trust me, none of this is fun at all.
Just pick the version management solution that makes the most sense for you and your team. In the software field, the most common version management scheme is: major.minor.patch. The PATCH section is a bit much in my opinion, but you can choose this mode. I usually start with v1.1 and work my way up to v1.9. So, for major version changes, you are changing the core of the API, such as authentication, core schemas, processes, etc. For minor and patch releases, what you usually do is add or remove some small feature, break data structures in some way or something like that.
Another question that confuses you is how do you actually implement version management since there are so many controllable options. You can use version management URI paths, request headers, query parameters, or content negotiation in the following ways. Now, each of these approaches has pros and cons, but I recommend using URL versioning. It makes the most sense, and in many ways, the easiest to understand. By updating, you can know which versions are in use, just from the URL to point to the correct version of the documentation. REST APIs are basically URI based, and I think we should keep that tradition and use URI based versioning. Some examples of this include:
-
api.domain.com/v1/auth/login
-
api.domain.com/v1.2/auth/login
-
api.domain.com/v1.4.5/auth/login
-
api.domain.com/v2/auth/login
To summarize, start using version management early, you can avoid problems in the future, and you can scale your API.
6. Be consistent
You may have heard this phrase. “Consistency is what turns mediocrity into excellence”. Believe it or not, this statement holds true in life and in API design. One characteristic of a good API is its consistency. First, I’m aiming for resource/model consistency, then other areas like naming, URIs, HTTP codes and similar .
As we now know, APIs boil down to resources. A resource can be anything, including users, articles, books, products, and more. Each resource can contain multiple properties, objects, or arrays. Resources are structured, based on your data in the database or other business logic. The key to the success of your API is keeping your resources responsive. You cannot return your endpoint to a completely different resource structure. While this sounds appealing and may be a way to optimize things, you’d better not do it. Mobile developers implementing your API will follow the structure you provide as if they were following the Bible. If you’re sending something different on each endpoint, he/she’s going to have a bad day, and no one wants that. So, try to always send the same resource structure. If you don’t have data, send it as null, or object, or data. Let’s talk reality, assuming we have “articles” resources, sometimes articles may have comments and other times they don’t. Sometimes it makes sense to load comments, and sometimes it doesn’t. That’s fine, but try to have a consistent response in terms of your structure.
When you get an article, you want to load the comments, like this:
{ "status":true, "message":"Getting details for article with UUID: 5b8f6db5-7848-490e-95a7-f7146dd2e30c", "article":{ "title":"Sample title 1", "description":"Sample description 1", "image":"https://domain.com/image-1,jpg", "uuid":"eec33d99-e955-408e-a64a-abec3ae052df", "comments":[ { "text":"Great article", "user":{ "name":"John Doe", "uuid": "5b8f6db5-7848-490e-95a7-f7146dd2e30c" } }, { "text":"Nice one", "user":{ "name":"Jane Doe", "uuid":"2ececb69-d208-46c2-b560-531cb716d25d" } } ] } }
But if you are downloading a series of articles, or you just created an article without any comments, then you should return the following:
{ "status":true, "message":"Article list was a success", "articles":[ { "title":"Sample title 1", "description":"Sample description 1", "image":"https://domain.com/image-1,jpg", "uuid":"eec33d99-e955-408e-a64a-abec3ae052df", "comments":[] }, { "title":"Sample title 2", "description":"Sample description 2", "image":"https://domain.com/image-2,jpg", "uuid":"b8ee70a8-1128-4670-9368-83953fdf722b", "comments":[] } ] }
So if clients expect to see an array of comments, they will still get it, but it will just be empty. This way you won’t be changing your model and you won’t delete objects/arrays.
You save yourself and others a lot of time just by being consistent.
7. Be elegant
If you’re building an API, some problems inevitably occur. This is good. This is also expected. You don’t have to feel bad about API bugs or problems.
You shouldn’t feel bad if your API has a bug or problem. If you don’t provide details, and make sure your API is smarter than anyone else, you should be upset. .
Starting at the top, I found one of the things that developers use the most are HTTP status codes. If you don’t know, HTTP status codes can be used in any situation you can think of. You just need to know which one to use and then go back to the client. There are more than 50 HTTP corresponding status codes, each of which has its own special meaning and needs to be applied in a specific environment. I won’t list them all, but we’ll list some of the most commonly used ones. We already have:
-
Informational response code (starts with 1xx).
-
Success response code (starts with 2xx).
-
Redirect response code (starting with 3xx).
-
Client error response codes (starting with 4xx).
-
Server error response code (starts with 5xx).
So you really have all the states you need. Everything from OK, Unauthorized, Not Found, Internal Server Error to Hypertext Coffee Maker Control Protocol. Yes, the last one is an actual state. This proves that the people who make HTTPs are the most joking people.
Regardless, each state has its meaning. This meaning is widely accepted and understood . So, both Chinese developers and German developers will understand that when you send a 401 (unauthorized) status, it means that the client did not send the correct authentication information. Since we responded with a status code of 401 (Unauthorized), everyone knew it was a client-side failure and had to be resolved by the client, not the API. I’m just giving an example, but what I mean is that you should use the appropriate HTTP status code where appropriate. Using them can help your API be widely understood, consistent, and standardized. While REST is not a standard, it is one that you must adhere to.
Once we have HTTP status codes, we have to give our clients as much detail as possible when we get stuck. For this, we need to do a lot of work. First, we need to be able to anticipate the failure of the API, what others will do, what will not happen, and who will violate these rules. So the first step is strong, rigorous data validation, especially before content is created. When you get the data, you need to check if the data is valid. This means yo check if the ID actually exists, if the value is what we expect, and can store it in the database. Doing the above, and responding with the appropriate status code, will make your API very pleasant to use. So let’s say you already have an endpoint that accepts a user_id and gets the user profile. If we applied the strategy of predicting what might happen, we would do the following:
-
Check if there is a user_id parameter in the request: if not, respond with a 400 Bad Request.
-
Check if the given user_id really exists in the system: if not, respond with 404 (Not Found).
-
If user_id returns a result, respond with 200 (OK).
As you can see, we have multiple failsafes, and in all of them we respond with correct, understandable response codes.
Finally, once we’ve set up our response codes, and anticipated possible failures of the API, we just need to express as much as possible. I know it’s a very difficult thing for us developers to do, but trust me, it’s one of the best things you can do. REST APIs have a general error response model when things go wrong. If we already have this model, client developers can rely on this to provide users with a more detailed explanation of what went wrong. So, let’s imagine a user sends an invalid email from his phone. It gets passed to the API somehow, and the API naturally fires an ack and an error, and responds with a 400 (Bad Request). At the same time, the API should emit a common error response pattern that enables the client to display any or all of the information to the end user. So, if that’s the case, there’s a good chance you’ll get an error message: “The email address entered is invalid”. The client can read it and display it to the user. Again, we need to make sure you can cover everything from authentication to server failures. To achieve this goal, it is best to find a common error pattern that applies to various scenarios. I recommend you to do the following:
{ "title":"Invalid data", "message":"The data you entered is not valid", "errors":[ { "field": "email", "message":"The email address you provided is not real" }, { "field": "phone_number", "message":"You did not enter a phone number at all" } ] }
The error structure of JSON is very simple. We have a header and a message that gives us a general direction, and many times the developer doesn’t show the full error message to the end user. They can set up an alert mode in the iPhone that comes in our message or headline. But we also send an error array, which can hold specific errors with specific information. Providing detailed error messages will help you and other developers working on the API to understand exactly what went wrong. Even if you don’t show this information to the end user, you can see it at your request, or if you’re using a service like Treblle.
So keep in mind that you want to anticipate as many problems as possible . Provides a lot of detail about why things fail, even if no one is using them, and in a language that is generally understood for HTTP response codes.
8. Be smart
This is a more philosophical question, but I think it’s one of the pillars of a good REST API. If you think about the role of APIs in modern platforms, services or applications, then we can say that APIs are the brains of the whole operation . The rationale is that every client you might have (iPhone app, Android app, website, IoT device) talks to the same API. This means that our API plays a pivotal role in the entire ecosystem, and our API solves all problems. If I could add one more word, it would be elegance.
The first thing a smart API does is protect its most valuable resource — the database. This means it should sanitize the database, sanitize it, and prevent any bad data from entering the database. To do this, be sure to validate everything you send from your app to the client, and exclude anything that doesn’t seem right. But when we reject something, we also want to give the user a clear reason why it happened, or why it didn’t happen in this case.
Any good, smart API can handle complex processes independently, rather than relying on the client . The simplest example is to register a user to your application. For all clients, this should be an API call. But on the backend, the API handles all the possible logistics: registering the user on the MailChimp newsletter, storing the push token to Firebase, sending the user a welcome email, and so on. The client segment should not call multiple API endpoints for these things. If we package everything to an endpoint, then you can easily change the process at any point in time without the client noticing. APIs can always have full control over the entire business logic and process, as long as you can get the data you need from them.
Please determine if the API is optimized for cross-platform needs . When you’re dealing with multiple platforms or devices, like iPhones, Android phones, computers, TVs, and similar devices, the API should be able to adapt to them. This means that the API must be flexible enough to handle input that may differ from other clients, while still allowing the client to continue working. A good example of this is resizable photos, if you have an API that provides the content of the photo, then you probably don’t want to send a 4000 x 4000 pixel image to the phone, but you can send it Send it to TV or the website. A smart API would know which client is accessing this endpoint and would return its own optimized resource, even allowing clients to request specific dimensions. There are many more such examples, but you will get the idea.
Minimize client dependencies as much as possible. A smart API will always take client-side bugs into account and try to correct them.
9. Be concise
What is an API if it can’t be optimized quickly? The API of in cannot be a pain point for the entire ecosystem. It’s that simple. There are many ways to guarantee your performance and scalability as a good API should be. Let’s take a look at some of them.
Fast and optimized starts at the database level . Whenever I hear someone say their API is slow, nine times out of ten it has to do with the database. Poor database design, complex queries, sluggish infrastructure, insufficient caching. You should always optimize the database structure, queries, indexes, and everything else that interacts with the database. After you’ve done this, the next thing to do is to ensure that you can serve as much cached data as possible. Sometimes, caching database queries can reduce your load times by 100%.所以,加入你有API 断电,可以向用户展示他们的个人资料或者类似的内容,我敢肯定,它不会在每5 分钟改变。聪明一点,把数据缓存起来。你的用户和调用这个API 的客户端将会很高兴。
另外一个影响性能的因素是,你将大量的数据通过API 下发到客户端。一定要保证你的资源和模式只能转回客户端需要的数据,而非全部数据。如果你要返回一个项目的集合,可能你并不需要完全了解模式细节,以及它们之间的关系——每次都是如此。如果这样会加快进度,就这么办。但始终要努力与响应中返回的模型保持一致。这意味着,如果你不加载关系,就返回一个空数组,如果你不加载计数,就返回0,等等。在建立优秀的REST APIs 时,一致性是关键。
你可以做的另一件非常简单的事情是启用压缩,以减少响应大小并提高性能。最流行的是Gzip 压缩。在Apache 上,它默认启用了一个叫做mod_deflate
的模块。当启用时,你通常可以看到一个响应头的Accept-Encoding
设置为gzip、compress 之类的。尽管它是默认启用的,你仍然需要将它“应用”到你的API 响应中。要做到这一点,我们必须在我们的默认Apache 配置中添加一些规则。因此,让我们实际打开配置文件,像这样: sudo nano /etc/apache2/conf-available/000-default.conf
并添加这个美丽的东西。
这告诉Apache 对各种mime 类型应用Gzip 压缩,如application/javascript、application/json 和其他。一旦我们保存了这个,我们只需要通过输入sudo systemctl restart apache2
来重启Apache,我们就完成了。你的API 响应现在比以前小了50~75%。这有多简单啊! ?
10. 要周到
最后这一块我就不多说了,因为我们在REST 方面已经做得太多了(永远不会过时 ),但我不打算降低这个问题的重要性。开发API 的过程对我们的后端开发人员是很寂寞的。这基本上就是你,一大堆代码和你喜爱的测试工具。当你完成最后一行代码,并把它与生产分支合并的时候,你也许会举的工作已经结束了。但事实并非如此。对于其他许多人来说,旅程才刚刚开始。
有许多人只是等你把工作做完了再去干。要想让他们更好地工作,你就必须在很多方面对API 进行充分的准备。你要保证这个功能有效,文档很好,而且你还得做好了提供集成支持的准备。无论你的文档编写的多么出色,在集成过程中和集成后都会出现问题、困惑和难题。
设身处地为他人着想,尽量让他人的工作更加轻松。构建一个良好的API,遵循我们在这里定义的规则,编写优秀的文档,服务于他人。
考虑一下这些工具,这些工具可以帮助你解决很多构建、传输和运行API 的问题,这些问题都很有挑战性。这些工具之一就是,你猜对了, Treblle 。只要把Treblle 添加到你的API 中,你就可以得到自动生成的支持OpenAPI 规范的文档。然后你会得到实时监控和记录,这样你就可以了解别人在做什么,从而更好地帮助他们。最后,你甚至会得到一个基于这些相同规则的高质量的API 核心。当然,我们在设计时考虑到了整个团队。
希望我能够简单的说明一下你在构建REST API 时可能会遇到的疑惑和担忧。我必须指出的是,REST 并不是一个标准,因此没有人能说你的错误。不过,请考虑一下:作为开发人员,我们每天都在寻求让代码更好、更漂亮、更高效的模式,何不对API 也这么做?如果我们开始遵循一些模式,那么我们都会享受一个更健康、更漂亮的生态系统。
最后,我要引述一位伟人说过的话来结束本文,他就是我们大家的叔叔——Ben Parker。他曾经睿智地说过:“能力越大,责任越大”( With great power comes great responsibility )。当我们谈论REST API 时,这句话再正确不过了。
作者简介:
Vedran Cindrić,Treblle 创始人。
原文链接:
https://treblle.com/blog/the-10-rest-commandments
本文文字及图片出自InfoQ
本文转自https://www.techug.com/post/rest-ten-commandments.html
This site is for inclusion only, and the copyright belongs to the original author.