Api ошибка 403

Some Background

REST APIs use the Status-Line part of an HTTP response message to inform clients of their request’s overarching result.
RFC 2616 defines the Status-Line syntax as shown below:

Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF

A great amount of applications are using Restful APIs that are based on the HTTP protocol for connecting their clients. In all the calls, the server and the endpoint at the client both return a call status to the client which can be in the form of:

  • The success of API call.
  • Failure of API call.

In both the cases, it is necessary to let the client know so that they can proceed to the next step. In the case of a successful API call they can proceed to the next call or whatever their intent was in the first place but in the case of latter they will be forced to modify their call so that the failed call can be recovered.

RestCase

To enable the best user experience for your customer, it is necessary on the part of the developers to make excellent error messages that can help their client to know what they want to do with the information they get. An excellent error message is precise and lets the user know about the nature of the error so that they can figure their way out of it.

A good error message also allows the developers to get their way out of the failed call.

Next step is to know what error messages to integrate into your framework so that the clients on the end point and the developers at the server are constantly made aware of the situation which they are in. in order to do so, the rule of thumb is to keep the error messages to a minimum and only incorporate those error messages which are helpful.

HTTP defines over 40 standard status codes that can be used to convey the results of a client’s request. The status codes are divided into the five categories presented here:

  • 1xx: Informational — Communicates transfer protocol-level information
  • 2xx: Success -Indicates that the client’s request was accepted successfully.
  • 3xx: Redirection — Indicates that the client must take some additional action in order to complete their request.
  • 4xx: Client Error — This category of error status codes points the finger at clients.
  • 5xx: Server Error — The server takes responsibility for these error status codes.

HTTP & REST

If you would ask me 5 years ago about HTTP Status codes I would guess that the talk is about web sites, status 404 meaning that some page was not found and etc. But today when someone asks me about HTTP Status codes, it is 99.9% refers to REST API web services development. I have lots of experience in both areas (Website development, REST API web services development) and it is sometimes hard to come to a conclusion about what and how use the errors in REST APIs.

There are some cases where this status code is always returned, even if there was an error that occurred. Some believe that returning status codes other than 200 is not good as the client did reach your REST API and got response.

Proper use of the status codes will help with your REST API management and REST API workflow management.

If for example the user asked for “account” and that account was not found there are 2 options to use for returning an error to the user:

  • Return 200 OK Status and in the body return a json containing explanation that the account was not found.

  • Return 404 not found status.
    The first solution opens up a question whether the user should work a bit harder to parse the json received and to see whether that json contains error or not.

  • There is also a third solution: Return 400 Error — Client Error. I will explain a bit later why this is my favorite solution.

It is understandable that for the user it is easier to check the status code of 404 without any parsing work to do.

I my opinion this solution is actually miss-use of the HTTP protocol

We did reach the REST API, we did got response from the REST API, what happens if the users misspells the URL of the REST API – he will get the 404 status but that is returned not by the REST API itself.

I think that these solutions should be interesting to explore and to see the benefits of one versus the other.

There is also one more solution that is basically my favorite – this one is a combination of the first two solutions, he is also gives better Restful API services automatic testing support because only several status codes are returned, I will try to explain about it.

Error handling Overview

Error responses should include a common HTTP status code, message for the developer, message for the end-user (when appropriate), internal error code (corresponding to some specific internally determined ID), links where developers can find more info. For example:

‘{ «status» : 400,
«developerMessage» : «Verbose, plain language description of the problem. Provide developers suggestions about how to solve their problems here»,
«userMessage» : «This is a message that can be passed along to end-users, if needed.»,
«errorCode» : «444444»,
«moreInfo» : «http://www.example.gov/developer/path/to/help/for/444444,
http://tests.org/node/444444»,
}’

How to think about errors in a pragmatic way with REST?
Apigee’s blog post that talks about this issue compares 3 top API providers.

REST API Error Codes

Facebook

No matter what happens on a Facebook request, you get back the 200 status code — everything is OK. Many error messages also push down into the HTTP response. Here they also throw an #803 error but with no information about what #803 is or how to react to it.

Twilio

Twilio does a great job aligning errors with HTTP status codes. Like Facebook, they provide a more granular error message but with a link that takes you to the documentation. Community commenting and discussion on the documentation helps to build a body of information and adds context for developers experiencing these errors.

SimpleGeo

Provides error codes but with no additional value in the payload.

Error Handling — Best Practises

First of all: Use HTTP status codes! but don’t overuse them.
Use HTTP status codes and try to map them cleanly to relevant standard-based codes.
There are over 70 HTTP status codes. However, most developers don’t have all 70 memorized. So if you choose status codes that are not very common you will force application developers away from building their apps and over to wikipedia to figure out what you’re trying to tell them.

Therefore, most API providers use a small subset.
For example, the Google GData API uses only 10 status codes, Netflix uses 9, and Digg, only 8.

REST API Status Codes Subset

How many status codes should you use for your API?

When you boil it down, there are really only 3 outcomes in the interaction between an app and an API:

  • Everything worked
  • The application did something wrong
  • The API did something wrong

Start by using the following 3 codes. If you need more, add them. But you shouldn’t go beyond 8.

  • 200 — OK
  • 400 — Bad Request
  • 500 — Internal Server Error

Please keep in mind the following rules when using these status codes:

200 (OK) must not be used to communicate errors in the response body

Always make proper use of the HTTP response status codes as specified by the rules in this section. In particular, a REST API must not be compromised in an effort to accommodate less sophisticated HTTP clients.

400 (Bad Request) may be used to indicate nonspecific failure

400 is the generic client-side error status, used when no other 4xx error code is appropriate. For errors in the 4xx category, the response body may contain a document describing the client’s error (unless the request method was HEAD).

500 (Internal Server Error) should be used to indicate API malfunction 500 is the generic REST API error response.

Most web frameworks automatically respond with this response status code whenever they execute some request handler code that raises an exception. A 500 error is never the client’s fault and therefore it is reasonable for the client to retry the exact same request that triggered this response, and hope to get a different response.

If you’re not comfortable reducing all your error conditions to these 3, try adding some more but do not go beyond 8:

  • 401 — Unauthorized
  • 403 — Forbidden
  • 404 — Not Found

Please keep in mind the following rules when using these status codes:

A 401 error response indicates that the client tried to operate on a protected resource without providing the proper authorization. It may have provided the wrong credentials or none at all.

403 (Forbidden) should be used to forbid access regardless of authorization state

A 403 error response indicates that the client’s request is formed correctly, but the REST API refuses to honor it. A 403 response is not a case of insufficient client credentials; that would be 401 (“Unauthorized”). REST APIs use 403 to enforce application-level permissions. For example, a client may be authorized to interact with some, but not all of a REST API’s resources. If the client attempts a resource interaction that is outside of its permitted scope, the REST API should respond with 403.

404 (Not Found) must be used when a client’s URI cannot be mapped to a resource

The 404 error status code indicates that the REST API can’t map the client’s URI to a resource.

RestCase

Conclusion

I believe that the best solution to handle errors in a REST API web services is the third option, in short:
Use three simple, common response codes indicating (1) success, (2) failure due to client-side problem, (3) failure due to server-side problem:

  • 200 — OK
  • 400 — Bad Request (Client Error) — A json with error \ more details should return to the client.
  • 401 — Unauthorized
  • 500 — Internal Server Error — A json with an error should return to the client only when there is no security risk by doing that.

I think that this solution can also ease the client to handle only these 4 status codes and when getting either 400 or 500 code he should take the response message and parse it in order to see what is the problem exactly and on the other hand the REST API service is simple enough.

The decision of choosing which error messages to incorporate and which to leave is based on sheer insight and intuition. For example: if an app and API only has three outcomes which are; everything worked, the application did not work properly and API did not respond properly then you are only concerned with three error codes. By putting in unnecessary codes, you will only distract the users and force them to consult Google, Wikipedia and other websites.

Most important thing in the case of an error code is that it should be descriptive and it should offer two outputs:

  • A plain descriptive sentence explaining the situation in the most precise manner.
  • An ‘if-then’ situation where the user knows what to do with the error message once it is returned in an API call.

The error message returned in the result of the API call should be very descriptive and verbal. A code is preferred by the client who is well versed in the programming and web language but in the case of most clients they find it hard to get the code.

As I stated before, 404 is a bit problematic status when talking about Restful APIs. Does this status means that the resource was not found? or that there is not mapping to the requested resource? Everyone can decide what to use and where :)

When I call my Amazon API Gateway API, I get a 403 error. How do I troubleshoot 403 errors from API Gateway?

Short description

An HTTP 403 response code means that a client is forbidden from accessing a valid URL. The server understands the request, but it can’t fulfill the request because of client-side issues.

API Gateway APIs can return 403 responses for any of the following reasons:

Issue Response header Error message Root cause
Access denied «x-amzn-errortype» = «AccessDeniedException» «User is not authorized to access this resource with an explicit deny» The caller isn’t authorized to access an API that’s using an API Gateway Lambda authorizer.
Access denied «x-amzn-errortype» = «AccessDeniedException» «User: <user-arn> is not authorized to perform: execute-api:Invoke on resource: <api-resource-arn> with an explicit deny» The caller isn’t authorized to access an API that’s using AWS Identity and Access Management (IAM) authorization. Or, the API has an attached resource policy that explicitly denies access to the caller. For more information, see IAM authentication and resource policy.
Access denied «x-amzn-errortype» = «AccessDeniedException» «User: anonymous is not authorized to perform: execute-api:Invoke on resource:<api-resource-arn>» The caller isn’t authorized to access an API that’s using IAM authorization. Or, the API has an attached resource policy that doesn’t explicitly allow the caller to invoke the API. For more information, see IAM authentication and resource policy.
Access denied «x-amzn-errortype» = «AccessDeniedException» «The security token included in the request is invalid.» The caller used IAM keys that aren’t valid to access an API that’s using IAM authorization.
Missing authentication token «x-amzn-errortype» = «MissingAuthenticationTokenException» «Missing Authentication Token» An authentication token wasn’t found in the request.
Authentication token expired «x-amzn-errortype» = «InvalidSignatureException» «Signature expired» The authentication token in the request has expired.
API key isn’t valid «x-amzn-errortype» = «ForbiddenException» «Invalid API Key identifier specified» The caller used an API key that’s not valid for a method that requires an API key.
Signature isn’t valid «x-amzn-errortype» = «InvalidSignatureException» «The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method.» The signature in the request doesn’t match that on the server when accessing an API that’s using IAM authorization.
AWS WAF filtered «x-amzn-errortype» = «ForbiddenException» «Forbidden» The request is blocked by web application firewall filtering when AWS WAF is activated in the API.
Resource path doesn’t exist «x-amzn-errortype» = «MissingAuthenticationTokenException» «Missing Authentication Token» A request with no «Authorization» header is sent to an API resource path that doesn’t exist. For more information, see How do I troubleshoot 403 «Missing Authentication Token» errors from an API Gateway REST API endpoint?
Resource path doesn’t exist «x-amzn-errortype» = «IncompleteSignatureException» «Authorization header requires ‘Credential’ parameter. Authorization header requires ‘Signature’ parameter. Authorization header requires ‘SignedHeaders’ parameter. Authorization header requires existence of either a ‘X-Amz-Date’ or a ‘Date’ header. Authorization=allow» A request with an «Authorization» header is sent to an API resource path that doesn’t exist.
Invoking a private API using public DNS names incorrectly «x-amzn-errortype» = «ForbiddenException» «Forbidden» Invoking a private API from within an Amazon Virtual Private Cloud (Amazon VPC) using public DNS names incorrectly. For example: the «Host» or «x-apigw-api-id» header is missing in the request. For more information, see Invoking your private API using endpoint-specific public DNS hostnames.
Invoking a REST API that has a custom domain name using the default execute-api endpoint «x-amzn-errortype» = «ForbiddenException» «Forbidden» The caller uses the default execute-api endpoint to invoke a REST API after deactivating the default endpoint. For more information, see Disabling the default endpoint for a REST API
Invoking an API Gateway custom domain name that requires mutual Transport Layer Security (TLS) using a client certificate that’s not valid. «x-amzn-errortype» = «ForbiddenException» «Forbidden» The client certificate presented in the API request isn’t issued by the custom domain name’s truststore, or it isn’t valid. For more information, see How do I troubleshoot HTTP 403 Forbidden errors from an API Gateway custom domain name that requires mutual TLS?
Invoking a custom domain name without a base path mapping «x-amzn-errortype» = «ForbiddenException» «Forbidden» The caller invokes a custom domain without a base path being mapped to an API.   For more information, see Setting up custom domain names for REST APIs.
Invoking an API with custom domain enabled when the domain URL includes the stage «x-amzn-errortype» = «MissingAuthenticationTokenException» «Missing Authentication Token» An API mapping specifies an API, a stage, and optionally a path to use for the mapping. Therefore, when an API’s stage is mapped to a custom domain, you no longer need to include the stage in the URL. For more information, see Working with API mappings for REST APIs.
Stage in request URL is not valid «x-amzn-errortype» = «ForbiddenException» «Forbidden» The caller’s request URL includes a stage that doesn’t exist. Verify that the stage exists and the spelling of the request URL. For more information, see Invoking a REST API in Amazon API Gateway.

