How to specify error codes in Apiary Documentation? - apiblueprint

I want to specify the various exceptions/errors that have to be returned while making an API call. How do I achieve this with Apiary.

Kyle's response is indeed correct. I will just add that if you want to add little bit more semantics to this you can write the other possible responses like this:
## POST /users/resendVerification/{userId}
Resends the user's verification code to the email address on record.
+ Response 201
+ Response 403
Returned if the user does not have access to the requested account
+ Body
+ Response 404
Returned if a user was not found for the given userId
+ Body
Note: The + Body is needed (even though it is empty) to distinguish the description from a message-body.

I'm not aware of a specific syntax for error codes. In the past I've simply used bullet points. For example, this is my code for a re-request verification code API.
## POST /users/resendVerification/{userId}
Resends the user's verification code to the email address on record.</br>
• 403 is returned if the user does not have access to the requested account</br>
• 404 is returned if a user was not found for the given userId</br>
+ Response 201
Hope that helps.

Related

Difference between Laravel testing method assertRedirect($uri) and assertLocation($uri)?

I was reading Laravel document HTTP tests and a question occurred.
I can't tell the difference between assertLocation($uri) and assertRedirect($uri), since both are for redirecting to specific uri.
Anyone could help would be so much appreciated.
If we look functionality of both
assertLocation($uri) would assert that the current location header matches the given URI.
But assertRedirect($uri) would assert whether the response is redirecting to a given URI.
I agree with example given by #apokryfos,
only 3xx responses are considered to be redirect responses while a 201 is not a redirect so assertLocation will pass if the response is 201 with a specified location while assertRedirect will not pass for 201 responses.
If we look code wise,
The assertRedirect() function also calls assertLocation() internally but it also checks using PHPUnit::assertTrue() that the response is redirected, if not then it will send a message
'Response status code [201] is not a redirect status code.', where 201 specifies the status code of response.
Checkout the assertRedirect() from github repo of framework

How to use custom error settings for JWT middleware

I have followed the cook books guide to the letter, found here https://echo.labstack.com/cookbook/jwt
But when using the JWT middleware I am having some issues with adding custom error messages. Login works fine, even to the point of not giving details (username & password) that returns a 404.
But when the JWT is missing it returns a 400, I want it to also return a 404.
So in my research I found this, https://forum.labstack.com/t/custom-error-message-in-jwt-middleware/325/3 which lists the following middleware.ErrJWTMissing & middleware.ErrJWTInvalid But is very unclear on how to set these?
I have tried setting them as vars on the router file, like so
var (
ErrJWTInvalid = echo.NewHTTPError(http.StatusTeapot, "test 104")
ErrJWTMissing = echo.NewHTTPError(http.StatusTeapot, "test 103")
)
But the error that sill comes back to me is a 400 and not a 418 (as this is just a test). So what am I doing wrong?
You can change the HTTP code and message this way.
func init() {
middleware.ErrJWTMissing.Code = 401
middleware.ErrJWTMissing.Message = "Unauthorized"
}
First, a point on your statement that you want to return a 400 and also a 404 error - you cannot do this. You're sending one response from the server so it gets exactly one response code. You could send a 207, but we're not really talking about multiple resources here, so don't do that. In my opinion, a 400 error is indeed the correct response for a missing JWT as that constitutes a bad request. A 404 "Not Found" means that the requested resource (the thing on the server side) could not be found. It does not mean that something in the request could not be found.
As for setting your custom error message, you're likely to be out of luck without altering the source code for Echo. That specific response is coming from within the middleware handlers of the package itself (you can see it here). This is mostly abstracted away from you, so without looking at the inner workings of the package, there would be no way to tell where this was coming from, and frankly there's not a lot that you can easily do about it. ErrJWTMissing is indeed the variable that the package uses internally for this error message, but Echo does not appear to provide an exported setter method for you to change this value, so you're stuck with what it is.
If you truly wanted to set a custom error method for this case I think your options would be to:
Write your own middleware to intercept the request before it was handled by Echo's middleware, where you could handle the request however you wanted.
Edit the Echo source to work how you wanted it to work -- specifically, all you would have to do is edit ErrJWTMissing.
Basically, Echo is trying to do you favors by handling all of this middleware processing for you, and it's a lot of work or hackery to un-do that work while still using Echo.

