-
Notifications
You must be signed in to change notification settings - Fork 24
API Mock Tutorial: Applying Rules
Rules in sMockin are a great way to imitate real world behaviour in your HTTP mocks, by allowing you control the responses returned based on specific conditions.
In this section we will explore how to use Rules to simulate a simple login webservice.
-
Open http://localhost:8000/ in your browser.
-
Under the HTTP tab click the New HTTP Endpoint button
-
From the New HTTP Endpoint page:
- Enter /auth under the Path field
- Select POST under the Method field
- Ensure select HTTP Rules Based as the mock type on the right hand side
- Enter application/json into the Default Content Type field
- Enter 401 into the Default HTTP Status Code field
- Leave the reminaing fields blank
What we have done so far is to define a default response which the /auth mock will return whenever none of rules have not been matched.
-
Next, click the Add Rule button
-
In the New Rule window enter:
- application/json as the Content Type
- 200 as the HTTP Status Code
- { "token" : "15bcd1a0-187d-4d2d-ae18-1e836fd87648" } in the Response Body
- Leave the Response Headers empty.
This response is what will be returned when the rule we are about to create is matched.
-
Click the Add Rule Condition button
-
In the New Rule Condition window:
- Select Request Parameter in the Match On field
- Enter the value username in the field just below this
- Select Equals (TEXT) in the Comparator field
- Enter bob into the Match Value field
- Leave the Is Case Sensitive checkbox unchecked
- Lastly, click Add Arg button
-
Repeat this sequence of steps to add a 2nd condition:
- Select Request Parameter in the Match On field
- Enter the value password in the field just below this
- Select Equals (TEXT) in the Comparator field
- Enter letmein into the Match Value field
- Leave the Is Case Sensitive checkbox unchecked
- Click Add Arg button
-
Click the Done button to close the New Rule Condition window
-
Click the Add Rule button to close the New Rule window
-
Lastly click the Save button to create this mock.
Open a terminal window and run the following cURL commands:
- curl -i -H 'Content-Type: application/x-www-form-urlencoded' -d 'username=foo&password=foobar' -X POST http://localhost:8001/auth
This should return a 401 response.
- curl -i -H 'Content-Type: application/x-www-form-urlencoded' -d 'username=bob&password=letmein' -X POST http://localhost:8001/auth
This should return a 200 response with a token in the response body.