API Essentials
Cheatsheet Content
### API Basics - **API (Application Programming Interface):** A set of defined rules that enable different applications to communicate with each other. It acts as an intermediary. - **REST (Representational State Transfer):** An architectural style for networked applications. Uses standard HTTP methods (GET, POST, PUT, DELETE). - **SOAP (Simple Object Access Protocol):** A protocol for exchanging structured information in the implementation of web services. Uses XML for message formatting. - **GraphQL:** A query language for APIs and a runtime for fulfilling those queries with your existing data. Allows clients to request exactly what they need. ### Common HTTP Methods (REST) - **GET:** Retrieve data from a specified resource. (Safe, Idempotent) - Example: `GET /users/1` - **POST:** Submit data to be processed to a specified resource. (Not safe, Not Idempotent) - Example: `POST /users` (with user data in body) - **PUT:** Update a specified resource or create it if it does not exist. (Not safe, Idempotent) - Example: `PUT /users/1` (with updated user data in body) - **DELETE:** Delete a specified resource. (Safe, Idempotent) - Example: `DELETE /users/1` - **PATCH:** Apply partial modifications to a resource. (Not safe, Not Idempotent) - Example: `PATCH /users/1` (with partial user data in body) ### HTTP Status Codes - **1xx Informational:** Request received, continuing process. - **2xx Success:** - `200 OK`: Request succeeded. - `201 Created`: Resource successfully created. - `204 No Content`: Request succeeded, but no content to send back. - **3xx Redirection:** Further action needs to be taken. - `301 Moved Permanently`. - `304 Not Modified`. - **4xx Client Error:** Request contains bad syntax or cannot be fulfilled. - `400 Bad Request`: Server could not understand the request. - `401 Unauthorized`: Authentication required/failed. - `403 Forbidden`: Server understood, but refuses to authorize. - `404 Not Found`: Resource not found on server. - `429 Too Many Requests`: User sent too many requests in a given time. - **5xx Server Error:** Server failed to fulfill an apparently valid request. - `500 Internal Server Error`: Generic error message. - `503 Service Unavailable`: Server is not ready to handle the request. ### Request & Response Structure - **Request:** - **URL/Endpoint:** `https://api.example.com/v1/resource/id` - **Method:** GET, POST, PUT, DELETE, PATCH - **Headers:** Key-value pairs for metadata (e.g., `Content-Type: application/json`, `Authorization: Bearer `) - **Body:** Data sent to the server (e.g., JSON for POST/PUT) ```json { "name": "John Doe", "email": "john.doe@example.com" } ``` - **Response:** - **Status Code:** (e.g., `200 OK`) - **Headers:** (e.g., `Content-Type: application/json`, `Date`) - **Body:** Data received from the server (e.g., JSON) ```json { "id": "abc123xyz", "name": "John Doe", "email": "john.doe@example.com" } ``` ### API Authentication - **API Keys:** A simple token, often passed in headers or query parameters. - `X-API-Key: your_api_key_here` - **Basic Authentication:** Send username and password base64 encoded in `Authorization` header. - `Authorization: Basic encoded_credentials` - **OAuth 2.0:** Industry standard for delegated authorization. Provides access tokens after user grants permission. - **Flows:** Authorization Code, Client Credentials, Implicit, Password. - `Authorization: Bearer access_token_here` - **JSON Web Tokens (JWT):** Compact, URL-safe means of representing claims to be transferred between two parties. Often used with OAuth 2.0. Signature verifies sender. - Structure: `header.payload.signature` ### Common Data Formats - **JSON (JavaScript Object Notation):** Lightweight, human-readable, and widely used for data interchange. ```json { "user": { "id": 123, "name": "Alice", "roles": ["admin", "editor"] }, "active": true } ``` - **XML (Extensible Markup Language):** More verbose, but still used, especially with SOAP. ```xml 123 Alice admin editor true ``` - **Form Data (URL-encoded/Multipart):** Used for submitting web forms. - `application/x-www-form-urlencoded`: `key1=value1&key2=value2` - `multipart/form-data`: For submitting files. ### API Best Practices - **Versioning:** Use `/v1`, `/v2` in URLs to manage changes without breaking old clients. - **HATEOAS (Hypermedia As The Engine Of Application State):** Include links in responses to related resources. `"_links": {"self": "/api/users/1"}` - **Paging/Pagination:** For large datasets, return limited results and links for next/previous pages. - Example params: `?offset=20&limit=10` or `?page=2&per_page=10` - **Rate Limiting:** Protect your API from abuse by limiting the number of requests clients can make in a given time. - Headers: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` - **Error Handling:** Provide clear, consistent error messages with appropriate HTTP status codes. - **Security:** Always use HTTPS. Validate all input.