Resolution

Consider the source of the error

If the 403 error was reported from other resources, there might be another cause for the error. For example:

  • If the error was reported in a web browser, then that error might be caused by an incorrect proxy setting. The proxy server returns a 403 error if HTTP access isn’t allowed.
  • If there’s another AWS service in front of the API, then that service can reject the request with a 403 error in the response. For example: Amazon CloudFront.

Identify what’s causing the error

If you haven’t done so already, set up Amazon CloudWatch access logging for your API. Then, view your API’s execution logs in CloudWatch to determine if requests are reaching the API.

Note: HTTP APIs don’t support execution logging. To troubleshoot 403 errors returned by a custom domain name that requires mutual TLS and invokes an HTTP API, you must do the following:

1.    Create a new API mapping for your custom domain name that invokes a REST API for testing only.

2.    Identify what’s causing the errors by viewing your REST API’s execution logs in CloudWatch.

3.    After the error is identified and resolved, reroute the API mapping for your custom domain name back to your HTTP API.

Confirm that the requested resource exists in the API definition

Note: If you receive errors when running AWS Command Line Interface (AWS CLI) commands, make sure that you’re using the most recent AWS CLI version.

Verify the following using either the API Gateway console or the AWS CLI:

  • The API is deployed with the latest API definition.
  • The requested resource exists in the API definition.

Use curl to get request and response details

If the error can be reproduced, use the curl -v command to get more details between the client and the API similar to the following:

curl -X HTTP_VERB -v https://{api_id}.execute-api.{region}.amazonaws.com/{stage_name}/{resource_name}

Note: For more information, see the curl project website.

Verify that the request header is correct

If the error is the result of an API key that’s not valid, then verify that the «x-api-key» header was sent in the request.

Verify that the DNS setting on any interface Amazon VPC endpoints is set correctly

Note: Confirm the following for APIs invoked from an Amazon VPC that has an interface VPC endpoint only.

Verify that the DNS setting of the interface endpoint is set correctly based on the type of API that you’re using.

Keep in mind the following:

  • To invoke a Regional API from inside an Amazon VPC, private DNS names must be deactivated on the interface endpoint. Then, the endpoint’s hostname can be resolved by a public DNS. For more information, see Creating a private API in Amazon API Gateway.
  • To invoke a private API from inside an Amazon VPC using the API’s private DNS name, private DNS names must be activated on the interface endpoint. Then, the interface endpoint’s hostname can be resolved to the Amazon VPC’s local subnet resources. For more information, see How to invoke a private API.
    Note: You don’t need to set up a private DNS if you’re invoking the private API using either of the following:
    The private API’s public DNS name.
    -or-
    An Amazon Route 53 alias.

Review the API’s resource policy

Review your API’s resource policy to verify the following:

  • (For APIs invoked from an Amazon VPC with an interface VPC endpoint) The API’s resource policy grants the Amazon VPC or the interface endpoint access to the API.
  • The resource policy’s resource specifications and formatting are correct.
    Note: There’s no validation of the resource specification when saving a resource policy. For examples, see API Gateway resource policy examples.
  • The caller is allowed to invoke the API endpoint by the authentication type that you’ve defined for the API. For more information, see How API Gateway resource policies affect authorization workflow.

Review HTTP request and response messages

Reproduce the error in a web browser, if possible. Then, use the browser’s network tools to capture the HTTP request and response messages and analyze them to determine where the error occurred.

Note: For offline analysis, save the messages in an HTTP Archive (HAR) file.


Related information

Common errors — Amazon API Gateway

How do I allow only specific IP addresses to access my API Gateway REST API?

How do I troubleshoot issues when connecting to an API Gateway private API endpoint?

How do I turn on Amazon CloudWatch Logs for troubleshooting my API Gateway REST API or WebSocket API?

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

    1. 404 — Not Found
    2. 401 — Unauthorized
    3. 403 — Forbidden
    4. 400 — Bad Request
    5. 429 — Too Many Requests
  • Server-side status code

    1. 500 — Internal Server Error
    2. 502 — Bad Gateway
    3. 503 — Service Unavailable
    4. 504 — Gateway Timeout
    5. 501 — Not Implemented
  • 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.

API Error Status CodesAPI Error Codes

API Error Codes

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.

  1. Client-side Status Code
  2. 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

  1. Check the URL: Make sure the URL you’re trying to access is correct and complete.
  2. Clear your cache and cookies: Clearing your browser’s cache and cookies can sometimes help fix the 400 error.
  3. Check your request syntax: Double-check that your request syntax is correct, including all necessary headers and parameters.
  4. Check for outdated software: Make sure that your web browser, operating system, and other software are up-to-date.
  5. Disable browser extensions: Try disabling any browser extensions that may be interfering with your web requests.
  6. 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.
  7. 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.

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 or index.php. The first and easiest is to change the homepage’s name to index.html or index.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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. Implement retries: Allow clients to retry failed requests after a specified interval to reduce the impact of temporary network or server issues.
  6. Log errors: Log all API errors, including error codes, error messages, and any relevant details, to help diagnose and troubleshoot issues.
  7. 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.

Try your 14-day free trial of Atatus!

Assume your Web API is protected and a client attempts to access it without the appropriate credentials. How do you deal with this scenario? Most likely, you know you have to return an HTTP status code. But what is the more appropriate one? Should it be 401 Unauthorized or 403 Forbidden? Or maybe something else?

As usual, it depends 🙂. It depends on the specific scenario and also on the security level you want to provide. Let’s go a little deeper.

If you prefer, you can watch a video on the same topic:

Web APIs and HTTP Status Codes

