There are many ways of doing API testing, the most popular tools is Postman (JavaScript) and RestAssured (Java), in this post we going to use Python request library to test Deck of Cards API.

Let’s review the requirements and start automating API tests.

Requirements 

  • Execute the following operations in order:  
    • Shuffle – to establish a fresh “deck”
    • Using the deck created in  the previous step, create 2 piles of 3 cards each. 
    • Using the piles created in the previous step, list cards in each pile to validate they contain the 3 cards they were built with.

First we need to setup project. Here is the structure I use:

demo_project
- tests
-- api_test.py

We going to use pytest as a test runner and assertion library let’s add it to the project:

pip install pytest

Shuffle – to establish a fresh “deck” get one deck and assert that we getting Success 200 code in return

import requests

def test_shuffle_deck():
    response = requests.get('https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1')
    assert response.status_code is 200
    response_body = response.json()
    assert response_body['success'] is True

Now we can not only test for status code but also parse the results and assert expected results, here is how to do it:

import requests

def test_shuffle_deck():
    response = requests.get('https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1')
    assert response.status_code is 200    

    response_body = response.json()
    assert response_body['success'] is True

    deck_id = response_body['deck_id']
    assert len(deck_id) is 12
    assert response_body['shuffled'] is True
    assert response_body['remaining'] is 52

Using the deck created in  the previous step, create 2 piles of 3 cards each.

Since we already stored deck_id we can pass it to our next call, also we going to create two pile variables to hold piles information

response = requests.get('https://deckofcardsapi.com/api/deck/' + deck_id + '/draw/?count=3')
    response_body = response.json()
    cards = response_body['cards']
    pile_name_one = 'pile_one'
    pile_name_two = 'pile_two'

Now lets create 2 piles of cards

for card in cards:
    assert len(card['code']) is 2
    cards_response_one = requests.get(
            'https://deckofcardsapi.com/api/deck/' + deck_id + '/pile/' + pile_name_one + '/add/?cards=' + card['code'])
        assert cards_response_one.status_code is 200

response = requests.get('https://deckofcardsapi.com/api/deck/' + deck_id + '/draw/?count=3')
response_body = response.json()
for card in cards:
    assert len(card['code']) is 2
    cards_response_two = requests.get(
            'https://deckofcardsapi.com/api/deck/' + deck_id + '/pile/' + pile_name_two + '/add/?cards=' + card['code'])
        assert cards_response_two.status_code is 200

Using the piles created in the previous step, list cards in each pile to validate they contain the 3 cards they were built with. (to be continued)