Recently I have been updating my GO REST APIs into graphQl API's and I came across issue where I am unable to customise my status code with gqlgen.
Response I got
Headers
Status Code: 200 OK
{
data: null,
errors: [
{message: "Unauthorized access", path: ["..."]}
]
}
Expected Header
Status Code: 401 UNAUTHORISED
Any help would be really appreciating!
Assume you have a gqlgen resolver similar to this:
func (r *queryResolver) SecretItems(ctx context.Context, userID string,
password string) ([]SecretItems, error) {
// ...
if !isAuthorized(userID, password) {
return nil, errors.New("Unauthorized access")
}
// ...
}
then the described behavior is expected. Errors should be returned as part of
the response body.
GraphQL is transport agnostic. While it is often served over HTTP, it might be
served over other client-server Protocols as well. Handling errors in the
response body requires no assumptions about the protocol. Hence, you shouldn't
rely on HTTP status codes.
Handling errors in the response body has another advantage: Assume a request
contains multiple queries. Some of them succeed, some of them fail. Then the
response can contain the result of successful queries under data and errors
related to failed queries under errors.
References:
GraphQL website
Specification: Response
Hasura: GraphQL vs REST
Possible reason why you expected a 401 status code
The gqlgen docs on
authentication contain an example
where 401 status code is returned.
Why? This happens in a http handler used as middleware on the chi http server.
The 401 status code is not returned by a GraphQL resolver.
Related
So basically I need to use the update/revise Rest API to update the fields in the vTiger CRM.
But when I am using the rest API (link : https://help.vtiger.com/article/147111249-Rest-API-Manual) to update the fields, I am getting the error as "400 Unsupported operations: The request cannot be fulfilled due to bad syntax."
My api : endpoint/reviseelement=convert_into_json_string({id:5x369, potentialname:'demo2'})
Also apart from this, I had used the SQL query Rest API, to update the record in the modules, but it is also giving me the same error as: "400 Unsupported operations: The request cannot be fulfilled due to bad syntax."
My Api query : endpoint/query?query=UPDATE Potentials SET potentialname = 'demo2 where id = 5x369;
Also by using the webservice(https://community.vtiger.com/help/vtigercrm/developers/third-party-app-integration.html) rest api I am getting error like : "Permission to perform the operations is denied for id: ".
So how can I use the update api. Can anyone please help?
For web services API (https://community.vtiger.com/help/vtigercrm/developers/third-party-app-integration.html),
When you pass the payload data, make sure you're passing the x-www-form-urlencoded form of data.
Also, make sure you're passing 'element' argument with value like this:
{"id": "10x11471458", "leadsource": "Facebook"}.
if you're still facing this issue, you can share more details and I'll be happy to help you.
If you still need to do this the following should work.
Method: POST
End Point: /revise
Headers: "Authorization: Basic YOUR_TOKEN"
Body:
{
"element": {
"id":"5x369",
"potentialname": "demo2"
}
}
reference: https://www.vtiger.com/docs/rest-api-for-vtiger#/Revise
Problem
I get
Microsoft\Graph\Exception\GraphException: [0]: Received 403 for call
to
https://graph.microsoft.com/beta/me/chats/[id]#unq.gbl.spaces/members
I fail to understand why.
Research
permissions in Azure
how the exception appears in my queue
Additional information
Just to be clear: this same request with other users of our company is working, so it's not something that always fails. It might be worth noting that the permissions starting with Chat are from the beta version of the graph api. Also retrieving info about the user (ownUser getGivenName) is working for all users.
App scopes
The scopes defined in the application are:
openid
profile
offline_access
user.read
mailboxsettings.read
calendars.readwrite
Chat.ReadBasic
Chat.Read
Chat.ReadWrite
Response of the server
The response completely:
{
"error": {
"code": "Forbidden",
"message": "Forbidden",
"innerError": {
"date": "2021-05-04T12:05:41",
"request-id": "xxxxxxx-f7ea-4912-a23b-676002d0912d",
"client-request-id": "xxxxxxx-f7ea-4912-a23b-676002d0912d"
}
}
}
The response headers also don't reveal anything:
Also tried
I also tried re-visiting https://login.microsoftonline.com/common/adminconsent?client_id=[id] and give my (admin) consent, however this doesn't change anything.
JWT token
Also I decoded both a working users jwt token and a non-working one and they have the same scp (scopes) configured. Here is the diff
used endpoints
/me/chats
/me
/me/chats/$chatId/messages
/me/chats/$chatId/members
Just some observations and workarounds to help out others who come on this post through google:
Only the /me/chats/$chatId/members fails, without an apparant reason. It might be a mistake in in the beta implementation. Maybe it's better to use the $expand argument to see them to mitigate this problem.
for another subgroup of users retrieving all the chats with the endpoint /me/chats with the php sdk also fails with the recommended code
public function listChats(): array
{
$graph = $this->getGraph();
$chats = [];
$response = $graph->setApiVersion("beta")
->createCollectionRequest("GET", "/me/chats")
->setReturnType(Chat::class);
while (!$response->isEnd()) {
$chats = array_merge($chats, $response->getPage());
}
return $chats;
}
because the while loop never stops. #odata.nextLink is always present in the response for these users. Probably also a bug as by design the sdk checks if it's present.
$maxRequests = 10;
while (!$response->isEnd() && $maxRequests > 0) {
$chats = array_merge($chats, $response->getPage());
$maxRequests--;
}
I'm using laravel 5.7 to build an API REST.
When I add the verified middleware to my route group and I try to login with an unverified user by my client api, I get the error 400 Bad request. This error is too generic and don't show the problem clearly for my customer (it's happens in a login form).
If I to edit the render() method in Handler.php to ignore the isApiCall() and return parent::render($request, $e);, so I get the full error (Your email address is not verified, status 403), but when I try to return this in a json object with response()->json([$e]), the response is always empty.
So how to handle properly the api errors to be return the full message from exception, in this case?
You probably have already solved this problem, but this solution might help someone else:
The reason why your response was returning an empty array is because you were passing an Exception type object into the json function that is expecting an array. The response should look like this:
return response()->json(['message' => $e->getMessage()]);
This will return a json response like:
{
"message": "Your email address is not verified"
}
I am using UseStatusCodePages Middleware to show status code pages on my application but it shows plain text on UI without any other information,
I want to show UI with Status Code Information along with some other helpful information like Customer Support Number with more user-friendly page.
I found out we can use two extension methods to do that which is UseStatusCodePagesWithRedirects and UseStatusCodePagesWithReExecute. Only Difference I found out from Microsoft Docs is,
UseStatusCodePagesWithRedirects : Send 302 to Client.
UseStatusCodePagesWithReExecute : Send Original Status Code and Executes handler for redirect URL.
Is that the only difference?
I think that the main difference is that UseStatusCodePagesWithRedirects is redirecting you to error controller action method while UseStatusCodePagesWithReExecute is just rendering page with out redirecting
Example
Controller actions
[Route("error/404")]
public IActionResult Error404(int code)
{
return View("Error404");
}
[Route("error/{code}")]
public IActionResult Error(int code)
{
return StatusCode(code);
}
Startup Cinfigue
app.UseStatusCodePagesWithRedirects("/error/{0}");
or
app.UseStatusCodePagesWithReExecute("/error/{0}");
Case 1 (404 Error)
Url : https://localhost:5001/notexits_page
1) UseStatusCodePagesWithRedirects
Result:
Url is: https://localhost:5001/error/404
We see Error404 page
2) UseStatusCodePagesWithReExecute
Result:
Url is: https://localhost:5001/notexits_page
We see Error404 page
Case2 (401 Error)
Url : https://localhost:5001/admin/users
1) UseStatusCodePagesWithRedirects
Result:
Url is: https://localhost:5001/error/401
We stack in infinity loop
1) UseStatusCodePagesWithRedirects
Result:
Url is: https://localhost:5001/admin/users
We see default browser error page for 401 error
When Using app.UseStatusCodePagesWithRedirects("/Error/{0}") and invalid request(lets say "/abc/xyz") is raised then;
Status Code 404 is issued, app.UseStatusCodePagesWithRedirects("/Error/{0}") intercepts the request and 302 status code is issued(which means URI of the requested resource has been changed temporarily)
As 302 is issued another get request is issued which results in change of the url from
"/abc/xyz" to "/Error/404".
As the request is redirected to the specific error controller the status code for the request is 200 ok in the browser developer tool.
But When Using app.UseStatusCodePagesWithReExecute("/Error/{0}") and invalid request(lets say "/abc/xyz") is raised then;
app.UseStatusCodePagesWithReExecute("/Error/{0}") middleware intercepts the 404 status code and re-executes the pipeline pointing it to the URL
As the middleware is re executing the pipeline the original URL "/abc/xyz" in the address bar is preserved. It does not change from "/abc/xyz" to "/Error/{0}".
Also the original status Code(404 in this case) is preserved in the developer tool.
Given have the following list of steps
Given path 'verify'
And header x-api-key = apiKey
And header tenant-id = tenantId
And request a_json_object_with_invalid_user_id_to_verify
When method put
Then status 404
When the endpoint returned HTTP 200 (which is a bug that i need to fix) but with an invalid json response such as
{
"score" :
}
This exception is thrown
com.jayway.jsonpath.InvalidJsonException: net.minidev.json.parser.ParseException: Unexpected character (}) at position 15.
at com.jayway.jsonpath.spi.json.JsonSmartJsonProvider.parse(JsonSmartJsonProvider.java:64)
at com.jayway.jsonpath.internal.JsonContext.parse(JsonContext.java:82)
at com.jayway.jsonpath.JsonPath.parse(JsonPath.java:596)
at com.intuit.karate.JsonUtils.toJsonDoc(JsonUtils.java:84)
at com.intuit.karate.StepDefs.method(StepDefs.java:344)
I expect to see the test failed because of wrong status code 200 received of the expected 404. I would like to know if throwing this exception is correct in karate?
Thanks.
I apologize for mis-reading your question.
There is indeed a bug in Karate when handling malformed JSON responses.
We have opened an issue, you should be able to get a patch version very soon: https://github.com/intuit/karate/issues/259