Api error 422

An HTTP 422: Unprocessable Entity error occurs when a request to the API can not be processed. This is a client-side error, meaning the problem is with the requ

An HTTP 422: Unprocessable Entity error occurs when a request to the API can not be processed. This is a client-side error, meaning the problem is with the request itself, and not the API.

If you are receiving an HTTP 422: Unprocessable Entity error, there are several possibilities for why it might be occurring:

  • You are sending in a payload that is not valid JSON
  • You are sending HTTP headers, such as Content-Type or Accept, which specify a value other than application/json
  • The request may be valid JSON, but there is something wrong with the content. For example, instructing the API to upgrade a cluster to a plan which does not exist.

Example

A call to the API that results in an HTTP 422: Unprocessable Entity error may look something like this:

{
  "errors": [
    "The Content-Type header specifies application/xml.",
    "The Accept header specifies a response format other than application/json.",
    "Your request could not be processed. "
  ],
  "status": 422
}

The  "status": 422 key indicates the HTTP 422: Unprocessable Entity error.

Troubleshooting

The first step in troubleshooting this error is to carefully inspect the response from the API. It will often provide valuable information about what went wrong with the request. For example, if there was a problem creating a cluster because a plan slug was not recognized, you might see something like this:

{
  "errors": [
    "Plan 'sandboxing' not found.",
    "Please use the /plans endpoint for a list of available plans.",
    "Your request could not be processed. "
  ],
  "status": 422
}

If all else fails, you can always contact support and we will be glad to assist.

Last updated on February 12, 2020

Selecting a proper HTTP Response Code makes REST API more descriptive. However, developers are lazy. While reviewing a REST API, I’ve seen a lot of cases, that the only response codes returned were HTTP 500 (aka “backend is not working”) and 400 (broadly known as “frontend messed up”). “Better” APIs were also returning 404 and authentication/authorization failure codes, but still, they should not be named as RESTFull. Such an approach is fast to implement and covers most of the use cases. But have you ever wonder, what will happen if developers have the possibility and time to experiment? They will delve into it.


This article has to make you pay attention to the quality of messages returned by your API, with the biggest focus on 422 Unprocessable Entity status codes. Selecting response codes carefully will make your API more descriptive and easier to use, reducing feedback loop time needed for root cause analysis.

The need for proper status

One day in my work, we were implementing some API, that was consuming JSON. Nothing special, but there was some logic behind two fields sent in a message payload.

curl for sample command invocation.

Generally, the time difference between dates could not be bigger than some period. Tests, that we wrote for this endpoint, were checking if HTTP 400 Bad Request was returned in case of the too broad time range. Looked solid, but during code review, we got a comment, if is this a good status code, as request syntax is perfectly valid, but semantics is here a problem. Well, that started a very long discussion.

Word on Client Error codes

In general, response codes classes start with very broad information. For Client Error codes it is HTTP 400 Bad request, originally meaning “request sent by client has a malformed syntax”, which was very strict about the reason behind this status. Later, in updating RFC 7231, the definition of 400 was defined less restrictive. Since 2014, it is just information about potential client problem, that sent an invalid request. Neither specific nor descriptive. Hopefully, there are a lot of other status codes, that could be used.

Looking on a list published on IANA or Mozilla Developer Center, we can see that they are more and more specific, from authorization issues, through invalid header values, to legal problems, so probably there is an error code that will fit our needs. In our case, we got a suggestion that 422 Unprocessable Entity could be used.

Doubts about 422

Request that we sent was perfectly fine in the matter of syntax, as the content type was understood by the server, and its body was successfully parsed. The problem was just in data that was provided within the body, which made our case a perfect situation for Unprocessable Entity status. Such a situation might happen for some reasons, e.g. because of logic behind command processing, like a requirement that selected period cannot be bigger than 60 days. That could be achieved by changing userRegisteredTo field value to out of the defined range.

In this case, requested command contained date range for over 60 days.

Even if requested command syntax was correct, data inside it was not. It can also happen in other scenarios, that check the quality of provided data, like in one below, where a user wants to set prices for shipping packages to some country but is trying to use the currency that cannot be used within it:

Imagine, that system that you are developing allows for paying in euro and some cryptocurrency in Germany, but not in United States dollars.

