Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 36 ยท Web and API Testing

API testing with RequestsLibrary

Test REST APIs in Robot Framework with RequestsLibrary: sessions, GET and POST, status codes, JSON bodies and assertions, with a runnable fake-API stand-in.

Many bugs hide below the screen. Testing an HTTP API directly is faster and less flaky than clicking through a browser, and Robot Framework handles it well with RequestsLibrary, a wrapper around Python's requests package. Together with the built-in Collections library you can send requests, check status codes and inspect JSON.

No real server is reachable from this site, so the Robot code below is read-only. The runnable parts are Python stand-ins: a fake API function that behaves like a small service, plus helper functions that act like the keywords.

Install and a first request

Terminal
pip install robotframework-requests
TEXT
*** Settings ***
Library    RequestsLibrary
Library    Collections

*** Variables ***
${BASE}    https://api.example.test

*** Test Cases ***
Get A User
    ${response}=    GET    ${BASE}/users/1    expected_status=200
    Should Be Equal As Integers    ${response.status_code}    200
    ${body}=    Set Variable    ${response.json()}
    Should Be Equal    ${body}[name]    Ada Lovelace

GET is a keyword named after the HTTP method; there are POST, PUT, PATCH and DELETE too. It returns a response object with status_code, text, headers and a json() method. Writing expected_status=200 makes the keyword itself fail when the status differs (the default expects any status below 400). Use expected_status=anything when you want to examine an error response yourself.

${body}[name] is Robot's syntax for indexing a dictionary, which you met in variables.

Anatomy of an API test

Request Method, URL, headers, body.
Response Status, headers, body.
Assert Status first, then body.
Clean up Delete what you created.
1 / 2

Sessions

Repeating the base URL and headers in every call is noisy. Create a session once and reuse it:

TEXT
*** Test Cases ***
Create And Read A Todo
    ${headers}=    Create Dictionary    Authorization=Bearer ${TOKEN}
    Create Session    api    ${BASE}    headers=${headers}
    ${payload}=    Create Dictionary    title=Write tests    done=${False}
    ${created}=    POST On Session    api    /todos    json=${payload}    expected_status=201
    ${id}=         Set Variable    ${created.json()}[id]
    ${read}=       GET On Session    api    /todos/${id}
    Should Be Equal    ${read.json()}[title]    Write tests
    [Teardown]     DELETE On Session    api    /todos/${id}    expected_status=anything

POST On Session and GET On Session use the stored base URL and headers. Passing json=${payload} serializes the dictionary and sets the content type for you.

Never hard-code tokens in the suite. Pass them in with --variable TOKEN:... or read them from an environment variable (see CI), and keep them out of version control.

What to assert

Check in this order, from cheapest to most detailed:

  1. Status code: did the request work at all?
  2. Headers: Content-Type should be JSON, and Location should be set after a create.
  3. Body shape: the keys you rely on exist, with the right types.
  4. Body values: names, totals, counts.
  5. Side effects: a later GET shows the change.

Also test the sad paths. A missing token should give 401, an unknown id 404, a bad payload 400 or 422. These are the cases that manual testers skip and real clients hit.

A fake API to practice on

The stand-in below is a tiny in-memory service with GET and POST for /todos. The helper functions copy the keyword ideas: a request function returns a response, and assertion helpers raise on mismatch. It is deterministic and needs no network.

Python Stand-in: fake API and assertions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This is the right mix: one happy path (create then read) and three sad paths. In real Robot code each should_be_equal becomes Should Be Equal As Integers, and api(...) becomes a ... On Session keyword.

Validating JSON shape

Checking each field by hand gets tedious. Many suites validate the whole shape at once, for example with the JSONLibrary package, or with a small helper of their own. This stand-in checks that required keys exist and have the right types.

Python Stand-in: validate a JSON shape

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Keep API tests independent of each other. Create the data a test needs inside the test (or its setup), and delete it in the teardown, so tests can run in any order and in parallel.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does expected_status=201 do on a request keyword?

    It is an assertion built into the keyword.
  2. 2. Why create a session?

    A session saves the repeated settings so each call stays short.
  3. 3. Which sad path should an unauthenticated request usually produce?

    401 Unauthorized means credentials are missing or invalid.
  4. 4. In which order are assertions best written?

    Check the cheap and general things first so a failure message points at the real problem.

Summary

  • RequestsLibrary sends HTTP requests; keywords exist for each method.
  • Sessions hold the base URL and headers.
  • Assert status, headers, body shape, body values and side effects, in that order.
  • Test sad paths (401, 404, 422) as well as the happy path.
  • Keep tokens out of the suite and tests independent of each other.

Next: Template tests for data-driven testing