API Error Codes: A Beginner's Primer
When building APIs for the first time, it is important to understand error status codes and how they impact the overall performance of the API. Error status codes are essential for ensuring that the API is functioning correctly, communicating errors and warnings to the user or system, and providing a seamless experience.
It is important to understand the different types of error status codes, what they mean, and how to interpret them so that your API will function properly.
This blog post will explore the various API error status codes and how to interpret them when building APIs for the first time.
It will provide a comprehensive discussion on the different types of error codes and the best practices for handling them, as well as provide a few tips to help make your API building experience as smooth as possible.
- What are API error Codes?
- Client-side status code
- Server-side status code
- Best practices for handling API Error codes
What are API error Codes?
API error codes are standardized status codes that are returned by an API (Application Programming Interface) in response to a client's request. These codes are used to indicate whether the requested operation was successful or not, and if not, to provide information on the type of error that occurred.
API error codes are typically three-digit numbers, with the first digit indicating the general category of the error, and the remaining two digits specifying the particular error within that category. For example, a 404 error code is a common error that indicates the requested resource was not found on the server.
By providing standardized error codes, APIs can communicate more effectively with clients and developers, and allow them to quickly diagnose and address any issues that arise during the use of the API.
For example, Suppose a client sends a request to an API to retrieve information about a specific resource, such as a user profile, but the API is unable to find that resource. In this case, the API may return a 404 error code, with a message indicating that the requested resource was not found.
The 404 error code is a standardized HTTP status code, which indicates that the server was unable to find the requested resource. The first digit "4" indicates that the error falls under the category of client errors, meaning that the error was caused by an issue with the client's request, rather than an issue with the server. The remaining two digits "04" specify the specific error within that category, in this case, "not found".
The client can then use this information to understand that the requested resource was not found, and take appropriate action, such as displaying an error message to the user or retrying the request with different parameters.
There are two types of error status codes when you build an API for the first time.
- Client-side Status Code
- Server-side Status Code
Client-side Status Code
Client-side status codes are HTTP response codes that are generated by a client's web browser in response to a server's attempt to fulfill the client's request. These codes are used to communicate information about the status of the request to the client, and they can help the client to take appropriate action based on the response.
The 4XX series of status codes often refers to client-side failures, though they can also result from modifications to the API. The top 5 client-side status error codes are listed below, along with explanations of how to fix them.
There are 5 common client-side status codes when you build an API:
1. 400 - Bad Request
The 400 Bad Request error is an HTTP response status code that indicates that the server cannot understand the request sent by the client because it was malformed or incomplete. This means that the server is unable to process the request and return the desired response.
Ways to fix the 400 - Bad Request error
- Check the URL: Make sure the URL you're trying to access is correct and complete.
- Clear your cache and cookies: Clearing your browser's cache and cookies can sometimes help fix the 400 error.
- Check your request syntax: Double-check that your request syntax is correct, including all necessary headers and parameters.
- Check for outdated software: Make sure that your web browser, operating system, and other software are up-to-date.
- Disable browser extensions: Try disabling any browser extensions that may be interfering with your web requests.
- Contact the website owner: If you're trying to access a specific website, you can try contacting the website owner or technical support team for assistance.
- Try a different browser or device: If you're still having trouble after trying the above steps, you can try accessing the website from a different browser or device.
2. 401 - Unauthorized
The client request has not been fulfilled because it does not contain proper authentication credentials for the requested resource, as indicated by the HyperText Transfer Protocol (HTTP) 401 Unauthorized response status code.
Because the client request does not contain proper authentication credentials for the requested resource, the HyperText Transfer Protocol (HTTP) 401 Unauthorized response status code indicates that the client request has not been fulfilled.
This error indicates that the website or web application was unable to authenticate the request that was made. Fortunately, this problem may typically be quickly fixed.
Ways to fix 401 - Unauthorized Error
- Verify that you are using a valid user ID and password to log in.
- It may be worthwhile to momentarily disable password security for the troublesome area of your website if you're a webmaster trying to fix the 401 issue.
- It may be worthwhile to momentarily disable password security for the troublesome area of your website if you're a webmaster trying to fix the 401 issue. Clear it!
3. 403 - Forbidden
Although the server recognizes the request, it will not grant access, as shown by the HTTP response status code 403 Forbidden. For the 403 Forbidden status code, re-authenticating has no effect, even though this status is comparable to 401. Such as insufficient privileges to a resource, the access is connected to the application logic.
Simply put, it indicates that the website's content you're seeking to access is being banned for a specified reason. Although the cause could be something in your power, the content owner or server is more likely to be to blame.
A request that the server cannot accept results in a 403 Forbidden error. This frequently happens because of firewall rules that categorically forbid making this particular request, but other settings, including permissions, may also restrict access based on user privileges.
Ways to fix 403 - Forbidden error
- If you've made it this far and none of the previous fixes have worked, there's a good possibility that the issue is the result of a malfunctioning or incompatible plugin. Try disabling plugins.
- Verify the name of the homepage on your website; it should be
index.html
orindex.php
. The first and easiest is to change the homepage's name toindex.html
orindex.php
.
4. 404 - Not Found
A website user will be informed if a requested page is unavailable with the status code 404. The Hypertext Transfer Protocol response codes on the web include 404 and various response status codes. The 404 error number indicates that a client's requested webpage was not found by the server.
These happen when a page cannot be located. If the URL is typed incorrectly or the page has been erased, this may occur. These 400 errors show that the request cannot be processed by the server. This may occur if there is a coding issue or if the website is unavailable for maintenance.
Ways to fix 404 - Page Not Found Error
- Open a new window and try to close the current one.
- erase the cache. Delete the history and data from your browser.
- To be sure you typed in the proper website address in the search bar, double-check the URL.
- Make sure your website doesn't include any broken links.
5. 429 - Too Many Requests
When a user sends too many requests in a short period, the HTTP 429 Too Many Requests response status code shows this ("rate limiting"). This answer may have a Retry-After header stating how long it should be before a fresh request is made.
The lack of resources to handle so many concurrent requests is the main reason behind 429 errors. If this error, for instance, appears on a hosting server, it may indicate that the package you are using has a cap on the number of requests you are permitted to submit.
Ways to fix 429 - Too many requests error
- The next time you come, the browser can load the website more quickly thanks to cached data. But, as this data builds up, the 429 error may appear. Thus, the first step is to empty the cache on your browser.
- Conflicts may also result from WordPress themes with poor coding. Switching to a default WordPress theme is the simplest method to address this problem.
Server-side Status Code
Server-side status codes are HTTP response codes that are generated by a web server in response to a client's request for a resource. These status codes provide information about the status of the server's attempt to fulfill the request, and they help to ensure that the client and server can communicate effectively.
The 5XX group of status codes typically returns in response to a server error, but if the server misses an invalid API call that ought to produce a 4XX answer, it may also return a 5XX error.
1. 500 - Internal Server Error
The HyperText Transfer Protocol (HTTP) 500 Internal Server Error server error response code denotes that the request could not be processed by the server due to an unexpected condition. This error message is an all-purpose "catch-all" message.
Since the 500 Internal Server Error is a server-side issue, it is most likely not your computer or internet connection that is at fault, but rather the server hosting the website. Although unlikely, there could be a problem on your end, in which case you can try the following: Refresh the website.
When a server-side issue prohibits Apache from handling a request and providing a suitable response, Apache returns a 500 Internal Server Error. This may be the result of several factors, including flawed code, insufficient file permissions, and missing files mentioned in the code.
Ways to fix 500 - Internal Server Error:
- Attempt refreshing the page. The website may return immediately if the host or server is just overloaded.
- Themes and plugins from unofficial sources might easily result in 500 internal server issues. Deactivate them.
2. 501 - Not Implemented
The server does not support the functionality required to complete the request if the HyperText Transfer Protocol (HTTP) 501 Not Implemented server error response code is returned. The Retry-After header, which notifies the requester when to check back to see if the functionality is supported by then, may also be sent by this status.
You can't fix the problem yourself because it's a server-side error; it needs to be fixed by the server and website management.
An HTTP error message, also known as an HTTP status code, is returned by a browser when it accesses a page and discovers something that doesn't operate properly. A problem on the server is indicated if the message's code begins with a 5.
This indicates that anything on the server's end of the website is malfunctioning and preventing a full page load. The root causes of this problem, however, can vary.
Ways to fix 501 - Not Implemented Error:
- Malware or viruses on the computer could be the cause of Error 501. Thus, it's crucial to do a comprehensive scan of your antivirus software and maintain it updated.
- Checking the server's log files to see if any error messages can aid with the problem can be another idea for resolving it.
3. 502 - Bad Gateway
A 502 bad gateway message denotes that a server received a faulty answer from another server. In essence, you have established a connection with some sort of temporary device (such as an edge server) that should fetch all the information required to load the page.
The notice identifies the issue as anything with that process that went wrong. It denotes a server issue rather than one with your device, router, or internet connection. There's a good chance that other website visitors are having the same issue.
Ways to fix 502 - Bad Gateway Error
- Deciding to re-route your internet traffic over a virtual private network (VPN) can assist you to figure out whether the connection to the site is having problems because of your ISP or something else.
- Clearing the browser's cache might help if refreshing the browser a few times doesn't work.
- Check the web server logs from the time the error occurred.
4. 503 - Service Unavailable
An HTTP response status code of 503 Service Unavailable indicates that although your web server is operational, it is now unable to handle a request. It's challenging to determine the precise cause of the problem because the error message is only a general one.
You are not at fault because a 503 error on the HTTP protocol usually signifies that the server is having problems. But, you may troubleshoot and resolve the issue by following a few straightforward actions. When you get a 503 service unavailable error message, you could be left scratching your head and wondering what went wrong.
Ways to 503 - Service Unavailable Error:
- A server employs Memory, CPU, I/O, entry processes, and website inodes as resources. You can determine whether the problem is connected to resource limitations by looking at these metrics.
- Several web hosting typically gives their users automatic upgrades. You have the opportunity to change the server configuration settings and turn off automatic updates.
5. 504 - Gateway Timeout
The 504 "Gateway Timeout" Error denotes that the browser attempted to send an HTTP request to the server but was unable to do so because it did not receive a timely response from another server. You may usually fix it by refreshing the website.
A 504 Gateway Timeout Error denotes that your web server did not immediately receive a response from an upstream server when it attempted to load one of your web pages. Simply said, the communication between your web servers isn't happening swiftly enough.
Ways to fix 504 - Gateway Timeout Error:
- Try opening the WordPress website in incognito mode and using a different browser.
- An alternative computer, network connection, or mobile device might be able to load the page. To determine whether the issue is with the hardware or the internet connection, you may also try restarting the network devices.
Discover the secrets of HTTP status codes with our Complete Guide! Learn how to use them effectively to communicate with clients and servers, and how to handle errors gracefully.
Best practices for handling API Error Codes
- Use standardized error codes: Use well-defined error status codes consistent with industry standards and HTTP specifications. This can make it easier for clients to understand and handle errors.
- Provide informative error messages: Include informative and precise error messages and error codes to help clients understand the reason for the error and what action they can take to resolve it.
- Be consistent: Ensure consistency in the format and content of error messages and error status codes across all API endpoints to avoid confusion and simplify client error handling.
- Use appropriate HTTP methods: Use appropriate HTTP methods to indicate the nature of the request and the desired action. For example, use GET for retrieving data and POST for creating new resources.
- Implement retries: Allow clients to retry failed requests after a specified interval to reduce the impact of temporary network or server issues.
- Log errors: Log all API errors, including error codes, error messages, and any relevant details, to help diagnose and troubleshoot issues.
- Use versioning: Use versioning to indicate API changes and allow clients to migrate to new versions at their own pace without disrupting existing applications.
Here's an example of how to handle API errors in a Node.js application using the Express framework:
const express = require('express');
const app = express();
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
if (!isValidUserId(userId)) {
const error = new Error('Invalid user ID');
error.status = 400; // Set the HTTP status code
return next(error);
}
// Continue with the normal request handling
// ...
});
// Error handler middleware
app.use((err, req, res, next) => {
const statusCode = err.status || 500; // Default to 500 if status code not set
res.status(statusCode).json({
message: err.message
});
});
// Helper function to validate user IDs
function isValidUserId(id) {
// Check if ID is a non-empty string of digits
return /^\d+$/.test(id);
}
In this example, the API endpoint /users/:id
accepts a request to retrieve a user's information based on their ID. The isValidUserId
function is used to validate the user ID, and if it is found to be invalid, an error is thrown with a message of "Invalid user ID" and a status code of 400. The error is then passed to the error handler middleware using the next
function, which sets the appropriate status code and sends a JSON response with the error message.
The error handler middleware is a catch-all middleware that handles any errors that occur in the application. It extracts the status code and error message from the error object and sends a JSON response to the client with that information.
By following this pattern, you can ensure that any errors that occur during the handling of an API request are properly handled and communicated to the client in a consistent and informative manner.
Conclusion
Any issue that prevents access to the website should be resolved as quickly as possible. This is because while your page is down, your visitors are unable to access your material, which is bad for your business. After all, you could lose both the visit and a potential client.
The detrimental effects of unavailability on the SEO strategy are one of the key issues they create. This is due to Google periodically crawling the website's pages for indexing. Hence, it will produce an error message if it tries to access the website and discovers that it is not available.
Refreshing the page and clearing the cache are two simple things that provide reliable solutions for any type of error. Hence, take into account the potential reasons for the problem and the suggested fixes to your website.
Atatus API Monitoring and Observability
Atatus provides Powerful API Observability to help you debug and prevent API issues. It monitors the consumer experience and is notified when abnormalities or issues arise. You can deeply understand who is using your APIs, how they are used, and the payloads they are sending.
Atatus's user-centric API observability tracks how your actual customers experience your APIs and applications. Customers may easily get metrics on their quota usage, SLAs, and more.
It monitors the functionality, availability, and performance data of your internal, external, and third-party APIs to see how your actual users interact with the API in your application. It also validates rest APIs and keeps track of metrics like latency, response time, and other performance indicators to ensure your application runs smoothly.
#1 Solution for Logs, Traces & Metrics
APM
Kubernetes
Logs
Synthetics
RUM
Serverless
Security
More