QA Interview Hub · Knowledge base · Quizzes · Українська

API

Client-server and REST

Client and server: who is responsible for what

The client builds the request and shows the result; the server holds the business logic, checks permissions and alone talks to the database. The split serves security, single-place rules and independent client evolution. A bug is located by stage: what the client sent (Network), whether the request arrived (DNS, TLS, load balancer), what the server answered and the state afterwards. With asynchronous processing the final state is checked by a separate request.

API · Client-server and REST

The Transfer button spins and no money moves. Where is the cause: the UI, the network or the server?

A user taps "Transfer", the spinner keeps spinning, and no money has moved. In a complaint this reads as "it is broken", but between the button and the database there are several places where something can go wrong. A tester who knows this path can say within a minute at which stage the problem is, instead of "it does not work". This article is about who is responsible for what in the client-server pair and how that turns into locating a bug.

The roles and why they are separated. The client (a browser, a mobile app, Postman, another service) builds the request and shows the result. The server holds the business logic, checks permissions and talks to the database itself. The client never goes to the database directly, for three reasons:

  • Security. The user controls the browser and the phone. Database credentials that reach the client reach everyone.
  • Rules in one place. The transfer limit is checked by the server, not by copies of the logic in the web app, on iOS and on Android: then a rule cannot be "forgotten" in one of the clients.
  • Independent evolution. Old mobile app versions live for weeks, the server is updated in minutes. The API contract has to survive that. This is Fielding's first REST constraint: separation of client and server.

The path of a request from the button to the database

1 Clientmethod, URL, headers, request body 2 DNS, TCP, TLSdomain, connection, certificate 3 Load balancer / gatewaywhich instance got the request 4 Servertoken, validation, business logic 5 Databasetransaction: all or nothing
Figure 1. The request goes down, the response comes back the same way. A problem can sit at every step, and each looks different.

Each stage breaks in its own way, and the symptom tells where to look:

StageWhat can be wrongHow to notice
ClientA wrong request, or a wrong display of a correct responseNetwork tab: what was sent and what came back
DNS, TLSThe domain does not resolve, the certificate is expiredThe request never arrives: net::ERR_CERT_DATE_INVALID in the browser, "certificate has expired" in curl
Load balancerOne instance runs an old version, a backend is down502, 503, 504 or responses that "flip" between two behaviors
ServerWrong authorization, validation or business ruleThe request is right, the status or the body is not
Database, transactionHalf of the data is saved, a lock, a raceThe response is an error, but part of the changes is already saved: the next GET shows it

Example: the UI says "Insufficient funds" although there is money. The complaint: the account has 5000, a transfer of 1200 fails. The first thing a tester does is not open the code but open Network and see what the client actually sent:

POST /api/transfers HTTP/1.1
Authorization: Bearer eyJ…
Content-Type: application/json

{"fromAccount":"acc-1","toAccount":"acc-2","amount":1200}
HTTP/1.1 422 Unprocessable Content
Content-Type: application/json

{"code":"insufficient_funds","message":"Insufficient funds"}

How to read it. The request is right: the same accounts and the amount the user typed. So the frontend is not at fault, the message on the screen only shows what the server returned. The second step: ask for the balance separately, without the UI.

curl -s -H "Authorization: Bearer $TOKEN" $BASE/api/accounts/acc-1
{ "id": "acc-1", "balance": 5000 }

The account shows 5000, while the transfer check believes there are no funds. Hence the wording that goes to the developer: "the request is correct, GET /accounts/acc-1 returns 5000, POST /transfers returns 422 insufficient_funds: the server-side check uses a different balance value". The bug reaches the backend team at once, with a reproduction in two curl commands.

Two reports about the same bug

Typical

"The transfer fails in the UI"

It is unknown whether this is the frontend, the network or the server. The developer starts from scratch, and the bug may go to the wrong team.

Better

Request, response and a control GET

It shows that the client sent the right thing and the server answered wrongly. It reproduces with one curl, without the app.

Figure 2. The same bug, two reports. The second names the stage of the path where the data went wrong.

Limits of the model. The picture "a request arrives, a response returns" is simplified:

  • Not everything is synchronous. The server can answer 202 Accepted and run the transfer later while the client polls the status. Then a successful response does not mean the transfer is finished.
  • There are caches between client and server. A browser or CDN can return an earlier response, and the server never sees the request.
  • Several services can sit behind a gateway. The error the client sees sometimes came from a deeper service, and its text says nothing about which failure it was.
  • The client is not always the UI. Integrations, other services and autotests call the same endpoints, so the API has to be right on its own.