Before going into the specific topic, let’s take a quick look at the rationale of HTTP status codes in general. Most Web APIs are inspired by the REST paradigm. Although the vast majority of them don’t actually implement REST, they usually follow a few RESTful conventions when it comes to HTTP status codes.

The basic principle behind these conventions is that a status code returned in a response must make the client aware of what is going on and what the server expects the client to do next. You can fulfill this principle by giving answers to the following questions:

  • Is there a problem or not?
  • If there is a problem, on which side is it? On the client or on the server side?
  • If there is a problem, what should the client do?

This is a general principle that applies to all the HTTP status codes. For example, if the client receives a 200 OK status code, it knows there was no problem with its request and expects the requested resource representation in the response’s body. If the client receives a 201 Created status code, it knows there was no problem with its request, but the resource representation is not in the response’s body. Similarly, when the client receives a 500 Internal Server Error status code, it knows that this is a problem on the server side, and the client can’t do anything to mitigate it.

In summary, your Web API’s response should provide the client with enough information to realize how it can move forward opportunely.

Let’s consider the case when a client attempts to call a protected API. If the client provides the appropriate credentials (e.g., a valid access token), its request is accepted and processed. What happens when the client has no appropriate credentials? What status code should your API return when a request is not legitimate? What information should it return, and how to guarantee the best security experience?

Fortunately, in the OAuth security context, you have some guidelines. Of course, you can use them even if you don’t use OAuth to secure your API.

«The basic principle behind REST status code conventions is that a status code must make the client aware of what is going on and what the server expects the client to do next»

Tweet

Tweet This

When to Use 400 Bad Request?

Let’s start with a simple case: a client calls your protected API, omitting a required parameter. In this case, your API should respond with a 400 Bad Request status code. In fact, if that parameter is required, your API can’t even process the client request. The client’s request is malformed.

Your API should return the same status code even when the client provides an unsupported parameter or repeats the same parameter multiple times in its request. In both cases, the client’s request is not as expected and should be refused.

Following the general principle discussed above, the client should be empowered to understand what to do to fix the problem. So, you should add in your response’s body what was wrong with the client’s request. You can provide those details in the format you prefer, such as simple text, XML, JSON, etc. However, using a standard format like the one proposed by the Problem Details for HTTP APIs specifications would be more appropriate to enable uniform problem management across clients.

For example, if your client calls your API with an empty value for the required data parameter, the API could reply with the following response:

HTTP/1.1 400 Bad Request
Content-Type: application/problem+json
Content-Language: en

{
  "type": "https://myapi.com/validation-error",
  "title": "Validation error",
  "detail": "Your request parameters are not valid.",
  "invalid-params": [
    {
      "name": "data",
      "reason": "cannot be blank."
    }
  ]
}

When to Use 401 Unauthorized?

Now, let’s assume that the client calls your protected API with a well-formed request but no valid credentials. For example, in the OAuth context, this may fall in one of the following cases:

  • An access token is missing.
  • An access token is expired, revoked, malformed, or invalid for other reasons.

In both cases, the appropriate status code to reply with is 401 Unauthorized. In the spirit of mutual collaboration between the client and the API, the response must include a hint on how to obtain such authorization. That comes in the form of the WWW-Authenticate header with the specific authentication scheme to use. For example, in the case of OAuth2, the response should look like the following:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example"

You have to use the Bearer scheme and provide the realm parameter to indicate the set of resources the API is protecting.

If the client request does not include any access token, demonstrating that it wasn’t aware that the API is protected, the API’s response should not include any other information.

On the other hand, if the client’s request includes an expired access token, the API response could include the reason for the denied access, as shown in the following example:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example",
                  error="invalid_token",
                  error_description="The access token expired"

When to Use 403 Forbidden?

Let’s explore a different case now. Assume, for example, that your client sends a request to modify a document and provides a valid access token to the API. However, that token doesn’t include or imply any permission or scope that allows the client to perform the desired action.

In this case, your API should respond with a 403 Forbidden status code. With this status code, your API tells the client that the credentials it provided (e.g., the access token) are valid, but it needs appropriate privileges to perform the requested action.

To help the client understand what to do next, your API may include what privileges are needed in its response. For example, according to the OAuth2 guidelines, your API may include information about the missing scope to access the protected resource.

Try out the most powerful authentication platform for free.Get started →

Security Considerations

When you plan how to respond to your client’s requests, always keep security in mind.

How to deal with response details

A primary security concern is to avoid providing useful information to potential attackers. In other words, returning detailed information in the API responses to attempts to access protected resources may be a security risk.

For example, suppose your API returns a 401 Unauthorized status code with an error description like The access token is expired. In this case, it gives information about the token itself to a potential attacker. The same happens when your API responds with a 403 Forbidden status code and reports the missing scope or privilege.

In other words, sharing this information can improve the collaboration between the client and the server, according to the basic principle of the REST paradigm. However, the same information may be used by malicious attackers to elaborate their attack strategy.

Since this additional information is optional for both the HTTP specifications and the OAuth2 bearer token guidelines, maybe you should think carefully about sharing it. The basic principle on sharing that additional information should be based on the answer to this question: how would the client behave any differently if provided with more information?

For example, in the case of a response with a 401 Unauthorized status code, does the client’s behavior change when it knows that its token is expired or revoked? In any case, it must request a new token. So, adding that information doesn’t change the client’s behavior.

Different is the case with 403 Forbidden. By informing your client that it needs a specific permission, your API makes it learn what to do next, i.e., requesting that additional permission. If your API doesn’t provide this additional information, it will behave differently because it doesn’t know what to do to access that resource.

Don’t let the client know…

Now, assume your client attempts to access a resource that it MUST NOT access at all, for example, because it belongs to another user. What status code should your API return? Should it return a 403 or a 401 status code?

You may be tempted to return a 403 status code anyway. But, actually, you can’t suggest any missing permission because that client has no way to access that resource. So, the 403 status code gives no actual helpful information. You may think that returning a 401 status code makes sense in this case. After all, the resource belongs to another user, so the request should come from a different user.

However, since that resource shouldn’t be reached by the current client, the best option is to hide it. Letting the client (and especially the user behind it) know that resource exists could possibly lead to Insecure Direct Object References (IDOR), an access control vulnerability based on the knowledge of resources you shouldn’t access. Therefore, in these cases, your API should respond with a 404 Not Found status code. This is an option provided by the HTTP specification:

An origin server that wishes to «hide» the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found).

For example, this is the strategy adopted by GitHub when you don’t have any permission to access a repository. This approach avoids that an attacker attempts to access the resource again with a slightly different strategy.

How to deal with bad requests

When a client sends a malformed request, you know you should reply with a 400 Bad Request status code. You may be tempted to analyze the request’s correctness before evaluating the client credentials. You shouldn’t do this for a few reasons:

  • By evaluating the client credentials before the request’s validity, you avoid your API processing requests that aren’t allowed to be there.
  • A potential attacker could figure out how a request should look without being authenticated, even before obtaining or stealing a legitimate access token.

Also, consider that in infrastructures with an API gateway, the client credentials will be evaluated beforehand by the gateway itself, which doesn’t know at all what parameters the API is expecting.

The security measures discussed here must be applied in the production environment. Of course, in the development environment, your API can provide all the information you need to be able to diagnose the causes of an authorization failure.

Recap

Throughout this article, you learned that:

  • 400 Bad Request is the status code to return when the form of the client request is not as the API expects.
  • 401 Unauthorized is the status code to return when the client provides no credentials or invalid credentials.
  • 403 Forbidden is the status code to return when a client has valid credentials but not enough privileges to perform an action on a resource.

You also learned that some security concerns might arise when your API exposes details that malicious attackers may exploit. In these cases, you may adopt a more restricted strategy by including just the needed details in the response body or even using the 404 Not Found status code instead of 403 Forbidden or 401 Unauthorized.

The following cheat sheet summarizes what you learned:

4xx HTTP status codes cheat sheet

REST API использует строку состояния в HTTP ответе (статус ответа), чтобы информировать Клиентов о результате запроса.

Вообще HTTP определяет 40 стандартных кодов состояния (статусов ответа), которые делятся на пять категорий. Ниже выделены только те коды состояния, которые часто используются в REST API.

Категория Описание
1xx: Информация В этот класс содержит заголовки информирующие о процессе передачи. Это обычно предварительный ответ, состоящий только из Status-Line и опциональных заголовков, и завершается пустой строкой. Нет обязательных заголовков. Серверы НЕ ДОЛЖНЫ посылать 1xx ответы HTTP/1.0 клиентам.
2xx: Успех Этот класс кодов состояния указывает, что запрос клиента был успешно получен, понят, и принят.
3xx: Перенаправление Коды этого класса сообщают клиенту, что для успешного выполнения операции необходимо сделать другой запрос, как правило, по другому URI. Из данного класса пять кодов 301, 302, 303, 305 и 307 относятся непосредственно к перенаправлениям.
4xx: Ошибка клиента Класс кодов 4xx предназначен для указания ошибок со стороны клиента.
5xx: Ошибка сервера Коды ответов, начинающиеся с «5» указывают на случаи, когда сервер знает, что произошла ошибка или он не может обработать запрос.

Коды состояний в REST

Звездочкой * помечены популярные (часто используемые) коды ответов.

200 * (OK)

Запрос выполнен успешно. Информация, возвращаемая с ответом зависит от метода, используемого в запросе, например при:

  • GET Получен объект, соответствующий запрошенному ресурсу.
  • HEAD Получены поля заголовков, соответствующие запрошенному ресурсу, тело ответа пустое.
  • POST Запрошенное действие выполнено.

201 * (Created — Создано)

REST API отвечает кодом состояния 201 при каждом создании ресурса в коллекции. Также могут быть случаи, когда новый ресурс создается в результате какого-либо действия контроллера, и в этом случае 201 также будет подходящем ответом.

Ссылка (URL) на новый ресурс может быть в теле ответа или в поле заголовка ответа Location.

Сервер должен создать ресурс перед тем как вернуть 201 статус. Если это невозможно сделать сразу, тогда сервер должен ответить кодом 202 (Accepted).

202 (Accepted — Принято)

Ответ 202 обычно используется для действий, которые занимают много времени для обработки и не могут быть выполнены сразу. Это означает, что запрос принят к обработке, но обработка не завершена.

Его цель состоит в том, чтобы позволить серверу принять запрос на какой-либо другой процесс (возможно, пакетный процесс, который выполняется только один раз в день), не требуя, чтобы соединение агента пользователя с сервером сохранялось до тех пор, пока процесс не будет завершен.

Сущность, возвращаемая с этим ответом, должна содержать указание на текущее состояние запроса и указатель на монитор состояния (расположение очереди заданий) или некоторую оценку того, когда пользователь может ожидать выполнения запроса.

203 (Non-Authoritative Information — Неавторитетная информация)

Предоставленная информация взята не из оригинального источника (а, например, из кэша, который мог устареть, или из резервной копии, которая могла потерять актуальность). Этот факт отражен в заголовке ответа и подтверждается этим кодом. Предоставленная информация может совпадать, а может и не совпадать с оригинальными данными.

204 * (No Content — Нет контента)

Код состояния 204 обычно отправляется в ответ на запрос PUT, POST или DELETE, когда REST API отказывается отправлять обратно любое сообщение о состоянии проделанной работы.

API может также отправить 204 статус в ответ на GET запрос, чтобы указать, что запрошенный ресурс существует, но не имеет данных для добавления их в тело ответа.

Ответ 204 не должен содержать тело сообщения и, таким образом, всегда завершается первой пустой строкой после полей заголовка.

205 — (Reset Content — Сброшенное содержимое)

Сервер успешно обработал запрос и обязывает клиента сбросить введенные пользователем данные. В ответе не должно передаваться никаких данных (в теле ответа). Обычно применяется для возврата в начальное состояние формы ввода данных на клиенте.

206 — (Partial Content — Частичное содержимое)

Сервер выполнил часть GET запроса ресурса. Запрос ДОЛЖЕН был содержать поле заголовка Range (секция 14.35), который указывает на желаемый диапазон и МОГ содержать поле заголовка If-Range (секция 14.27), который делает запрос условным.

Запрос ДОЛЖЕН содержать следующие поля заголовка:

  • Либо поле Content-Range (секция 14.16), который показывает диапазон, включённый в этот запрос, либо Content-Type со значением multipart/byteranges, включающими в себя поля Content-Range для каждой части. Если в заголовке запроса есть поле Content-Length, его значение ДОЛЖНО совпадать с фактическим количеством октетов, переданных в теле сообщения.
  • Date
  • ETag и/или Content-Location, если ранее был получен ответ 200 на такой же запрос.
  • Expires, Cache-Control, и/или Vary, если значение поля изменилось с момента отправления последнего такого же запроса