Even if our cases looked like a perfect match for 422 status code, we still had concerns regarding if it should be used. It is not a part of the standard HTTP protocol but is a part of its extension called WebDAV. WebDAV is used for managing resources, usually files, directories, and its properties. As we were not implementing anything related to WebDAV, it looked like an overhead. We were going to use only one response code defined in whole, over 120 pages documentation. We liked the response code, but we needed proof that we can use it.

So, why we decided to utilise it?

To get an argument for using code from extension to plain HTTP, we need to take a step back and check original documentation one more time. Fortunately, in a section that is describing status codes there is one, very important sentence for us:

HTTP status codes are extensible.

This opens a lot of doors for using available extensions. There is a huge benefit in using specific response codes, as it provides information about the root cause of the problem. Knowing what was wrong, API clients can perform retry, tell users to fix the data, or authorize again, depending on retrieved status. It could not be possible with returning general HTTP 400 Bad Request in response.

Can the response be more descriptive?

Take the benefit of various response code, and inform clients about the source of a problem. If no code will match your need, remember that HTTP statuses are extensible, so look for best one also within extensions, or as a last resort — create your own one. If that is not enough for your case, consider implementing Problem Details for your API. Problem details can give huge insight for a user that is using your API, e.g. when requested setting price for shipping in invalid currency, apart from status code, it could provide response body like:

{
    "type": "/errors/currency-is-not-supported-in-country",
    "title": "Requested currency cannot be used in this country.",
    "status": 422,
    "detail": "Germany supports only currencies: EUR, BTC",
    "instance": "/errors/currency-is-not-supported-in-country/7291562",
    "requestedCountry": "Germany",
    "requestedCurrency": "USD"
}

Format of response is standardized, if you are interested in it, please refer to the documentation.

Security consideration

Descriptive responses from your API may accidentally expose valuable information for attackers. You should not expose information about your infrastructure (webserver implementation, database version), or used language and its version. Make sure to never return any stack trace within your response body. All this information can allow malicious users to use exploits and break your application. You can also perform some additional steps to protect yourself, as not always returning detail is desirable behaviour.

Hiding some HTTP response codes can increase security

Photo by ÉMILE SÉGUIN 🇨🇦 on Unsplash

Hiding what should not be visible

One of the things, that can improve your API security, is hiding details from a user that do not have access to a resource. Let’s visualize it with resource providing business deal details under /api/contracts/32167. Who should be able to see those details? Probably only allowed users. Even more, probably not allowed users should even not know if such resource exists. Therefore, if an unauthorized user A would request for this contract details, it could get a response 404 Not Found (instead of 403 Forbidden), which will hide from him even existence of such agreement.

A similar situation should happen for a user that is not logged in. Instead of returning 403 Forbidden for protected resources and 404 Not Found for not existing ones, it might be valuable to return 401 Unauthorized for all non-public resources. Usually, users, who are not authorized, are not consumers of API, so they should not retrieve detailed reasons.

Design API responsibly

Meaningful responses are simplifying communication, leaving no room for guesses that may lead to long hours for analysing the root cause. Being strict and precise in HTTP responses will cause your API more discoverable and easier to use for your clients. Just make sure, that you will not tell them too much.

Featured photo by andreas160578 on pixabay.

Ошибка 422: решение

Код состояния 422 (HTTP 422 Unprocessable Entity) обозначает ошибку со стороны пользователя, а не API. Сервер понимает запрос со стороны клиента и может работать с типом содержимого, который ему предоставили. Однако логическая ошибка делает выполнение невозможным.

Например, документ XML построен синтаксически грамотно, но со стороны семантики в инструкции содержится погрешность.

  • вы отправляете полезные данные, которые недействительны в формате JSON;
  • вы отправляете заголовки HTTP, такие как Content-Type или Accept, которые указывают значение, отличное от application / json;
  • запрос может быть валиден по отношению к JSON, но что-то не так с содержимым. Например, указание API обновить кластер до несуществующего варианта;
  • в теле или запросе содержится лишний символ или пробел (в первую очередь стоит проверить пробелы перед заголовком) или напротив, не хватает кавычек/проставлен неправильный тип. Самая актуальная проблема при работе с JSON, при которой может перестать работать весь код.