Common mistakes.

  • Starting from the code or server logs without looking at the request in Network: wasted time if the problem is on the client.
  • Treating the message on the screen as "the server's response": the frontend builds it and may rewrite the text.
  • Checking only the response and not the state after it: a business operation may have partly run.
  • Testing only through the UI: whatever the UI does not let you type stays unverified.

Check yourself

The request in Network is correct, the server returned 500, and the database has a half-created transfer. At which stage of the path do you look for the cause, and what does it say about the transaction?

Answer

At the server and database stage: the client sent a correct request. Half-saved data means several writes ran without a shared transaction, or the transaction was not rolled back after the error. A transaction should give "all or nothing".

After a deploy some requests behave in the new way and others in the old way, although you send them identically. Which link of the path is likely?

Answer

The load balancer: some requests reach an instance with the old version and some the new one. Repeating the same request several times and comparing responses (some services return the version in a header) helps confirm it.

In an interview. Junior: The client sends an HTTP request, the server checks authorization and data, runs the business logic, works with the database and returns a response with a status. The client never goes to the database directly. Middle/Senior: I go through the path stage by stage: what the client sent (Network), whether the request arrived (DNS, TLS, load balancer), what the server answered and what the state is afterwards. That way the bug reaches the right team with a curl reproduction. I add that a response is not always final: with asynchronous processing I check the final state with a separate request.

Three ideas that get asked in interviews

Interviews cover three ideas: the server checks everything itself, HTTP keeps no state between requests, and bugs are located in the Network tab. Client validation is bypassed by a direct request, so the API is tested separately. A token or cookie travels in every request, and tests must not depend on order. A wrong request points to the frontend, a right request with a wrong response to the backend.

API · Client-server and REST

The UI form rejects a negative amount. Does that mean the API rejects it too?

In the transfer form the amount field does not let you type a negative number, and the button stays disabled. A tester who checks only through the UI marks "passed". Then someone sends the same request with curl, the minus goes through, and money flows from the recipient to the sender. The three ideas below explain why this happens, and each answers an interview question: why API is tested separately from the UI.

1. HTTP is stateless. Every request is self-contained: by the protocol itself the server does not link it to the previous one, so everything needed (token, cookie, language, identifiers) travels in every request. Why it is designed this way: servers can be added and removed, and any of them answers any request because it does not depend on who sent what before. This is Fielding's second REST constraint. Two consequences for tests: a request can be replayed on its own if you have all the headers, and tests must not depend on the order they run in.

2. Client validation is convenience, server validation is security. A check in the form quickly tells the user about a mistake, but it runs in an environment controlled by whoever is using it. It is turned off in DevTools and bypassed by sending a request from Postman, curl or a script. So the server must validate everything as if the UI did not exist.

Where the check lives

Typical

Validation only in the UI

The form blocks the minus, but a direct request goes through. A negative amount, someone else's id and extra fields reach the database.

Better

Validation on the server (the UI only hints)

A wrong request is rejected with the same error no matter who sent it.

Figure 1. A UI check can be bypassed; security rests on the server one.

Example: the minus that never existed in the UI. An autotest supposedly "checks a negative amount" but goes through the form, where the field does not let you type it. The real check is a direct request:

curl -i -X POST $BASE/api/transfers \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"fromAccount":"acc-1","toAccount":"acc-2","amount":-500}'

The bad response, which is what catches the bug:

HTTP/1.1 201 Created
Content-Type: application/json

{"id":"tr-8841","amount":-500,"status":"completed"}

How to read it. The server created the transfer and marked it completed. The UI protected, the API did not. The expected response is a client error, 400 or 422 depending on the project's agreement, saying which field is wrong, with no record in the database. The same goes for someone else's id: if fromAccount belongs to another user, the server must refuse (403 or 404), although the UI never shows other people's accounts.

The same checks in Playwright, without a browser:

// token is set via extraHTTPHeaders in playwright.config
test('negative amount is rejected', async ({ request }) => {
  const res = await request.post('/api/transfers', {
    data: { fromAccount: 'acc-1', toAccount: 'acc-2', amount: -500 },
  });
  expect(res.status()).toBe(422);
  // and the state did not change: same balance
  const acc = await request.get('/api/accounts/acc-1');
  expect((await acc.json()).balance).toBe(5000);
});

3. Where to look for the bug. When something is wrong, the Network tab in DevTools separates three cases:

From Network to the team

Network: find the request The request is wrong→ frontend: what was sent, where Request ok, response wrong→ backend: what the server returned Response ok, screen wrong→ frontend: how it was displayed
Figure 2. Three conclusions from one tab: compare the request, the response and what the user sees.

This algorithm is quick because every conclusion can be checked by eye: Network shows both the request and the response. If the request replayed by hand (curl, Postman) returns the same, the bug is reproduced without the UI, and that is the strongest report.

Limits.

  • "Stateless" does not mean "no sessions". The server may keep a session, but the client must pass its identifier every time. The state did not vanish, it moved into a token, a cookie or a database.
  • Some bugs do not fit the three cases: races between two requests, caches, mismatches between client and server versions. Then Network is supplemented with server logs and request replays.
  • UI tests are not redundant: they check that the client builds the request correctly. But they do not replace API tests, which check the server.

Common mistakes.

  • Assuming a field limit in the form protects the API: the first direct request disproves it.
  • Tests that depend on execution order ("first create, then update"): one test's data becomes another's precondition, and a parallel or selective run breaks such tests. Each test prepares its own data.
  • Filing a bug against "backend" because of the message on the screen without looking at Network: the frontend may have built that text.
  • Pasting a token into a test for days: it has an expiry, and the test fails for a reason unrelated to the logic.

Check yourself

The UI test "zero amount is not accepted" is green. Why does it not prove that the API rejects zero, and what do you add?

Answer

The form could have disabled the button, so the request never went out: only the client validation was checked. Add a direct POST with amount: 0 and check the error status and that no record was created.

The request in Network is correct, the response has the right data, but the screen shows the old amount. Which team and what is the first check?

Answer

The frontend: the response is right, so the problem is in the display. First check whether a cached or stale component state is used, and what exactly is rendered from the response.

In an interview. Junior: HTTP is stateless, so authorization goes in every request. Server validation is mandatory because the client can be bypassed: that is the reason to test the API separately from the UI. Middle/Senior: I check negative amounts, other users' ids and extra fields with direct requests, not through the form. For a bug I open Network: a wrong request points to the frontend, a right request with a wrong response to the backend. I add that stateless does not cancel sessions: state is just carried by a token or cookie, so tests must not depend on request order.

REST and alternatives

REST is a set of Fielding's constraints (client-server, stateless, cacheable, uniform interface, layered system, code on demand), not a protocol. Most "REST APIs" implement only resources, methods and statuses. The alternatives (GraphQL, SOAP, gRPC, WebSocket) change how an error reaches the client: in GraphQL the errors in the body are checked, not just the HTTP status. The contract, validation, authorisation and error handling stay the same.

API · Client-server and REST

The project uses GraphQL, but your checks rest on status codes. Which of them still work?

On a new project the API is not REST but GraphQL. The test "unknown user" checks that the response is not 2xx and never fails, because the server answers 200 even on an execution error. To choose checks that make sense, you need to know what exactly is called REST, how the alternatives differ, and how that changes a test. It is also a typical interview question.

What REST is. REST was described by Roy Fielding in his 2000 dissertation as a set of constraints, not as a protocol or a standard. An API that follows them is called RESTful. In practice it looks like this: data are resources at URLs (/users/42), actions are set by HTTP methods (GET reads, POST creates, PUT and PATCH change, DELETE removes), the result is described by a status code, and the body is most often JSON. There are six constraints:

  • Client-server. Separation of concerns, as in the previous lesson.
  • Stateless. Each request contains everything needed to process it.
  • Cacheable. A response says whether it may be cached; this is how Cache-Control and ETag work.
  • Uniform interface. Resources have addresses, actions on them are the same (methods), messages describe themselves (content type, status), and a response may contain links to the next steps (hypermedia).
  • Layered system. A gateway, cache or proxy can sit between client and server, and the client does not notice.
  • Code on demand. The only optional one: the server may send code to run on the client.

In practice most "REST APIs" follow the middle of this list (resources, methods, codes) and barely use hypermedia. In the Richardson maturity model that is level 2 of four: level 0 is one endpoint for everything, level 1 separate resources, level 2 adds methods and statuses, level 3 hypermedia. A tester benefits from knowing this so as not to demand from an API something its contract never promised.

Alternatives and why they exist. Each solves a problem that hurts in REST:

ApproachWhat it isProblem it solvesWhat changes in tests
GraphQLOne endpoint, the client describes the fields it needsExtra data and many requests to different resourcesOften 200 even on an error (the newer GraphQL over HTTP specification recommends 4xx for request errors, but many servers don't follow it yet); check the errors array
SOAPXML messages, a strict WSDL contractA formal contract between enterprisesConformance to the XML schema; errors as a Fault element, often with 500
gRPCHTTP/2 and Protobuf, contract in .protoFast calls between servicesIts own status codes (NOT_FOUND, UNAVAILABLE), typed messages
WebSocketA persistent two-way connectionReal-time data: chat, quotesOrder and delivery of messages, reconnection

One error, two protocols

REST

GET /users/999999 returns 404 Not Found. The error is visible from the status alone.

GraphQL

POST /graphql returns 200 OK, and the body has data.user: null and an errors array.

Figure 1. The same "not found" looks different, so a status check works in only one of the cases.

Example: a check that never fails. The "unknown user" test carried over from a REST project:

test('unknown user', async ({ request }) => {
  const res = await request.post('/graphql', {
    data: { query: '{ user(id: "999999") { name } }' },
  });
  expect(res.ok()).toBeTruthy(); // green, but proves nothing
});
HTTP/1.1 200 OK
Content-Type: application/json

{"data":{"user":null},
 "errors":[{"message":"User not found","path":["user"],
            "extensions":{"code":"NOT_FOUND"}}]}

How to read it. The transport worked, so the HTTP status is 200, and the business error lies in the body. An "ok" check passes even when the request is broken. The fixed test looks at the body:

const body = await res.json();
expect(res.status()).toBe(200);
expect(body.data.user).toBeNull();
expect(body.errors?.[0].extensions.code).toBe('NOT_FOUND');

A code in extensions is more stable than a message text, which may be reworded. It is a convention of the particular server, not a requirement of the GraphQL specification, so the format is agreed with the team.

What stays the same. Whatever the style, the same things are checked: the contract (which fields and types), input validation, authorization (other people's data is unreachable), error handling and behavior on a repeat. What changes is how an error reaches the client, not the question of what should happen.

Limits and trade-offs.

  • REST constraints are a style, not a verifiable standard. Two "REST APIs" can differ a lot, so a tester compares behavior with the project's documentation, not with theory.
  • GraphQL still runs over HTTP, so authorization, limits and caching matter too, but caching POST is harder. A request with a partial failure can return both data and errors.
  • gRPC cannot be opened in a browser or checked with plain curl; you need Protobuf clients.

Common mistakes.

  • Checking only res.ok() in GraphQL: the test is green with any error in errors.
  • Calling any JSON over HTTP RESTful, even POST /doEverything: that is level 0.
  • Demanding hypermedia from an API that has no such contract.
  • Carrying the habit "404 means not found" into SOAP or gRPC: errors look different there.

Check yourself

A GraphQL request returned 200, and the body has data: { order: null } with no errors. Does it look like an error, and what do you check?

Answer

It can be fine: "no such order" is sometimes returned as null without an error. Compare with the project's contract: for an unknown id is null expected or an entry in errors, and write the assertion accordingly. The status 200 decides nothing here.

Why is it not right to describe "REST" as "an API that returns JSON"?

Answer

Because JSON is returned by GraphQL and any RPC style too. Signs of REST: resources at addresses, methods with defined semantics, status codes, stateless, cacheable. A single endpoint POST /api with JSON does not fit that description.

In an interview. Junior: REST is an API style where data are resources at URLs and actions are set by HTTP methods; it is stateless and usually works with JSON. Alternatives: GraphQL, SOAP, gRPC, WebSocket. Middle/Senior: REST is a set of Fielding's constraints, and most "REST APIs" implement only resources, methods and statuses. If the project uses GraphQL, I do not rely on the HTTP status but check errors in the body; in SOAP I compare the XML with the schema and the Fault; in WebSocket I check order and delivery. The principles are the same: contract, validation, authorization, errors.

Resources, collections and nesting: how to read a REST address

A REST address names a resource with a noun and the HTTP method sets the action. A collection is plural, an item is addressed by id, and nesting shows ownership, as in /users/42/orders. Filters, sorting and pagination go in the query. The address implies checks: a missing id gives 404, an empty collection 200 with [], and a nested address must not expose others' data. Naming style is checked against the contract.

API · Client-server and REST

One endpoint says /getUserOrders?id=42, another /users/42/orders. Which one is REST?

The documentation has two endpoints with a similar meaning: GET /getUserOrders?id=42 and GET /users/42/orders. Both work, and an interview asks you to assess the address. A REST API address is not random: you read from it what the resource is, whose collection it is and what the action is. The checks come from there too: what to expect for a non-existent id, whether a nested address opens someone else's data. This article is about how to read an address and what to verify from it.

The logic of the address. The path names a resource (a noun), and the HTTP method sets the action. A plural name is a collection, an address with an identifier is one item. Why: the method already says "what to do" (GET reads, DELETE removes), so a verb in the path duplicates it, and for clients and caches a resource gets one stable address that can be opened, cached and saved.

GET    /orders            list of orders
POST   /orders            create an order
GET    /orders/17         one order
PATCH  /orders/17         partial update
DELETE /orders/17         delete
GET    /users/42/orders   orders of user 42

Nesting (/users/42/orders) shows that an order belongs to a user. People usually do not go deeper than two levels: when an order has its own id, /orders/17 is enough. Filters, sorting and pagination are query parameters: /orders?status=paid&sort=-createdAt&page=2. The path identifies a resource, the query narrows or orders the selection. Actions that do not fit CRUD (cancel, confirm) are modeled as a state change (PATCH with a new status) or an action subresource: POST /orders/17/cancel. A verb in the path is an acceptable compromise as long as the action is called with POST, not GET: GET must be safe and change nothing.

Assessing an address

Typical

GET /getUserOrders?id=42

A verb in the name and the id in the query instead of the path. Every endpoint is named in its own way, so the next one cannot be guessed.

Better

GET /users/42/orders

Nouns, a plural collection, the owner in the path. This scheme lets you guess /users/42/orders/17.

Figure 1. Assessing an address: the resource and owner in the path, the action in the method.

Two situations that are easy to confuse. "There is nothing" can mean two different results, and bugs hide exactly here:

404 or 200 with an empty list

The resource does not exist

GET /orders/999999 and GET /users/999999/orders: there is no such order or user. Expect 404.

The collection is empty

GET /users/42/orders for a user who has no orders yet. Expect 200 and [].

Figure 2. A non-existent resource and an empty collection give different responses.

Example: a nested address that ignores the owner. Order 17 belongs to user 43. A test as user 42 requests it through "their own" address:

GET /api/users/42/orders/17 HTTP/1.1
Authorization: Bearer eyJ…  (token of user 42)

HTTP/1.1 200 OK
{"id":17,"userId":43,"total":1250,"status":"paid"}

How to read it. The response has userId: 43, the address says 42. The server checked that order 17 exists but did not compare its owner with the parent resource in the path (or with the token's owner). The user sees someone else's data: this is a broken object-level authorization. The right answer is 404 (do not reveal that the order exists) or 403. The autotest:

test('order of another user is not reachable', async ({ request }) => {
  // order 17 belongs to user 43, user 42 is asking
  for (const path of ['/api/users/42/orders/17', '/api/orders/17']) {
    const res = await request.get(path, {
      headers: { Authorization: 'Bearer ' + token42 },
    });
    expect([403, 404]).toContain(res.status());
  }
});

Both addresses are checked because protection is often added to one route only, and the other stays open.

What else a tester checks.

  • Consistency: one naming style (plural, case, hyphens) across all endpoints.
  • A trailing slash and letter case (/orders/, /Orders) behave the same on all endpoints: a redirect or a 404, but not different things.
  • Collection pagination: the default limit, the maximum limit, a page beyond the data.
  • An id in a wrong format (/orders/abc) gives 400 or 404, but not 500.
  • A filter with an unknown value (?status=unknown): an empty selection or a validation error, as the contract says.

Limits. "RESTful" is not a dogma. The action POST /orders/17/cancel breaks the pure scheme but is often clearer than the alternative, and a tester compares behavior with the contract, not with taste. Naming rules should follow the project's style: older APIs have singular names, camelCase or verbs, and changing addresses breaks clients. So such remarks go as a recommendation, not a bug, if the behavior matches the documentation.

Common mistakes.

  • Expecting 404 for an empty collection: then the client shows an error instead of "no orders yet".
  • Checking that a nested resource exists but not that it belongs to the parent: this gives access to other people's data through any id.
  • Testing only the "happy" address and not trying a wrong id format, extra segments or letter case.
  • Filing a naming style as a bug when it matches the documentation.

Check yourself

GET /users/42/orders returns 404 for a user with no orders. Why can this be a bug?

Answer

User 42 exists, their collection is just empty: expect 200 and []. A 404 tells the client the resource is missing, and the interface shows an error instead of an empty state. But if user 42 does not exist, 404 is right.

Why is it not enough, for /users/42/orders/17, to check that order 17 exists?

Answer

You also check that it belongs to user 42 and that the token belongs to 42. If the server looks only at the order id, changing the number in the address lets you read other people's orders.

In an interview. Junior: An address names the resource with a noun, a collection in the plural, an item by id, and the HTTP method sets the action. In /getUserOrders?id=42 there is a verb and the id in the query; GET /users/42/orders is better. Middle/Senior: From the address I derive checks: a non-existent id gives 404, an empty collection 200 with [], a nested address does not return other people's data, filters live in the query, the collection has pagination. I also remind that "RESTful" is not a dogma: a tester compares behavior with the contract, and naming style is only a recommendation.