VHow do you design a REST API that stays backward compatible?
Pytanie rekruteraREST API
Rekruterzy używają pytań o REST, żeby sprawdzić, jak projektujesz interfejs, z którego inni programiści będą korzystać latami. Słuchają poprawnej semantyki HTTP, ale też zdrowego rozsądku: błędów, które pomagają klientowi, bezpiecznych ponowień i zmian, które nie psują działania istniejącym użytkownikom.
Odpowiadaj na jednym konkretnym zasobie, na przykład orders, i konsekwentnie z niego korzystaj. Przykład w rodzaju POST na slash orders łatwiej wypowiedzieć na głos i łatwiej za nim nadążyć niż za abstrakcyjną regułą. Przy każdej regule wspomnij o kompromisie, bo REST ma wiele przypadków typu „to zależy”.
- ✓Słowa → zwroty → zdania → mówienie
- ✓Sens odpowiedzi
- ✓Język
Częste pytania i przykładowe odpowiedzi
How do you design a REST API for a resource like orders, and when do you use PUT, PATCH and POST?
Jak zaprojektujesz REST API dla zasobu takiego jak zamówienia (orders) i kiedy używasz PUT, PATCH i POST?
Co chce usłyszeć rekruter. Rzeczowniki w adresach URL, metody HTTP o właściwym znaczeniu, bezstanowość (statelessness) oraz różnica między zastąpieniem a częściową aktualizacją.
Przykładowa odpowiedź po angielsku do ćwiczenia na głosI model the resource as a noun, so I have slash orders for the collection and slash orders slash 123 for one order. The HTTP method carries the action. GET reads. POST creates a new order, and I return 201 with a Location header. PUT replaces the whole order, so sending the same request twice gives the same result. PATCH changes only some fields. DELETE removes the order. The server stays stateless: each request carries everything needed, including the authentication token. For actions that do not fit a resource, like cancelling an order, I can use a sub-resource, and I stay consistent.
Which HTTP status codes do you use, and how do you return errors?
Jakich kodów statusu HTTP używasz i jak zwracasz błędy?
Co chce usłyszeć rekruter. Właściwe grupy i konkretne kody (201, 204, 400, 401, 403, 404, 409, 429) oraz jedno spójne ciało błędu.
Przykładowa odpowiedź po angielsku do ćwiczenia na głosI use the status code families on purpose. 2xx means success: 200 for a normal response, 201 for a created resource and 204 when there is nothing to return. 4xx means the client made a mistake: 400 for a bad request, 401 when the user is not authenticated, 403 when the user is known but not allowed, 404 when the resource is missing, 409 for a conflict, and 429 when the client sends too many requests. 5xx means our server failed. I return the same JSON error format everywhere: a code, a clear message and details for validation errors. I never show stack traces.
What is idempotency, and why does it matter for an API?
Czym jest idempotentność (idempotency) i dlaczego ma znaczenie dla API?
Co chce usłyszeć rekruter. Precyzyjna definicja, które metody są idempotentne i jak sprawić, by POST można było bezpiecznie ponawiać, na przykład kluczem idempotentności.
Przykładowa odpowiedź po angielsku do ćwiczenia na głosAn operation is idempotent when repeating it leaves the server in the same state as doing it once. GET, PUT and DELETE are idempotent by definition, while POST is not. This matters because networks fail. A client sends a payment request, gets a timeout and does not know if it worked. If it retries and the request is not idempotent, the customer may pay twice. For such cases I support an idempotency key: the client sends a unique key in a header, the server stores the key with the result, and a repeated request returns the saved result instead of doing the work again.
How do you implement pagination, and what is wrong with offset pagination?
Jak zaimplementujesz paginację i co jest nie tak z paginacją opartą na offsecie?
Co chce usłyszeć rekruter. Offset kontra kursor, koszt na dużych tabelach, spójność przy zmianie danych i maksymalny rozmiar strony.
Przykładowa odpowiedź po angielsku do ćwiczenia na głosThe simplest way is offset pagination: the client sends a limit and an offset. It is easy to use and allows jumping to a page. But it has two problems. On big tables, the database still has to skip all the earlier rows, so late pages become slow. And if rows are added or deleted while the client is reading, items can be skipped or repeated. For large or fast-changing data, I prefer cursor pagination. The client sends the cursor from the last item, usually based on a key such as the creation time and the ID, and the server returns the next items after it. In both cases I set a maximum page size.
How do you secure a REST API?
Jak zabezpieczasz REST API?
Co chce usłyszeć rekruter. HTTPS, uwierzytelnianie a autoryzacja, dostęp oparty na tokenach, na przykład OAuth 2.0, oraz sprawdzanie uprawnień dla każdego obiektu.
Przykładowa odpowiedź po angielsku do ćwiczenia na głosFirst, everything runs over HTTPS. For authentication, I usually use tokens. With OAuth 2.0, a client gets a short-lived access token, often a JWT, and sends it in the Authorization header. A refresh token can get a new one. For server-to-server calls, an API key can identify the caller, but it is not a replacement for user permissions. After authentication, I check authorisation on the server for every request, including whether this user may access this specific object. A missing check there is a common vulnerability. I also validate the input, apply rate limiting and avoid putting tokens in URLs, because URLs end up in logs.
Jak wymawiać kluczowe terminy
- REST
- rest (czytane jak słowo, nie litera po literze)
- idempotent
- aj-dem-POŁ-tent
- endpoint
- END-pojnt
- payload
- PEJ-lołd
- pagination
- pa-dżi-NEJ-szn
- OAuth
- OŁ-oth (th jak w „think”)
- JSON
- DŻEJ-son
Przydatne zwroty do odpowiedzi
- I would model this as a resource.Zamodeluję to jako zasób.
- The client can safely retry this request.Klient może bezpiecznie ponowić to żądanie.
- I would return a 409, because…Zwrócę 409, ponieważ…
- The response includes a link to the next page.Odpowiedź zawiera link do następnej strony.
- We keep the API backward compatible by…Zachowujemy wsteczną zgodność API dzięki…
- The trade-off is simplicity against flexibility.Kompromis to prostota kontra elastyczność.
- The server never trusts the client input.Serwer nigdy nie ufa danym od klienta.
Typowe błędy
- Umieszczanie czasowników w adresach URL, na przykład "getOrders" albo "deleteUser". Używaj rzeczowników dla zasobów, a akcję niech opisuje metoda HTTP. Możesz wspomnieć o rzadkim wyjątku dla akcji takich jak "cancel".
- Zwracanie 200 dla każdej odpowiedzi i umieszczanie błędu w ciele. Klienci, proxy i monitoring opierają się na kodzie statusu, więc używaj właściwego.
- Mylenie 401 i 403. 401 znaczy „nie wiem, kim jesteś”, a 403 znaczy „wiem, kim jesteś, ale nie możesz tego zrobić”.
- Mówienie, że PUT i POST to to samo. Wyjaśnij, że PUT zastępuje znany zasób i można go bezpiecznie powtarzać, a POST zwykle coś tworzy i nie jest idempotentny.
- Unikanie słowa "idempotent" albo wymawianie go za każdym razem inaczej. Po polsku mówi się „idempotentny”, więc łatwo przenieść polską wymowę. Powiedz je raz powoli: aj-dem-POŁ-tent. To słowo kluczowe tego tematu.
Najczęstsze pytania
Czy REST to to samo co API HTTP z JSON?
Nie do końca. REST to styl architektury z takimi ideami jak zasoby, bezstanowość i jednolity interfejs. Wiele „RESTowych” API realizuje tylko jego część i możesz to uczciwie powiedzieć: "we build resource-oriented HTTP APIs with JSON".
Jak mówić o wersjonowaniu API?
Powiedz, że starasz się unikać zmian łamiących zgodność: dodajesz pola zamiast je usuwać lub zmieniać ich nazwy. Gdy złamanie zgodności jest nieuniknione, wprowadzasz nową wersję, najczęściej w adresie URL lub w nagłówku, wspierasz starą przez uzgodniony okres i informujesz klientów z wyprzedzeniem.
Czy wspominać o OpenAPI lub Swagger?
Tak, jeśli ich używasz. Spisany kontrakt w OpenAPI pomaga zespołom uzgodnić interfejs przed kodowaniem, tworzy dokumentację i może pomagać generować kod klienta i testy. Powiedz, jak twój zespół utrzymywał zgodność kontraktu z kodem.
Przeczytać odpowiedź to nie to samo, co ją wypowiedzieć. Przećwicz każde pytanie na głos, a potem porównaj sens i język własnej odpowiedzi.
Wypróbuj SpeakRole ↗Inne tematy w tym obszarze