In a recent article I looked at RESTful API Modeling Language (RAML). I provided an overview of what RAML is all about, how to write it and some of its uses.
This time, I’m going to look at some of the ways in which you can use RAML for testing. We’ll start by using RAML to validate responses from an API. Then we’ll look at an approach you could take to mock an API server, using a RAML file to create mock HTTP responses.
Validating API Responses
First, let’s define a simple RAML file for a fictional API. I’ve left out some routes, but it will be enough to demonstrate the principles.
#%RAML 0.8
title: Albums
version: v1
baseUri: http://localhost:8000
traits:
- secured:
description: Some requests require authentication
queryParameters:
accessToken:
displayName: Access Token
description: An access token is required for secure routes
required: true
- unsecured:
description: This is not secured
/account:
displayName: Account
get:
description: Get the currently authenticated user's account details.
is: [secured]
responses:
200:
body:
application/json:
schema: |
{ "$schema": "http://ift.tt/1g1kaF3",
"type": "object",
"description": "A user",
"properties": {
"id": {
"description": "Unique numeric ID for this user",
"type": "integer"
},
"username": {
"description": "The user's username",
"type": "string"
},
"email": {
"description": "The user's e-mail address",
"type": "string",
"format": "email"
},
"twitter": {
"description": "User's Twitter screen name (without the leading @)",
"type": "string",
"maxLength": 15
}
},
"required": [ "id", "username" ]
}
example: |
{
"id": 12345678,
"username": "joebloggs",
"email": "joebloggs@example.com",
"twitter": "joebloggs"
}
put:
description: Update the current user's account
/albums:
displayName: Albums
/{id}:
displayName: Album
uriParameters:
id:
description: Numeric ID which represents the album
/tracks:
displayName: Album Tracklisting
get:
responses:
200:
body:
application/json:
schema: |
{ "$schema": "http://json-schema.org/schema#",
"type": "array",
"description": "An array of tracks",
"items": {
"id": {
"description": "Unique numeric ID for this track",
"type": "integer"
},
"name": {
"description": "The name of the track",
"type": "string"
}
},
"required": [ "id", "name" ]
}
example: |
[
{
"id": 12345,
"name": "Dark & Long"
},
{
"id": 12346,
"name": "Mmm Skyscraper I Love You"
}
]
Notice we’ve defined a trait for secured routes, which expects an access token as a query parameter. We’ve defined a few available routes, and defined some JSON schemas to specify the format of the results. We’ve also included some example responses; these are what we’re going to use to generate mock responses.
Let’s create an application which we’ll use for both parts of this tutorial. You’ll find it on Github.
Continue reading %Testing APIs with RAML%
by Lukas White via SitePoint
No comments:
Post a Comment