{"id":27636974,"url":"https://github.com/dexter-xd/restapi-c-sqlite","last_synced_at":"2025-04-23T21:15:40.701Z","repository":{"id":288975250,"uuid":"969713353","full_name":"dexter-xD/restapi-c-sqlite","owner":"dexter-xD","description":"A lightweight RESTful API for todo management built entirely in C.","archived":false,"fork":false,"pushed_at":"2025-04-20T19:18:32.000Z","size":21,"stargazers_count":8,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-23T21:15:37.115Z","etag":null,"topics":["c","rest-api","sqlite"],"latest_commit_sha":null,"homepage":"https://medium.com/@trish07/building-a-restful-todo-api-in-c-a-step-by-step-guide-for-beginners-ab06d8e648dd","language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dexter-xD.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-04-20T19:12:35.000Z","updated_at":"2025-04-23T02:22:23.000Z","dependencies_parsed_at":"2025-04-20T20:37:49.931Z","dependency_job_id":null,"html_url":"https://github.com/dexter-xD/restapi-c-sqlite","commit_stats":null,"previous_names":["dexter-xd/restapi-c-sqlite"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dexter-xD%2Frestapi-c-sqlite","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dexter-xD%2Frestapi-c-sqlite/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dexter-xD%2Frestapi-c-sqlite/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dexter-xD%2Frestapi-c-sqlite/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dexter-xD","download_url":"https://codeload.github.com/dexter-xD/restapi-c-sqlite/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250514777,"owners_count":21443219,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["c","rest-api","sqlite"],"created_at":"2025-04-23T21:15:40.032Z","updated_at":"2025-04-23T21:15:40.681Z","avatar_url":"https://github.com/dexter-xD.png","language":"C","readme":"# C REST API - Todo Application\n\nA lightweight RESTful API for managing todo items, built entirely in C. This project demonstrates how to build web services at a low level using standard C libraries.\n\n```\n┌────────────┐     ┌─────────────┐     ┌─────────────┐\n│            │     │             │     │             │\n│   Client   │◄────►  HTTP API   │◄────►   SQLite    │\n│            │     │             │     │  Database   │\n└────────────┘     └─────────────┘     └─────────────┘\n                         │\n                         │\n                    ┌────▼────┐\n                    │         │\n                    │  JSON   │\n                    │         │\n                    └─────────┘\n```\n\n## Features\n\n- Complete CRUD operations (Create, Read, Update, Delete)\n- RESTful design following HTTP method conventions\n- SQLite database for data persistence\n- JSON request/response format\n- Modular, maintainable C code structure\n- Extensive testing capabilities\n- Memory-safe implementations with proper cleanup\n- Error handling with descriptive messages\n\n## REST API Theory\n\n### What is REST?\n\nREST (Representational State Transfer) is an architectural style for designing networked applications. Unlike SOAP or RPC which focus on actions, REST emphasizes resources and states.\n\nKey principles of REST:\n- **Statelessness**: Each request contains all information needed to process it\n- **Client-Server Architecture**: Separation of concerns between UI/client and data storage\n- **Uniform Interface**: Standard methods to interact with resources\n- **Resource-Based**: Everything is a resource identified by a unique URI\n- **Representation**: Resources can be represented in different formats (JSON, XML, etc.)\n\n### HTTP Methods in REST\n\nThis API implements the standard HTTP methods for CRUD operations:\n\n| HTTP Method | CRUD Operation | Description |\n|-------------|---------------|-------------|\n| GET | Read | Retrieve resource(s) |\n| POST | Create | Create a new resource |\n| PUT | Update | Update an existing resource |\n| DELETE | Delete | Remove a resource |\n\n## Dependencies\n\n- **libmicrohttpd**: Small C library that makes it easy to run an HTTP server\n- **libsqlite3**: C library for SQLite, a self-contained, serverless database engine\n- **libjansson**: C library for encoding, decoding, and manipulating JSON data\n- **libcurl**: Client-side URL transfer library (used for testing)\n- **CMake**: Cross-platform build system generator\n\n## Setup \u0026 Installation\n\n### Install Dependencies\n\nFor Debian/Ubuntu:\n```bash\nsudo apt-get update\nsudo apt-get install build-essential cmake libcurl4-openssl-dev libsqlite3-dev libmicrohttpd-dev libjansson-dev\n```\n\n### Build\n\n```bash\nmkdir -p build\ncd build\ncmake ..\nmake\n```\n\n## Running the API\n\nStart the server:\n```bash\n./build/src/todo_api\n```\n\nThe server will listen on port 8080 by default.\n\n## Example API Calls\n\n### Create a Todo\n```bash\ncurl -X POST http://localhost:8080/todos -H \"Content-Type: application/json\" -d '{\"title\":\"Buy groceries\",\"description\":\"Get milk, bread, and eggs\"}'\n```\n\n### List All Todos\n```bash\ncurl http://localhost:8080/todos\n```\n\n### Get a Specific Todo\n```bash\ncurl http://localhost:8080/todos/1\n```\n\n### Update a Todo\n```bash\ncurl -X PUT http://localhost:8080/todos/1 -H \"Content-Type: application/json\" -d '{\"title\":\"Buy groceries\",\"description\":\"Get milk, bread, eggs, and cheese\",\"completed\":true}'\n```\n\n### Delete a Todo\n```bash\ncurl -X DELETE http://localhost:8080/todos/1\n```\n\n## Management Script\n\nFor easier development, use the management script:\n```bash\n./manage.sh build   # Build the project\n./manage.sh run     # Run the server\n./manage.sh test    # Run unit tests\n./manage.sh api-test # Test API endpoints\n```\n\n## Project Architecture\n\n### Directory Structure\n\n```\nrest-api/\n├── CMakeLists.txt              # Main CMake configuration\n├── manage.sh                   # Management script\n├── src/                        # Source code\n│   ├── CMakeLists.txt          # Source CMake configuration\n│   ├── main.c                  # Entry point\n│   ├── core/                   # Core functionality\n│   │   ├── todo.h              # Todo structure definition\n│   │   └── todo.c              # Todo operations\n│   ├── db/                     # Database operations\n│   │   ├── database.h          # Database interface\n│   │   └── database.c          # SQLite implementation\n│   └── http/                   # HTTP handling\n│       ├── server.h            # Server interface\n│       ├── server.c            # Server implementation\n│       ├── handlers.h          # Request handlers interface\n│       └── handlers.c          # Request handlers implementation\n├── tests/                      # Unit tests\n│   ├── CMakeLists.txt          # Test CMake configuration\n│   └── test_todo.c             # Todo unit tests\n└── scripts/                    # Helper scripts\n    └── test_api.sh             # API test script\n```\n\n### Internal Components\n\n#### Todo Data Structure (core/todo.h, core/todo.c)\n\nThe central data model representing a task with:\n- Unique identifier\n- Title and description\n- Completion status\n- Timestamps for creation and updates\n\nOperations include creating, retrieving, updating, and deleting todos.\n\n#### Database Management (db/database.h, db/database.c)\n\nManages all interactions with SQLite:\n- Initializes the database and creates tables\n- Executes SQL statements for CRUD operations\n- Provides a callback mechanism for processing query results\n\nSQLite was chosen for its simplicity, zero-configuration, and self-contained nature.\n\n#### HTTP Server (http/server.h, http/server.c)\n\nBuilt with libmicrohttpd to:\n- Start and stop the HTTP server\n- Route requests to appropriate handlers\n- Parse request URLs, methods, and bodies\n- Send formatted responses with correct status codes\n\n#### Request Handlers (http/handlers.h, http/handlers.c)\n\nImplements the business logic for each API endpoint:\n- Parsing JSON requests using jansson\n- Performing operations on the todo structure\n- Generating JSON responses\n- Error handling with appropriate HTTP status codes\n\n## Implementation Details\n\n### Memory Management\n\nThe API takes care to properly manage memory:\n- Dynamic allocations are tracked and freed\n- String buffers are properly sized and null-terminated\n- JSON objects are reference-counted and properly released\n\n### Error Handling\n\nComprehensive error handling includes:\n- Database errors with detailed messages\n- JSON parsing errors\n- HTTP request validation\n- Resource not found errors\n- Server initialization failures\n\n### Concurrency\n\nlibmicrohttpd handles concurrency with a thread-per-connection model, allowing the API to serve multiple clients simultaneously. The SQLite database is configured for thread-safety.\n\n### Testing Strategy\n\nThe project implements multiple testing layers:\n1. **Unit Tests**: Test individual functions in isolation\n2. **Integration Tests**: Test the interaction between components\n3. **API Tests**: Test HTTP endpoints end-to-end\n\n## Performance Considerations\n\n- **Connection Pooling**: The server uses connection pooling to reduce overhead\n- **Prepared Statements**: SQL statements are prepared to improve database performance\n- **Minimal Copying**: Data is processed with minimal copying between memory regions\n- **Efficient JSON Parsing**: Uses jansson's stream parsing for large payloads\n\n## Security Considerations\n\n- **Input Validation**: All client inputs are validated before processing\n- **SQL Injection Prevention**: Uses prepared statements to prevent SQL injection\n- **Memory Safety**: Careful buffer management to prevent overflows\n- **Error Information**: Limited error details exposed to clients\n\n## Contributing\n\nContributions are welcome! Feel free to open issues or submit pull requests.\n\nWhen contributing, please:\n1. Follow the existing code style\n2. Add tests for new functionality\n3. Ensure all tests pass\n4. Update documentation as needed\n\n## Support\n\nIf you find this project helpful, consider buying me a coffee:\n\n[![Buy Me A Coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://buymeacoffee.com/trish07)\n\n## License\n\nThis project is licensed under the MIT License - see the LICENSE file for details. \n","funding_links":["https://buymeacoffee.com/trish07"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdexter-xd%2Frestapi-c-sqlite","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdexter-xd%2Frestapi-c-sqlite","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdexter-xd%2Frestapi-c-sqlite/lists"}