Если ответ 206 — это результат выполнения условного запроса, который использовал строгий кэш-валидатор (подробнее в секции 13.3.3), в ответ НЕ СЛЕДУЕТ включать какие-либо другие заголовки сущности. Если такой ответ — результат выполнения запроса If-Range, который использовал «слабый» валидатор, то ответ НЕ ДОЛЖЕН содержать другие заголовки сущности; это предотвращает несоответствие между закэшированными телами сущностей и обновлёнными заголовками. В противном случае ответ ДОЛЖЕН содержать все заголовки сущностей, которые вернули статус 200 (OK) на тот же запрос.

Кэш НЕ ДОЛЖЕН объединять ответ 206 с другими ранее закэшированными данными, если поле ETag или Last-Modified в точности не совпадают (подробнее в секции 16.5.4)

Кэш, который не поддерживает заголовки Range и Content-Range НЕ ДОЛЖЕН кэшировать ответы 206 (Partial).

300 — (Multiple Choices — Несколько вариантов)

По указанному URI существует несколько вариантов предоставления ресурса по типу MIME, по языку или по другим характеристикам. Сервер передаёт с сообщением список альтернатив, давая возможность сделать выбор клиенту автоматически или пользователю.

Если это не запрос HEAD, ответ ДОЛЖЕН включать объект, содержащий список характеристик и адресов, из которого пользователь или агент пользователя может выбрать один наиболее подходящий. Формат объекта определяется по типу данных приведённых в Content-Type поля заголовка. В зависимости от формата и возможностей агента пользователя, выбор наиболее подходящего варианта может выполняться автоматически. Однако эта спецификация не определяет никакого стандарта для автоматического выбора.

Если у сервера есть предпочтительный выбор представления, он ДОЛЖЕН включить конкретный URI для этого представления в поле Location; агент пользователя МОЖЕТ использовать заголовок Location для автоматического перенаправления к предложенному ресурсу. Этот запрос может быть закэширован, если явно не было указано иного.

301 (Moved Permanently — Перемещено навсегда)

Код перенаправления. Указывает, что модель ресурсов REST API была сильно изменена и теперь имеет новый URL. Rest API должен указать новый URI в заголовке ответа Location, и все будущие запросы должны быть направлены на указанный URI.

Вы вряд ли будете использовать этот код ответа в своем API, так как вы всегда можете использовать версию API для нового API, сохраняя при этом старый.

302 (Found — Найдено)

Является распространенным способом выполнить перенаправление на другой URL. HTTP-ответ с этим кодом должен дополнительно предоставит URL-адрес куда перенаправлять в поле заголовка Location. Агенту пользователя (например, браузеру) предлагается в ответе с этим кодом сделать второй запрос на новый URL.

Многие браузеры реализовали этот код таким образом, что нарушили стандарт. Они начали изменять Тип исходного запроса, например с POST на GET. Коды состояния 303 и 307 были добавлены для серверов, которые хотят однозначно определить, какая реакция ожидается от клиента.

303 (See Other — Смотрите другое)

Ответ 303 указывает, что ресурс контроллера завершил свою работу, но вместо отправки нежелательного тела ответа он отправляет клиенту URI ресурса. Это может быть URI временного сообщения о состоянии ресурса или URI для уже существующего постоянного ресурса.

Код состояния 303 позволяет REST API указать ссылку на ресурс, не заставляя клиента загружать ответ. Вместо этого клиент может отправить GET запрос на URL указанный в заголовке Location.

Ответ 303 не должен кэшироваться, но ответ на второй (перенаправленный) запрос может быть кэшируемым.

304 * (Not Modified — Не изменен)

Этот код состояния похож на 204 (Нет контента), так как тело ответа должно быть пустым. Ключевое различие состоит в том, что 204 используется, когда нет ничего для отправки в теле, тогда как 304 используется, когда ресурс не был изменен с версии, указанной заголовками запроса If-Modified-Since или If-None-Match.

В таком случае нет необходимости повторно передавать ресурс, так как у клиента все еще есть ранее загруженная копия.

Все это экономит ресурсы клиента и сервера, так как только заголовки должны быть отправлены и приняты, и серверу нет необходимости генерировать контент снова, а клиенту его получать.

305 — (Use Proxy — Используйте прокси)

Доступ к запрошенному ресурсу ДОЛЖЕН быть осуществлен через прокси-сервер, указанный в поле Location. Поле Location предоставляет URI прокси. Ожидается, что получатель повторит этот запрос с помощью прокси. Ответ 305 может генерироваться ТОЛЬКО серверами-источниками.

Заметьте: в спецификации RFC 2068 однозначно не сказано, что ответ 305 предназначен для перенаправления единственного запроса, и что он должен генерироваться только сервером-источником. Упущение этих ограничений вызвало ряд значительных последствий для безопасности.

Многие HTTP клиенты (такие, как Mozilla и Internet Explorer) обрабатывают этот статус некорректно прежде всего из соображений безопасности.

307 (Temporary Redirect — Временный редирект)

Ответ 307 указывает, что rest API не будет обрабатывать запрос клиента. Вместо этого клиент должен повторно отправить запрос на URL, указанный в заголовке Location. Однако в будущих запросах клиент по-прежнему должен использоваться исходный URL.

Rest API может использовать этот код состояния для назначения временного URL запрашиваемому ресурсу.

Если метод запроса не HEAD, тело ответа должно содержать короткую заметку с гиперссылкой на новый URL. Если код 307 был получен в ответ на запрос, отличный от GET или HEAD, Клиент не должен автоматически перенаправлять запрос, если он не может быть подтвержден Клиентом, так как это может изменить условия, при которых был создан запрос.

308 — (Permanent Redirect — Постоянное перенаправление) (experimental)

Нужно повторить запрос на другой адрес без изменения применяемого метода.

Этот и все последующие запросы нужно повторить на другой URI. 307 и 308 (как предложено) Схож в поведении с 302 и 301, но не требуют замены HTTP метода. Таким образом, например, отправку формы на «постоянно перенаправленный» ресурс можно продолжать без проблем.

400 * (Bad Request — Плохой запрос)