REST HTTP Status Code Best Practice for validation API

I am creating a simple API to validate a membership. Client will have to input a String ID and Server will check if the ID is a valid member of our, lets say, community. The ID must be numeric only, with length 10.
Quite simple right?
If the ID is a valid, of course we will return HTTP Status Code OK.
If the ID is contains alfabet, or less/more than 10, then we will return HTTP Status Code BAD REQUEST.
The question is, what is the best practive HTTP Status Code to return when the ID is numeric and length = 10, but is NOT a member of our community? and why is that.
The endpoints of a REST API are normally resources on which you act using HTTP methods like GET,PUT,POST,DELTE. When you do it like that, its much easier to decide which HTTP status to return.
So may be you could make an endpoint
/member/{id}
if a member with this id exists, return HTTP 200 and if you want some JSON with basic member info
if the id is valid, but no member exists, return HTTP 404 - NOT FOUND
if the id is not valid, length !=10 or contains invalid chars, return a HTTP 400 BAD REQUEST
Here you can find more about REST API design

Have Dynamical values for my parameters in the Request payload (POST x-www-form-urlencoded)

Is there a way (and does it make sense even) to have dynamical values for my request parameters (in my case POST application/x-www-form-urlencoded that has two parameters username and password) which can be altered based on some function or a returned value from the server from a previous request?
The motivation being that i have a register-new-user request which i run from time to time off apiary.io and unless i manually change the example value for the username i get a "use already exists" response instead of 201 i want (since this request was already run with the username in the example).
What i'd like to have instead is a value in the API documentation that will change on each execution of the API call (either using some random number there, or to be able to have it take a value returned from a previous request).
Is there anything you can suggest to solve my "user already exists" response for register-new-user API call?
Here is my current API documentation (the relevant part):
## Registration [/users.json]
The `/users.json` resource handles registration of new user
### Register a New Patient [POST]
Register a new patient action sends email and password and registers
the new user in case it doesn't already exist
+ Request (application/x-www-form-urlencoded)
+ Attributes (Test User)
+ Body
user[email]=username#example.com&user[password]=123456
+ Response 201 (application/json)
{
"id":500
}
# Data Structures
## Test User (object)
+ "user[email]" (string): "username#example.com" - user email
+ "user[password]" (string): "123456" - user password
Thanks in advance
You can partially simulate this in the Apiary mock server by passing a header in your call, for example:
Prefer: status=200
See https://help.apiary.io/tools/mock-server/#multiple-responses
In general the mock server is not yet flexible and programmable enough to fully do what you describe, for example conditionals, dynamic variables or random responses.
We are working on enhancing this. If you'd like you may comment here on your requirements:
https://github.com/apiaryio/api-blueprint/issues/58
Feel free to also ping us in Apiary (in-app chat) or on support#apiary.io.
Thanks

Custom http codes

Could I use custom HTTP codes?
I want to use these codes as response for AJAX requests.
Example:
220 - will be correspond to status that some item was created successfully
420 - will be correspond to status that some validations errors were occurred
Each response will be has json string.
You can define extension codes, but it only makes sense if you want to standardize something; in which case you need to write a spec, and get the status code registered (see http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p2-semantics-12.html#rfc.section.4.1).
If this is just between your server and your client, simply put the additional information into the response body and use a more generic status code.
That being said -- what you called "420" is already defined as "422 Unprocessable Entity".
Using your server side language of choice you can send headers to the browser with the relevant HTTP code and message.

Resources