I am building my first RESTful API for practising and learning. I am using RAML and will realize it with MuleSofts AnypointStudio. I don't really know how to deal with responses, particularly, error responses. I managed to figure out which HTTP status codes I want for my responses but didn't manage to figure out how to handle the response messages.
Do I need to define response datatype and example message for every response code (200, 201, 204, 404 etc.)? If I can have one datatype and one example message, how do I do use them accordingly?
Currently, I have defined one error type and one example message.
Error.raml
#%RAML 1.0 DataType
type: object
description: This general error structure is used throughout this API.
properties:
code:
type: integer
minimum: 400
maximum: 599
description?:
type: string
default: "Bad query parameter [$size]: Invalid integer value [abc]"
example: The server understood the request, but is refusing to fulfill it
reasonPhrase?:
type: string
examples:
example: Bad Request
example1: Forbidden
example: !include ../examples/error_example.json
error_example.json
{
"code": 400,
"description": "Bad query parameter [$size]: Invalid integer value [abc]",
"reasonPhrase": "Bad Request"
}
As you can see, I have variables in both datatype and example message. They were generated by Restlet. I don't know how to utilise them yet so I just left them for the time being.
Would really appreciate any help and tips.
Do I need to define response datatype and example message for every response code (200, 201, 204, 404 etc.)? If I can have one datatype and one example message, how do I do use them accordingly?
No you don't. For a resource you could specify responses such as 200
or 404
(these are the most commonly used)
From the docs:
resourceTypes:
collection:
description: Collection of available songs in Jukebox
get:
description: Get a list of songs based on the song title.
responses:
200:
body:
application/json:
post:
description: |
Add a new song to Jukebox.
queryParameters:
access_token:
description: "The access token provided by the authentication application"
example: AABBCCDD
required: true
type: string
body:
application/json:
type: song
responses:
200:
body:
application/json:
example: |
{ "message": "The song has been properly entered" }
An example of a resource with a not found error:
collection-item:
description: Entity representing a <<resourcePathName|!singularize>>
get:
description: |
Get the <<resourcePathName|!singularize>>
with <<resourcePathName|!singularize>>Id =
{<<resourcePathName|!singularize>>Id}
responses:
200:
body:
application/json:
404:
body:
application/json:
example: |
{"message": "<<resourcePathName|!singularize>> not found" }
There's an excellent blog post about this. Have a look at RAML tutorials as they have nice docs. You could also have a look at Swagger for more "inspiration".