Это общий статус ошибки на стороне Клиента. Используется, когда никакой другой код ошибки 4xx не уместен. Ошибки могут быть как неправильный синтаксис запроса, неверные параметры запроса, запросы вводящие в заблуждение или маршрутизатор и т.д.

Клиент не должен повторять точно такой же запрос.

401 * (Unauthorized — Неавторизован)

401 сообщение об ошибке указывает, что клиент пытается работать с закрытым ресурсом без предоставления данных авторизации. Возможно, он предоставил неправильные учетные данные или вообще ничего. Ответ должен включать поле заголовка WWW-Authenticate, содержащего описание проблемы.

Клиент может повторить запрос указав в заголовке подходящее поле авторизации. Если это уже было сделано, то в ответе 401 будет указано, что авторизация для указанных учетных данных не работает. Если в ответе 401 содержится та же проблема, что и в предыдущем ответе, и Клиент уже предпринял хотя бы одну попытку проверки подлинности, то пользователю Клиента следует представить данные полученные в ответе, владельцу сайта, так как они могут помочь в диагностике проблемы.

402 — (Payment Required — Требуется оплата)

Этот код зарезервирован для использования в будущем.

Предполагается использовать в будущем. В настоящий момент не используется. Этот код предусмотрен для платных пользовательских сервисов, а не для хостинговых компаний. Имеется в виду, что эта ошибка не будет выдана хостинговым провайдером в случае просроченной оплаты его услуг. Зарезервирован, начиная с HTTP/1.1.

403 * (Forbidden — Запрещено)

Ошибка 403 указывает, что rest API отказывается выполнять запрос клиента, т.е. Клиент не имеет необходимых разрешений для доступа. Ответ 403 не является случаем, когда нужна авторизация (для ошибки авторизации используется код 401).

Попытка аутентификация не поможет, и повторные запросы не имеют смысла.

404 * (Not Found — Не найдено)

Указывает, что rest API не может сопоставить URL клиента с ресурсом, но этот URL может быть доступен в будущем. Последующие запросы клиента допустимы.

404 не указывает, является ли состояние временным или постоянным. Для указания постоянного состояния используется код 410 (Gone — Пропал). 410 использоваться, если сервер знает, что старый ресурс постоянно недоступен и более не имеет адреса.

405 (Method Not Allowed — Метод не разрешен)

API выдает ошибку 405, когда клиент пытался использовать HTTP метод, который недопустим для ресурса. Например, указан метод PUT, но такого метода у ресурса нет.

Ответ 405 должен включать Заголовок Allow, в котором перечислены поддерживаемые HTTP методы, например, Allow: GET, POST.

406 (Not Acceptable — Неприемлемый)

API не может генерировать предпочитаемые клиентом типы данных, которые указаны в заголовке запроса Accept. Например, запрос клиента на данные в формате application/xml получит ответ 406, если API умеет отдавать данные только в формате application/json.

В таких случаях Клиент должен решить проблему данных у себя и только потом отправлять запросы повторно.

407 — (Proxy Authentication Required — Требуется прокси-аутентификация)

Ответ аналогичен коду 401, за исключением того, что аутентификация производится для прокси-сервера. Механизм аналогичен идентификации на исходном сервере.

Пользователь должен сначала авторизоваться через прокси. Прокси-сервер должен вернуть Proxy-Authenticate заголовок, содержащий запрос ресурса. Клиент может повторить запрос вместе с Proxy-Authenticate заголовком. Появился в HTTP/1.1.

408 — (Request Timeout — Таймаут запроса)

Время ожидания сервером передачи от клиента истекло. Клиент не предоставил запрос за то время, пока сервер был готов его принят. Клиент МОЖЕТ повторить запрос без изменений в любое время.

Например, такая ситуация может возникнуть при загрузке на сервер объёмного файла методом POST или PUT. В какой-то момент передачи источник данных перестал отвечать, например, из-за повреждения компакт-диска или потери связи с другим компьютером в локальной сети. Пока клиент ничего не передаёт, ожидая от него ответа, соединение с сервером держится. Через некоторое время сервер может закрыть соединение со своей стороны, чтобы дать возможность другим клиентам сделать запрос.

409 * (Conflict — Конфликт)

Запрос нельзя обработать из-за конфликта в текущем состоянии ресурса. Этот код разрешается использовать только в тех случаях, когда ожидается, что пользователь может самостоятельно разрешить этот конфликт и повторить запрос. В тело ответа СЛЕДУЕТ включить достаточное количество информации для того, чтобы пользователь смог понять причину конфликта. В идеале ответ должен содержать такую информацию, которая поможет пользователю или его агенту исправить проблему. Однако это не всегда возможно и это не обязательно.

Как правило, конфликты происходят во время PUT-запроса. Например, во время использования версионирования, если сущность, к которой обращаются методом PUT, содержит изменения, конфликтующие с теми, что были сделаны ранее третьей стороной, серверу следует использовать ответ 409, чтобы дать понять пользователю, что этот запрос нельзя завершить. В этом случае в ответной сущности должен содержаться список изменений между двумя версиями в формате, который указан в поле заголовка Content-Type.

410 — (Gone — Исчез)

Такой ответ сервер посылает, если ресурс раньше был по указанному URL, но был удалён и теперь недоступен. Серверу в этом случае неизвестно и местоположение альтернативного документа, например, копии. Если у сервера есть подозрение, что документ в ближайшее время может быть восстановлен, то лучше клиенту передать код 404. Появился в HTTP/1.1.

411 — (Length Required — Требуется длина)

Для указанного ресурса клиент должен указать Content-Length в заголовке запроса. Без указания этого поля не стоит делать повторную попытку запроса к серверу по данному URI. Такой ответ естественен для запросов типа POST и PUT. Например, если по указанному URI производится загрузка файлов, а на сервере стоит ограничение на их объём. Тогда разумней будет проверить в самом начале заголовок Content-Length и сразу отказать в загрузке, чем провоцировать бессмысленную нагрузку, разрывая соединение, когда клиент действительно пришлёт слишком объёмное сообщение.

412 — (Precondition Failed — Предварительное условие не выполнено)

Возвращается, если ни одно из условных полей заголовка запроса не было выполнено.

Когда клиент указывает rest API выполнять запрос только при выполнении определенных условий, а API не может выполнить запрос при таких условиях, то возвращается ответ 412.

