Skip to content

Instantly share code, notes, and snippets.

@3bit-techs
Last active February 28, 2020 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 3bit-techs/5caf742c17df5e8e4aacd475cd1274c7 to your computer and use it in GitHub Desktop.
Save 3bit-techs/5caf742c17df5e8e4aacd475cd1274c7 to your computer and use it in GitHub Desktop.

How-to: API First

To develop and manage microservice APIs following the best practices and open standards, ensuring quality and security, we created this hands-on article demonstrating how we can use opensource tools and common techniques to make it possible to enable an 'API First' approach.

Tools

  • Kong as the API Gateway
  • Keycloak as the IAM solution
  • Postman for the creation of the integration tests
  • Newman for the execution of the integration tests

Requirements

Follow the requirements to run the examples demonstrated in this tutorial:

  • Docker installed
  • Postman installed
  • Curl installed
  • Linux Make installed

We will use the petstore-v3.0.yaml spec as our OpenApi contract.

Important: Note that we used Linux to run all commands, but it's completely possible to run on Windows using tools like gitbash or wsl.

Postman

After the installation, open the Postman console so we can start designing our API:

Postman console

Importing the OpenApi spec on Postman

It's possible to import an OpenApi spec directly on Postman:

  1. On Postman console, click on Import
  2. On the popup, tab Import File click on Choose files Import openapi on Postman
  3. Choose the file petstore-v3.0.yaml
  4. On the next screen click on Next to finish the import process Finish import Imported API

API Mocking with Prism

The best way to start explore our API using Postman and then write integration tests is to mock our API so we can easily simulate calls without a real backend implementation.

For that, we need to run a Docker container with Prism pointing to our OpenApi spec:

cd tutorial-apifirst
docker run --rm --name prism -d -p 4010:4010 -v "$(pwd)/petstore-v3.0.yaml":/etc/openapi/spec.file stoplight/prism:3 mock -h 0.0.0.0  "/etc/openapi/spec.file"
docker logs prism

If you succeeded to run the container, you should see an output similar to this one:

[CLI] …  awaiting  Starting Prism…
[HTTP SERVER] ℹ  info      Server listening at http://0.0.0.0:4010
[CLI] ●  note      GET        http://0.0.0.0:4010/pets
[CLI] ●  note      POST       http://0.0.0.0:4010/pets
[CLI] ●  note      GET        http://0.0.0.0:4010/pets/{petId}
[CLI] ▶  start     Prism is listening on http://0.0.0.0:4010

For this point is possible to invoke the tool curl to check if our API Mock is working:

curl http://localhost:4010/pets/1

The output should be:

{"id":-9223372036854776000,"name":"string","tag":"string"}

Exploring our API through Postman

With everything set up, we can explore our API using Postman.

Changing the API target URL to our Mock

We need to change the URL from our API on Postman to the local address of our Mock:

  1. On the navigation bar, right click on the collection Swagger Petstore and than click on Edit
  2. On the popup, click on tab Variables
  3. Replace the current value of the variable baseUrl with the address: http://localhost:4010
  4. Click in Update to confirm the changes

Changing baseUrl

First exploratory test

  1. On the navigation sidebar, choose one of the available requests under the collection Swagger Petstore on the folder pets, like List all pets for example.
  2. Change the parameter limit to 1
  3. Click on Send to execute the request
  4. Check the result on the tab Body

Exploring the API Mock through postman

First API Test

From the output generated by our Mock, we can create our first test to check if the returned output is what we really were expecting.

Prism returns always the same value for each Json data type, making it easy to preview and test this values.

Tip: It's possible to keep this same values for the Mocks generated for the microservice backend tests (Spring Boot for example), so the same API tests (created in Postman) can be reused to make integration tests with the real API microservice implementation.

Steps to create our first real test:

  1. On the request screen click on the tab Tests
  2. Paste the content below on the text field.
pm.test('expect response be 200', function () {
    pm.response.to.be.ok
});

pm.test('expect response json valid', function () {
    pm.expect(pm.response.json()).to.be.an('array').that.have.length(1)
    pm.expect(pm.response.json()[0]).to.include({'id':-9223372036854776000,'name':'string','tag':'string'})
})
  1. Click on Send to make the request and execute the tests
  2. Check the test results by clicking on the tab Test Results right under the test text field, on the response section.
  3. Click on Save (near to the Send button) to save the changes

Teste de API

On this test scenario, we validated the following conditions:

  1. Assert that the HTTP Status Code should be equal to ok (HTTP 200)
  2. Assert that our return is a valid JSON document
  3. Assert that the returned json is an array
  4. Assert that the number of itens on the array is 1
  5. Assert that the object on the position 0 of the array should be: {'id':-9223372036854776000,'name':'string','tag':'string'}

Exporting the collection

At this point we have:

  • The API Mock running
  • The API imported on Postman and configured to target our Mock
  • Some API tests executed against our Mock

We can now export this Postman collection so we can execute it via command line, giving us the hability to add this tests in a CI/CD Pipeline:

  1. On the navigation sidebar, right click on the collection Swagger Petstore and then click on Export
  2. Keep the default options
  3. Click on Export to confirm
  4. Save the collection under the same folder of this tutorial, with the name petstore-collection.json

Exporting the collection

Exporting the collection

Creating and exporting a Postman Environment

On postman, we have the concept of Environments, that are an abstraction to store configurations used by the collection during the execution and may change depending on the target environment.

We will create an Environment so we can export it together with the Collection, changing the variable baseUrl that we used in our collection targeting our Mock:

  1. On postman's workspace, on the right corner click on the icon Manage environments (gear tool icon)
  2. On the popup Manage environments, click on Add to add a new environment
  3. On the popup Add Environment, type the environment's name, on this tutorial we will use localhost
  4. Add the variable baseUrl with value http://localhost:4010 for the INITIAL VALUE field
  5. Click on Add to confirm the configuration
  6. On the popup Manage environments, click on the option Download Environment over the just created environment localhost
  7. Save the collection under the same folder, with the name localhost.postman_environment.json

Creating an Environment

Creating an Environment

Creating an Environment

Creating an Environment

Creating an Environment

Executing the collection via command line

In order to run the collection petstore-collection.json and execute our tests, we'll use a tool named Newman (command line runner for Postman):

docker run --net host --rm -v "$(pwd)/localhost.postman_environment.json:/etc/newman/env.json" -v "$(pwd)/petstore-collection.json":/etc/newman/collection.json -t postman/newman:alpine run -e env.json collection.json

If the command succeeded, the result output should be the following:

Tests via cmd with Newman

We have our API (spec openapi) designed, validated and with automated tests!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment