Restful API design Flashcards
What
Identify the Goal: What problem does the API solve? What resources will it manage?
Set Functionalities: List actions the API will support, like creating, reading, updating, or deleting resources.
Identify Resources
Resources represent the main entities in your API and are typically nouns.
Users
Orders
Products
Use Resource URIs
Design resource URLs that are hierarchical, predictable, and meaningful.
Use nouns to represent resources.
Use plural for resource names (e.g., /users instead of /user).
/users – Get all users or create a new user.
/users/{id} – Access a specific user by ID.
/users/{id}/orders – Access orders for a specific user.
Map to HTTP Methods
GET: Retrieve resources.
POST: Create new resources.
PUT: Update an existing resource (replace the whole).
PATCH: Partially update a resource.
DELETE: Remove a resource.
GET /users – Fetch all users.
POST /users – Create a new user.
PUT /users/{id} – Update user details.
DELETE /users/{id} – Delete a user.
Versioning Handling
API versions ensure backward compatibility when introducing changes
GET /v1/users
Error Codes
200 OK: Successful GET or PUT request.
201 Created: Resource successfully created.
204 No Content: Successful DELETE request.
400 Bad Request: Invalid input.
401 Unauthorized: Authentication failure.
404 Not Found: Resource not found.
500 Internal Server Error: Server failure.
Input Mechanisms For APIs
Query Params
Path Params
Request Body
HTTP Headers
Form Data
Cookies
Query Param
GET /users?name=John&age=30
Passed in the URL after ? and separated by &.
Used for filtering, pagination, and optional parameters.
Used with GET, DELETE etc
Path Parameters
Embedded in the URL path to specify a resource.
GET /users/{id}
Used with GET, PUT, DELETE
Request Body
Sends data in JSON, XML, or form format.
Used with POST, PUT, PATCH
POST /users
Content-Type: application/json
{
“name”: “John”,
“age”: 30
}
HTTP Headers
Passes metadata such as authentication tokens, content type, or custom headers.
GET /users
Authorization: Bearer <token>
Content-Type: application/json</token>
Form Data
Used for submitting forms (application/x-www-form-urlencoded or multipart/form-data).
Example (application/x-www-form-urlencoded
POST /submit-form
Content-Type: application/x-www-form-urlencoded
name=John&age=30
Example (multipart/form-data for file upload
POST /upload
Content-Type: multipart/form-data; boundary=—XYZ
—XYZ
Content-Disposition: form-data; name=”file”; filename=”image.jpg”
Content-Type: image/jpeg
[binary data]
Cookies
Used for authentication or session management.
GET /dashboard
Cookie: session_id=abcd1234
Request Body vs Form Data Input Type
Used when submitting HTML forms. Data is encoded as key-value pairs. Sent as part of the request body but encoded in a way that mimics query parameters.
Of 2 Types
application/x-www-form-urlencoded
Default for web forms (text data only). Data is URL-encoded (like query parameters).
POST /submit-form
Content-Type: application/x-www-form-urlencoded
name=John&age=30
multipart/form-data
Used for file uploads (binary data).
Each field is separated by a boundary.
POST /upload
Content-Type: multipart/form-data; boundary=—XYZ
—XYZ
Content-Disposition: form-data; name=”file”; filename=”image.jpg”
Content-Type: image/jpeg
[binary image data]
Request Body (application/json, application/xml, etc.)
Used when sending structured data (e.g., JSON, XML).
Data is sent as a raw payload.
Request Body vs Form Data Input Type - Server Handling
FORM DATA
POST /submit-form
Content-Type: application/x-www-form-urlencoded
name=John&age=30
@PostMapping(“/submit”)
public String handleForm(@RequestParam String name, @RequestParam int age) {
File Handling
@PostMapping(“/file”)
public String handleFileUpload(@RequestParam(“file”) MultipartFile file) {
return “Received File: “ + file.getOriginalFilename();
Request Body
POST /users
Content-Type: application/json
{
“name”: “John”,
“age”: 30
}
@PostMapping
public String handleJson(@RequestBody User user) {
return “Received JSON Data: Name - “ + user.getName() + “, Age - “ + user.getAge();
}
Browser Handling of Form Submission
Depending on the form’s method (GET or POST), the data is formatted accordingly.
<form>
The action attribute defines the target URL (/submit).
In case of GET - Data is appended to the URL as query parameters
In case of POST - Data is sent in the request body.
The server response replaces the current page.
If the response is an HTML page, it is rendered.
If the response is JSON, the browser may display raw JSON
If the server sends a redirect (302 Found), the browser automatically navigates to the new URL.
</form>
Browser handing of Form Submission - Ajax Interception
Instead of the default behavior, JavaScript can prevent the form from reloading the page and send data asynchronously.
This allows real-time form submission without reloading the page.
document.getElementById(“myForm”).addEventListener(“submit”, function(event) {
event.preventDefault(); // Prevents full page reload
let formData = new FormData(this); fetch('/submit', { method: 'POST', body: formData }).then(response => response.json()) .then(data => console.log(data)); });
Redirects Use Cases
Preventing Duplicate Submissions
After a user submits a form, a server may respond with a redirect to prevent accidental resubmission on refresh.
User submits a POST request (/submit-form).
Server processes the request and responds with
HTTP/1.1 302 Found
Location: /thank-you
Browser follows the redirect to /thank-you using GET.
f the user refreshes the page, only the GET request reloads (not the POST).
Redirect Method Type change
A redirect can change the HTTP method depending on the redirect status code used. Some redirects preserve the method (e.g., 307, 308), while others convert POST to GET (e.g., 302, 303).
Authorization Header
The Authorization header is used in HTTP requests to authenticate the client with the server. It contains credentials or tokens that allow the server to verify the client’s identity before granting access to resources.
General Format of the Authorization Header
Authorization: <type> <credentials></credentials></type>
<type> → Specifies the authentication scheme (e.g., Basic, Bearer, Digest)
<credentials> → Contains the encoded authentication information
</credentials></type>
Authorization Schemes
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
dXNlcm5hbWU6cGFzc3dvcmQ= is Base64(username:password).
Security Risk: Base64 is not encrypted, so it should only be used over HTTPS.
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9…
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9… is a JWT token.
Authorization: ApiKey my-secret-api-key
Digest Authentication -less common today
Server handling of Authorization
401 - Unauthorized
403 - If credentials are required
CORS
A CORS request happens when the client (frontend) is hosted on a different origin than the backend API.
Client on https://client.com makes a request to https://api.example.com.
GET /api/data HTTP/1.1
Origin: https://client.com
Host: api.example.com
Example from Frontend of makemytrip.com request is made to visa.com for payment
Host Header vs Origin Header
Host Header: Defines which server the request is sent to (used for routing requests).
Origin Header: Defines where the request is coming from (used for security policies in browsers).
GET /pay HTTP/1.1
Host: payservice.com
Origin: https://shop.com
Host: payservice.com → The server is payservice.com, so it receives the request.
Origin: https://shop.com → The browser checks CORS policy because the request comes from a different origin.
Without CORS, the browser blocks the response before the frontend can read it.