Этот код ответа позволяет клиенту записывать предварительные условия в метаинформации текущего ресурса, таким образом, предотвращая применение запрошенного метода к ресурсу, кроме того, что ожидается.

413 — (Request Entity Too Large — Сущность запроса слишком большая)

Возвращается в случае, если сервер отказывается обработать запрос по причине слишком большого размера тела запроса. Сервер может закрыть соединение, чтобы прекратить дальнейшую передачу запроса.

Если проблема временная, то рекомендуется в ответ сервера включить заголовок Retry-After с указанием времени, по истечении которого можно повторить аналогичный запрос.

414 — (Request-URI Too Long — Запрос-URI Слишком длинный)

Сервер не может обработать запрос из-за слишком длинного указанного URL. Эту редкую ошибку можно спровоцировать, например, когда клиент пытается передать длинные параметры через метод GET, а не POST, когда клиент попадает в «чёрную дыру» перенаправлений (например, когда префикс URI указывает на своё же окончание), или когда сервер подвергается атаке со стороны клиента, который пытается использовать дыры в безопасности, которые встречаются на серверах с фиксированной длиной буфера для чтения или обработки Request-URI.

415 (Unsupported Media Type — Неподдерживаемый медиа тип)

Сообщение об ошибке 415 указывает, что API не может обработать предоставленный клиентом Тип медиа, как указано в заголовке запроса Content-Type.

Например, запрос клиента содержит данные в формате application/xml, а API готов обработать только application/json. В этом случае клиент получит ответ 415.

Например, клиент загружает изображение как image/svg+xml, но сервер требует, чтобы изображения использовали другой формат.

428 — (Precondition Required — Требуется предварительное условие)

Код состояния 428 указывает, что исходный сервер требует, чтобы запрос был условным.

Его типичное использование — избежать проблемы «потерянного обновления», когда клиент ПОЛУЧАЕТ состояние ресурса, изменяет его и ОТПРАВЛЯЕТ обратно на сервер, когда тем временем третья сторона изменила состояние на сервере, что привело к конфликту. Требуя, чтобы запросы были условными, сервер может гарантировать, что клиенты работают с правильными копиями.

Ответы с этим кодом состояния ДОЛЖНЫ объяснять, как повторно отправить запрос.

429 — (Too Many Requests — Слишком много запросов)

Пользователь отправил слишком много запросов за заданный промежуток времени.

Представления ответа ДОЛЖНЫ включать подробности, объясняющие условие, и МОГУТ включать заголовок Retry-After, указывающий, как долго ждать, прежде чем делать новый запрос.

431 — (Request Header Fields Too Large — Слишком большие поля заголовка запроса)

Код состояния 431 указывает на то, что сервер не желает обрабатывать запрос, поскольку его поля заголовка слишком велики. Запрос МОЖЕТ быть отправлен повторно после уменьшения размера полей заголовка запроса.

Его можно использовать как в случае, когда совокупность полей заголовка запроса слишком велика, так и в случае неисправности одного поля заголовка. В последнем случае представление ответа ДОЛЖНО указывать, какое поле заголовка было слишком большим.

444 — (No Response — Нет ответа) (Nginx)

Код ответа Nginx. Сервер не вернул информацию и закрыл соединение. (полезно в качестве сдерживающего фактора для вредоносных программ)

451 — (Unavailable For Legal Reasons — Недоступен по юридическим причинам)

Доступ к ресурсу закрыт по юридическим причинам. Наиболее близким из существующих является код 403 Forbidden (сервер понял запрос, но отказывается его обработать). Однако в случае цензуры, особенно когда это требование к провайдерам заблокировать доступ к сайту, сервер никак не мог понять запроса — он его даже не получил. Совершенно точно подходит другой код: 305 Use Proxy. Однако такое использование этого кода может не понравиться цензорам. Было предложено несколько вариантов для нового кода, включая «112 Emergency. Censorship in action» и «460 Blocked by Repressive Regime»

500 * (Internal Server Error — Внутренняя ошибка сервера)

Общий ответ при ошибке в коде. Универсальное сообщение о внутренней ошибке сервера, когда никакое более определенное сообщение не подходит.

Большинство веб-платформ автоматически отвечают этим кодом состояния, когда при выполнении кода обработчика запроса возникла ошибка.

Ошибка 500 никогда не зависит от клиента, поэтому для клиента разумно повторить точно такой же запрос, и надеяться что в этот раз сервер отработает без ошибок.

501 (Not Implemented — Не реализован)

Серверу либо неизвестен метод запроса, или ему (серверу) не хватает возможностей выполнить запрос. Обычно это подразумевает будущую доступность (например, новая функция API веб-сервиса).

Если же метод серверу известен, но он не применим к данному ресурсу, то нужно вернуть ответ 405.

502 — (Bad Gateway — Плохой шлюз)

Сервер, выступая в роли шлюза или прокси-сервера, получил некорректный ответ от вышестоящего сервера, к которому он обратился. Появился в HTTP/1.0.

503 — (Service Unavailable — Служба недоступна)

Сервер не может обработать запрос из-за временной перегрузки или технических работ. Это временное состояние, из которого сервер выйдет через какое-то время. Если это время известно, то его МОЖНО передать в заголовке Retry-After.

504 — (Gateway Timeout — Таймаут шлюза)

Сервер, в роли шлюза или прокси-сервера, не дождался в рамках установленного таймаута ответа от вышестоящего сервера текущего запроса.

505 — (HTTP Version Not Supported — Версия HTTP не поддерживается)

Сервер не поддерживает или отказывается поддерживать указанную в запросе версию протокола HTTP.

510 — (Not Extended — Не расширен)

В запросе не соблюдена политика доступа к ресурсу. Сервер должен отправить обратно всю информацию, необходимую клиенту для отправки расширенного запроса. Указание того, как расширения информируют клиента, выходит за рамки данной спецификации.

Источники и более подробная информация:

  • https://restapitutorial.ru/httpstatuscodes.html
  • https://www.restapitutorial.com/httpstatuscodes.html
  • https://restfulapi.net/http-status-codes/
  • https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/428

Понравилась статья? Поделить с друзьями:
  • App module exe ошибка приложения
  • Api ошибка 200
  • App installation failed with error message ошибка 0x80073d02
  • App gallery ошибка входа
  • App home ps3 game ошибка 80028f14