A comprehensive Python-based API test automation framework for the Restful Booker API using pytest and requests library.
This project demonstrates QA automation best practices for testing the Booking API endpoint:
- Endpoint:
POST https://restful-booker.herokuapp.com/booking - Framework: pytest
- HTTP Client: requests
- Python Version: 3.8+
booking/
βββ config/
β βββ __init__.py
β βββ config.py # Configuration settings and constants
βββ data/
β βββ __init__.py
β βββ test_data.py # Reusable test payloads and data sets
βββ utils/
β βββ __init__.py
β βββ api_client.py # API client and assertion helpers
βββ tests/
β βββ __init__.py
β βββ test_booking_api.py # Test cases
βββ pytest.ini # Pytest configuration
βββ requirements.txt # Python dependencies
βββ README.md # This file
cd /Users/gulcan/Desktop/booking
pip install -r requirements.txtpytest
pytest -v
pytest tests/test_booking_api.py -v
pytest tests/test_booking_api.py::TestBookingAPI::test_create_booking_with_valid_payload -v
pytest --cov=. --cov-report=html
pytest -k "test_create_multiple_bookings" -vThe test suite includes 11 comprehensive test cases with ~92% code coverage (see htmlcov/index.html for details):
- test_create_booking_with_valid_payload - Create booking and validate full response structure
- test_response_contains_booking_id - Verify
bookingidis present and valid - test_booking_details_match_request - Validate
firstname,lastname, andtotalpricematch request - test_booking_dates_validation - Verify check-in and check-out dates are correct
- test_deposit_paid_field - Verify
depositpaidfield behavior fortrue/false - test_create_multiple_bookings - Parameterized test using 3 data sets (counts as 3 parameterized cases)
- test_booking_with_special_characters - Test special characters in guest names (e.g., JosΓ©, GarcΓa-Smith)
- test_booking_with_zero_price - Test zero price bookings (
totalprice = 0) - test_booking_with_high_price - Test high price bookings (
totalprice = 999999)
- GET /booking/{id} and invalid ID handling - (suggested) verify retrieval and 404 behaviors
- Negative POST scenarios & schema validation - (suggested) missing required fields, invalid types, and JSON Schema validation
Note: The current repository implements the POST/create flow (main + edge cases). Adding auth, GET/PUT/DELETE flows and explicit JSON Schema checks will strengthen the framework; see the TODO section and CLAUDE_PROMPTS.md for planned items.
{
"firstname": "John",
"lastname": "Doe",
"totalprice": 1500,
"depositpaid": true,
"bookingdates": {
"checkin": "2024-01-28",
"checkout": "2024-02-04"
},
"additionalneeds": "Breakfast included"
}{
"bookingid": 1,
"booking": {
"firstname": "John",
"lastname": "Doe",
"totalprice": 1500,
"depositpaid": true,
"bookingdates": {
"checkin": "2024-01-28",
"checkout": "2024-02-04"
},
"additionalneeds": "Breakfast included"
}
}- Centralized configuration management
- API endpoints and URLs
- Request timeouts and headers
- Response validation rules
get_valid_booking_payload()- Returns standard booking payloadget_booking_payload_with_params()- Returns customized payloadTEST_DATA_SETS- Pre-defined test data for parameterized tests
APIClient Class
post()- Make POST requests with loggingget()- Make GET requests with logging
AssertionHelper Class
assert_status_code()- Validate response status codeassert_response_contains_keys()- Verify required keys existassert_booking_response_structure()- Validate full response structureassert_field_value()- Assert specific field values
β Clean Code Structure
- Organized folder layout (config, data, utils, tests)
- Single Responsibility Principle
- DRY (Don't Repeat Yourself)
β Reusable Components
- Generic API client for any endpoint
- Test data functions for easy payload generation
- Assertion helpers for common validations
β Comprehensive Logging
- Request/response logging
- Test execution flow visibility
- Debug information for troubleshooting
β Maintainability
- Clear function names and docstrings
- Parameterized tests for data-driven testing
- Configuration management for easy updates
β Best Practices
- PEP 8 code style
- Type hints where applicable
- Proper exception handling
- Pytest fixtures for setup/teardown
Edit config/config.py:
BASE_URL = "https://your-api-url.com"
Edit data/test_data.py:
def get_custom_payload(): return { "firstname": "Custom", "lastname": "User", "totalprice": 5000, "depositpaid": True, "bookingdates": { "checkin": "2024-03-01", "checkout": "2024-03-05" } }
In tests/test_booking_api.py:
def test_new_scenario(self): """Test description""" payload = get_valid_booking_payload() response = self.api_client.post(Config.BOOKING_ENDPOINT, payload) self.assertion_helper.assert_status_code(response) # Add your assertions
| Command | Description |
|---|---|
pytest |
Run all tests |
pytest -v |
Run tests with verbose output |
pytest -k test_name |
Run specific test by pattern |
pytest -x |
Stop on first failure |
pytest -s |
Show print statements and logging |
pytest --collect-only |
Show tests without running |
pytest --markers |
Show available markers |
- Verify internet connection
- Check if API endpoint is accessible
- Verify firewall settings
- Ensure you're running tests from project root
- Verify all init.py files exist in each package
- Run
pip install -r requirements.txtagain
- Check pytest.ini log_cli_level setting
- Use
pytest -sto show logging
For questions or issues:
- Check test logs in console output
- Review API response in assertion error messages
The repository includes a GitHub Actions workflow that runs the test suite and uploads coverage reports as artifacts. A few notes about auth-enabled (update/delete) tests:
-
Repository secrets: To enable tests that require admin credentials (update/delete), add the following repository secrets:
ADMIN_USERNAMEβ admin usernameADMIN_PASSWORDβ admin password
-
How to add secrets:
- Go to your repository on GitHub.
- Settings β Secrets and variables β Actions β New repository secret.
- Add
ADMIN_USERNAMEandADMIN_PASSWORDwith their values.
-
Behavior: The workflow exposes these secrets as environment variables during the
pyteststeps. If secrets are present, auth tests will run; if they are missing, those tests will be skipped in CI (or locally they will be skipped unless you set the env vars). -
Security: Never hard-code credentials in the repo. Use secrets only via GitHub Settings.
If you want, I can also add a small GitHub Actions job that validates secrets are present and fails early with a clear message when they're missing (useful for protected branches). Let me know if you want that. 3. Verify payload structure in test_data.py 4. Check API documentation for endpoint changes
Happy Testing! π