Cursor rule
.cursor/rules/api-patterns.mdcRESTful API design patterns and conventions for POS System
Cursor rules
Quality
62/100
Scores the file, not the repository.Length
937 words
39 headings · 16 code blocksRepository
118
— · pushed 339 days agoLast changed
3 days ago
First indexed 3 days ago.12345# API Development Guidelines67## RESTful API Design89### Endpoint Conventions10Follow the patterns established in [backend/internal/api/routes.go](mdc:backend/internal/api/routes.go):1112### Resource Naming13- Use plural nouns for resources: `/api/v1/orders`, `/api/v1/products`14- Use kebab-case for multi-word resources: `/api/v1/dining-tables`15- Nest related resources: `/api/v1/orders/{id}/payments`16- Use descriptive action names for non-CRUD operations: `/api/v1/orders/{id}/status`1718### HTTP Methods19Standard CRUD operations:20```21GET /api/v1/orders # List all orders22POST /api/v1/orders # Create new order23GET /api/v1/orders/{id} # Get specific order24PUT /api/v1/orders/{id} # Update entire order25PATCH /api/v1/orders/{id} # Partial update26DELETE /api/v1/orders/{id} # Delete order2728# Action-specific endpoints29PATCH /api/v1/orders/{id}/status # Update order status30POST /api/v1/orders/{id}/payments # Add payment to order31```3233## Request/Response Patterns3435### Standard Response Format36Use consistent response structure from [models/models.go](mdc:backend/internal/models/models.go):3738```json39{40 "success": true,41 "message": "Order created successfully",42 "data": {43 "id": "uuid-here",44 "order_number": "ORD001",45 // ... other fields46 }47}48```4950### Error Response Format51```json52{53 "success": false,54 "message": "User-friendly error message",55 "error": "error_code_for_clients"56}57```5859### Pagination Response Format60```json61{62 "success": true,63 "message": "Orders retrieved successfully",64 "data": [...],65 "meta": {66 "current_page": 1,67 "per_page": 20,68 "total": 150,69 "total_pages": 870 }71}72```7374## Authentication & Authorization7576### JWT Token Authentication77Follow patterns from [middleware/auth.go](mdc:backend/internal/middleware/auth.go):7879### Request Headers80```81Authorization: Bearer <jwt_token>82Content-Type: application/json83Accept: application/json84```8586### Role-Based Access Control87```go88// Public routes - no authentication89public.POST("/auth/login", authHandler.Login)9091// Protected routes - authentication required92protected.GET("/orders", orderHandler.GetOrders)9394// Admin routes - specific roles required95admin.Use(middleware.RequireRoles([]string{"admin", "manager"}))96admin.GET("/dashboard/stats", getDashboardStats)97```9899## Query Parameters & Filtering100101### Standard Query Parameters102```103GET /api/v1/orders?page=1&per_page=20&status=pending&order_type=dine_in104```105106### Common Parameters107- `page` - Page number for pagination (default: 1)108- `per_page` - Items per page (default: 20, max: 100)109- `sort` - Sort field and direction: `sort=created_at:desc`110- `search` - Text search across relevant fields111- Resource-specific filters (status, type, date ranges, etc.)112113### Date Filtering114```115GET /api/v1/orders?created_after=2024-01-01&created_before=2024-12-31116```117118## Error Handling119120### HTTP Status Codes121Use appropriate status codes consistently:122```123200 OK - Successful GET, PUT, PATCH124201 Created - Successful POST125204 No Content - Successful DELETE126400 Bad Request - Invalid request data127401 Unauthorized - Authentication required/failed128403 Forbidden - Insufficient permissions129404 Not Found - Resource doesn't exist130409 Conflict - Resource conflict (duplicate, etc.)131422 Unprocessable - Valid JSON but business logic error132500 Internal Error - Server error133```134135### Error Response Examples136```go137// Validation error138c.JSON(http.StatusBadRequest, models.APIResponse{139 Success: false,140 Message: "Order must contain at least one item",141 Error: stringPtr("empty_order"),142})143144// Resource not found145c.JSON(http.StatusNotFound, models.APIResponse{146 Success: false,147 Message: "Order not found",148 Error: stringPtr("order_not_found"),149})150151// Permission error152c.JSON(http.StatusForbidden, models.APIResponse{153 Success: false,154 Message: "Insufficient permissions",155 Error: stringPtr("insufficient_permissions"),156})157```158159## Request Validation160161### Input Validation Pattern162```go163type CreateOrderRequest struct {164 TableID *uuid.UUID `json:"table_id"`165 CustomerName *string `json:"customer_name"`166 OrderType string `json:"order_type"`167 Items []CreateOrderItem `json:"items"`168 Notes *string `json:"notes"`169}170171func (h *OrderHandler) CreateOrder(c *gin.Context) {172 var req CreateOrderRequest173 if err := c.ShouldBindJSON(&req); err != nil {174 c.JSON(http.StatusBadRequest, models.APIResponse{175 Success: false,176 Message: "Invalid request body",177 Error: stringPtr(err.Error()),178 })179 return180 }181182 // Additional business logic validation183 if len(req.Items) == 0 {184 c.JSON(http.StatusBadRequest, models.APIResponse{185 Success: false,186 Message: "Order must contain at least one item",187 Error: stringPtr("empty_order"),188 })189 return190 }191}192```193194## Database Transaction Patterns195196### Transaction Usage197Use transactions for multi-table operations:198```go199func (h *OrderHandler) CreateOrder(c *gin.Context) {200 tx, err := h.db.Begin()201 if err != nil {202 // Handle error203 return204 }205 defer tx.Rollback() // Always rollback if not committed206207 // Multiple database operations208 _, err = tx.Exec("INSERT INTO orders ...")209 if err != nil {210 // Error will cause rollback211 return212 }213214 _, err = tx.Exec("INSERT INTO order_items ...")215 if err != nil {216 return217 }218219 // Commit transaction220 if err := tx.Commit(); err != nil {221 // Handle commit error222 return223 }224}225```226227## API Documentation228229### Endpoint Documentation230Document each endpoint with:231- Purpose and description232- Required permissions/roles233- Request format and validation rules234- Response format and possible status codes235- Example requests and responses236237### Request/Response Examples238```go239// CreateOrder creates a new order240// @Summary Create a new order241// @Description Create a new customer order with items and table assignment242// @Tags orders243// @Accept json244// @Produce json245// @Param order body CreateOrderRequest true "Order data"246// @Success 201 {object} APIResponse{data=Order}247// @Failure 400 {object} APIResponse248// @Failure 401 {object} APIResponse249// @Router /api/v1/orders [post]250```251252## Performance Considerations253254### Query Optimization255- Use database indexes for frequently filtered fields256- Implement pagination for large result sets257- Avoid N+1 query problems with proper JOINs258- Cache expensive computations259260### Response Optimization261- Use appropriate HTTP caching headers262- Compress responses when beneficial263- Return only necessary fields (consider field selection)264- Use ETags for conditional requests265266## Rate Limiting & Throttling267268### Rate Limiting Strategy269```go270// Implement rate limiting middleware271func RateLimitMiddleware() gin.HandlerFunc {272 // Rate limiting implementation273 // Consider user-based, IP-based, or endpoint-based limits274}275276// Apply to sensitive endpoints277protected.Use(RateLimitMiddleware())278```279280## API Versioning281282### URL Versioning283Current API uses URL path versioning:284```285/api/v1/orders # Version 1286/api/v2/orders # Version 2 (future)287```288289### Backward Compatibility290- Maintain backward compatibility within major versions291- Deprecate old endpoints gracefully with proper warnings292- Document breaking changes and migration paths293- Support multiple versions during transition periods294295## Monitoring & Logging296297### Request Logging298Log important API operations:299```go300// Log successful operations301log.Printf("Order created: user_id=%s, order_id=%s", userID, orderID)302303// Log errors with context304log.Printf("Failed to create order: user_id=%s, error=%s", userID, err.Error())305```306307### Metrics Collection308Track key metrics:309- Request/response times310- Error rates by endpoint311- Authentication success/failure rates312- Resource creation/modification rates313- Database query performance
Also in madebyaris/poinf-of-sales
Diff this repo’s formatsOne repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| madebyaris/poinf-of-sales.cursor/rules/admin-interface-patterns.mdc · 118 | Cursor rules | stylearchsecurityapi+2 | 62/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/authentication-and-security-patterns.mdc · 118 | Cursor rules | setupteststylesecurity+4 | 81/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/backend-golang.mdc · 118 | Cursor rules | testlint-formatstylearch+5 | 69/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/business-logic-patterns.mdc · 118 | Cursor rules | teststyledatabaseperformance+1 | 50/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/database-patterns.mdc · 118 | Cursor rules | stylearchtypessecurity+2 | 62/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/development-workflow.mdc · 118 | Cursor rules | setupbuildteststyle+3 | 86/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/docker-deployment.mdc · 118 | Cursor rules | setupbuildteststyle+8 | 77/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/frontend-react.mdc · 118 | Cursor rules | buildtestlint-formatstyle+4 | 69/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/makefile-scripting.mdc · 118 | Cursor rules | setuplint-formatstylearch+2 | 81/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/performance-optimization-patterns.mdc · 118 | Cursor rules | buildteststyledatabase+3 | 66/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/project-architecture.mdc · 118 | Cursor rules | setupteststylearch+6 | 78/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/react-native-mobile-patterns.mdc · 118 | Cursor rules | buildstylearchui+2 | 74/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/role-based-access-patterns.mdc · 118 | Cursor rules | styletypessecuritydatabase+2 | 58/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/tech-debt-prevention.mdc · 118 | Cursor rules | styletesting-strategyui | 50/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/testing-patterns.mdc · 118 | Cursor rules | setupteststylearch+4 | 74/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/user-journey-optimization.mdc · 118 | Cursor rules | styleperformanceagent-behaviour | 50/100 | 3 days ago |
Diff against .cursor/rules/admin-interface-patterns.mdc Diff against .cursor/rules/authentication-and-security-patterns.mdc Diff against .cursor/rules/backend-golang.mdc Diff against .cursor/rules/business-logic-patterns.mdc Diff against .cursor/rules/database-patterns.mdc Diff against .cursor/rules/development-workflow.mdc Diff against .cursor/rules/docker-deployment.mdc Diff against .cursor/rules/frontend-react.mdc Diff against .cursor/rules/makefile-scripting.mdc Diff against .cursor/rules/performance-optimization-patterns.mdc Diff against .cursor/rules/project-architecture.mdc Diff against .cursor/rules/react-native-mobile-patterns.mdc Diff against .cursor/rules/role-based-access-patterns.mdc Diff against .cursor/rules/tech-debt-prevention.mdc Diff against .cursor/rules/testing-patterns.mdc Diff against .cursor/rules/user-journey-optimization.mdc
Similar configs
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| hiromaily/go-crypto-wallet.cursor/rules/typescript.mdc · 126 | Cursor rules | setupbuildtestlint-format+6 | 100/100 | 3 days ago | |
| TechSquidTV/Hermes.cursor/rules/10-hermes-api.mdc · 45 | Cursor rules | testlint-formatstylearch+5 | 100/100 | 3 days ago | |
| markstev/mark-starter.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+6 | 99/100 | 3 days ago | |
| Allymahmoud/case-intake-platform.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 3 days ago | |
| dodgecfr/combatfilms-webapp.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 3 days ago | |
| deifos/clipmira-subtitles.cursor/rules/frontend.mdc · 1 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 3 days ago | |
| langflow-ai/langflow.cursor/rules/docs_development.mdc · 153k | Cursor rules | setupbuildtestlint-format+7 | 97/100 | 3 days ago | |
| TechSquidTV/Hermes.cursor/rules/20-hermes-api-tests.mdc · 45 | Cursor rules | teststyletesting-strategysecurity+3 | 97/100 | 3 days ago |