Проблема ошибка 422 через Ajax Post с использованием Laravel

В ajax этот код может выдаваться как ошибка по умолчанию, когда проверка не выполняется. Либо возвращаться Laravel при запросе, в котором допущена опечатка. Можно попробовать сделать запрос в консоли браузера: он должен выдать JSON с ошибками, возникшими во время проверки запроса. Есть вероятность, что код просто отправляет атрибуты формы не так, как вы запланировали. В любом случае, проблему решать программисту или вебмастеру.

Дополнительная информация

К сожалению, дать универсальный совет по исправлению ошибки 422 Unprocessable Entity непросто. Путь разрешения может сильно отличаться для каждой частной ситуации.

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

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

Дальше по теме…

HTTP error 422 is not as common as other codes such as 404 or 500. This particular error can be hard to diagnose as it doesn’t provide you with much information about what part of your request is causing the problem.

Broadly speaking, if you see an HTTP 422 error it means the server understands your request, but it can’t fulfill it due to a problem on your end. If you fix that problem, you should be able to reload the page and the error will go away.

In this article, we’ll talk about what causes the 422 error and how to troubleshoot it if you’re using WordPress. Let’s get to it!

Check Out Our Video Guide to the 422 Error

What Is the HTTP 422 Error?

Error 422 is an HTTP code that tells you that the server can’t process your request, although it understands it. The full name of the error code is 422 “unprocessable entity.”

In a nutshell, the error means that you’re making a request the server understands, but it can’t process it. Typically, this happens because there’s a semantic error somewhere in the request, usually within a PHP or JavaScript file.

Unlike other HTTP errors, the 422 code will keep reappearing until you manage to troubleshoot the problem with your request. However, this can be difficult since the error doesn’t provide specific information about what part of the request it can’t process.

What Causes the HTTP 422 Error?

Typically, the HTTP 422 code pops up when there’s a semantic error in the contents of a request. If you’re using WordPress, that usually means one of two things:

  1. One of the files involved in the request contains code with semantic errors. To put it another way, there’s an error somewhere in the code.
  2. You’re dealing with a corrupt database table.

One problem with error 422 is that there’s no way of knowing what its cause is at first glance. This means you may need to try more than one troubleshooting method until you arrive at the problem.

HTTP error 422 may not be as common as other codes such as 404 or 500- but don’t worry! 😅This guide is here to help 🚀Click to Tweet

You can check the HTTP response code of any page using our HTTP header Checker tool.

How To Fix the 422 Error in WordPress (2 Methods)

In this section, we’ll show you how to repair a corrupted WordPress database and how to identify files with semantic code errors. These steps will also help you debug other issues, such as the HTTP 400 error.

1. Repair a Corrupted WordPress Database

In some cases, tables within the WordPress database might become corrupted during an update. This means that if you’re updating a plugin, theme, or WordPress itself and the process is interrupted, database entries can start presenting errors.

A corrupt database can lead to all sorts of errors within WordPress, such as pages not loading, features not working correctly, and HTTP codes such as 422. There are two ways to repair a corrupted WordPress database. The easiest approach is to use a plugin such as WP-DBManager:

WP-DBManager plugin

WP-DBManager

Once you activate WP-DBManager, you’ll get access to a new Database tab in the dashboard. Go to Database > Repair DB and select the tables that you want to repair. Since you may not know which table is corrupt, select them all and click on Repair:

Repair database tab

Find the Repair DB tab

The process should only take a few seconds and you’ll see a success message when it’s ready. Now, try accessing the page that returned the 422 error to see if it persists.

If you don’t have access to the WordPress admin due to the 422 error, you can repair the database manually. To do so, you’ll need to access the database from your hosting control panel.

If you use Kinsta, you can access the database from your MyKinsta dashboard. Select a website and go to the Info tab. Look for the Database access section, where you’ll find the login credentials for the database. Click on Open phpMyAdmin and enter those credentials:

Login to phpMyAdmin

phpMyAdmin

Select the database you want to repair from the menu to the left and you’ll see a breakdown of all the tables it contains to the right. Use the Check all option at the bottom of the page to select every table. Then, look for the Repair table option in the menu to the right:

Find the repair table option

Repair table option

Click on the Go button and wait for phpMyAdmin to return a success message. Now, go ahead and check if the HTTP 422 error persists.

2. Use the WordPress Error Logs To Identify HTTP 422 Code Causes

If repairing the database doesn’t make error 422 go away, the problem lies with one of the WordPress files. Since every WordPress installation contains dozens to hundreds of files, it’s not feasible to check all of them for semantic code errors.

Your best bet, in this scenario, is to enable the WordPress debug feature, which will give you access to error logs. To enable the WordPress debug mode manually, you’ll need to edit the wp-config.php file in the root directory.

You can do that by accessing your website via a File Transfer Protocol (FTP) client and locating the wp-config.php file. Open the file and add the following two lines of code before the line that says /* That’s all, stop editing! Happy blogging. */:

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );

If the WP_DEBUG line already exists, make sure that it reads true and simply add the second line of code (the WP_DEBUG_LOG entry). Save the changes to the file and reload the page that returns the 422 error.

The error should persist, but now you have access to error logs. To read those logs, navigate to the wp-content folder inside the root directory and look for the debug.log file. You can open the file using a text editor.

If the file is new, it should only contain a few lines, one of which should refer to the error that’s causing the 422 code. The error should point you towards a specific file that’s causing the problem. It should also include information about which line within the file contains a semantic error.

If you use Kinsta, you don’t have to enable the WordPress debug mode or error logs manually. Instead, go to MyKinsta, select a website, and jump to the Tools tab. Inside you’ll find an option for enabling WordPress debugging:

WordPress debugging in MyKinsta

WordPress debugging in MyKinsta

After enabling debugging, you can go to the Logs tab and select the error.log option. MyKinsta will display the latest errors on your website and the viewer includes a search feature to help you find specific entries:

MyKinsta will display errors

Errors will display in MyKinsta

Focusing on the latest entries should help you identify which file is causing the 422 error. Once you identify the file, you can try and fix the semantic error or replace it with a stock version from WordPress.

Learn what causes what 422 error and how to troubleshoot it if you’re using WordPress, all in this guide 😄Click to Tweet

Summary

Identifying what’s causing the HTTP 422 error can be somewhat complicated. However, troubleshooting the error doesn’t take all that long. The process is much simpler if you’re using WordPress, as the software comes with tools that can help you when it comes to debugging errors.

If you run into the HTTP 422 error in WordPress, there are two ways that you can fix it:

  1. Repair a corrupted WordPress database.
  2. Use the WordPress error logs to identify the causes of the 422 code.

With Kinsta, troubleshooting errors is much easier. Our MyKinsta dashboard includes built-in tools for debugging WordPress. If you don’t want to troubleshoot issues manually, you can always reach out to our support team!


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

The 422 Unprocessable Entity status-code does not appear in the base
HTTP specification. Like 102 and 207 it’s part of the WebDAV
specification, which is an extension to HTTP.

Unlike the other two, the 422 code has a good general use-case, and is
often used in Web API’s.

The 422 code implies that the server understood the general syntax of the
request, but the contents were incorrect. For example, a server might expect
POST requests that uses the application/json format. If the request is
broken JSON, it might be more appropriate to send back the 400 status code,
but if the request is valid JSON but the request doesn’t pass validation
(via for example json-schema) returning 422 might be better.

If there was something wrong with the request body, you can use the following
rules to figure out what to send back:

  • If the Content-Type was not supported, use 415.
  • Else: If the request was not parsable (broken JSON, XML), use
    400 Bad Request.
  • Else: If the request was parsable but the specific contents of the payload
    were wrong (due to validation or otherwise), use 422

Example

POST /new-article HTTP/1.1
Content-Type: application/json

{ "title": "Hello world!"}
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/problem+json

{
  "type" : "https://example/errors/missing-property",
  "status": 422,
  "title": "Missing property: body"
}

References

  • RFC4918, Section 11.2 — 422 Unprocesable Entity

Понравилась статья? Поделить с друзьями:
  • Apache error page custom
  • Api error 200 entry not found occurred
  • Api error 101 server not found occurred
  • Api development tools telegram error
  • Apache error log где найти