Lesson 5 / الدرس 5

Sending requests by hand / إرسال الطلبات يدويًا

Before you automate an API test you have to be able to send the request once and read the answer. A request tool is the API equivalent of exploratory testing, and it is where every API test you write should start.

قبل أتمتة اختبار واجهة لا بد أن تستطيع إرسال الطلب مرة وقراءة الجواب. وأداة الطلبات هي مكافئ الاختبار الاستكشافي عند الواجهات، ومنها ينبغي أن يبدأ كل اختبار واجهة تكتبه.

Postman, Insomnia, Bruno, the REST client built into most editors, or plain curl — they all do the same thing: let you compose a request, send it, and look at exactly what came back. The tool matters far less than the habit, which is to send it once by hand and read every line of the answer before you write a single assertion about it.

The four parts of a request

  1. The method and the URL. GET /orders/44 asks for something; POST /orders creates one. Sending the wrong method to the right URL is the commonest beginner mistake, and the answer is usually 405.
  2. Headers. Content-Type says what you are sending; Authorization says who you are. A 401 when you expected 200 is nearly always a missing or stale token.
  3. The body. Usually JSON. This is where your test data goes, and every value from the data lesson applies here too.
  4. The answer. Status, headers, body — read all three. The status alone is not the result.
// The same request, three ways. All of them send exactly this:
//
//   POST /sign-in HTTP/1.1
//   Content-Type: application/json
//
//   { "email": "sara@example.com", "password": "totallywrong" }

// curl, in a terminal:
//   curl -i -X POST https://api.example.com/sign-in \
//     -H 'Content-Type: application/json' \
//     -d '{"email":"sara@example.com","password":"totallywrong"}'

// In a request tool: method POST, that URL, the header in the Headers tab,
// the JSON in the Body tab. Same request, friendlier surface.

// -i on curl prints the status and headers too. Without it you see only the
// body, which is how people end up asserting on a 500 that looks like JSON.
The last comment is a real trap. A request tool shows you the status by default; curl without -i does not, and an error page that happens to be JSON looks exactly like a successful answer until you look at the number.

Explore first, assert second

Send the request that should work and read the whole answer. Then start breaking it: remove a required field, send a string where a number belongs, drop the Authorization header, ask for a record belonging to somebody else. Each of those is a test case you now know the real answer to — and knowing the real answer before you write the assertion is what stops you enshrining a bug.

Check yourself / اختبر نفسك

1. Why read the whole response before writing any assertion?

2. You run curl without -i and see JSON that looks fine. What might you be missing?

3. Why must a real API key never be saved into a collection committed to git?