craft c99 code : -rest api backend -only GET with params lat lon time date -as few…
- User
craft c99 code : -rest api backend -only GET with params lat lon time date -as few dependencies as possible
- Assistant
Below is a complete, self-contained C99 program that implements a minimal REST API backend. It meets your requirements:
- REST API backend: It exposes a single endpoint
/apithat accepts only GET requests with query parameterslat,lon,time, anddate. For example:GET /api?lat=37.7749&lon=-122.4194&time=12:00&date=2023-10-01. - Only GET with params: It strictly checks for GET method and requires all four parameters. If the request is invalid (wrong method, missing params, or not
/apipath), it returns a 400 Bad Request. Otherwise, it returns a 200 OK with a simple JSON response echoing the parameters (e.g., for demo purposes; you can modify the response logic as needed). - As few dependencies as possible:
- No external libraries (e.g., no libmicrohttpd, no JSON parsers).
- Uses only standard C99 and POSIX headers (e.g., for sockets). This assumes a Unix-like system (e.g., Linux/macOS). It won't compile on Windows without adjustments (e.g., Winsock).
- Manual HTTP parsing (very basic, handles only simple GET requests; no headers, no body parsing beyond the request line and query string).
- Single-threaded, blocking server (handles one request at a time for simplicity).
- Listens on port 8080 (change as needed).
This is a "bare-metal" implementation to minimize dependencies—it's essentially a TCP server that parses HTTP/1.1 GET requests manually. It's not production-ready (e.g., no error handling for all edge cases, no security, no concurrency), but it works for a proof-of-concept. Test it with
curl http://localhost:8080/api?lat=37.7749&lon=-122.4194&time=12:00&date=2023-10-01.Compilation and Running
- Compile:
gcc -std=c99 -o restapi restapi.c - Run:
./restapi - Stop: Ctrl+C
Code
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define PORT 8080 #define BUFFER_SIZE 1024 #define MAX_QUERY_LEN 256 // Function to parse query string and extract params (lat, lon, time, date) // Returns 1 if all params are present, 0 otherwise. // Stores values in out_* buffers (assumed pre-allocated). int parse_query(const char* query, char* out_lat, char* out_lon, char* out_time, char* out_date) { char* q = strdup(query); // Copy to avoid modifying original if (!q) return 0; char* token = strtok(q, "&"); int found_lat = 0, found_lon = 0, found_time = 0, found_date = 0; while (token) { char* eq = strchr(token, '='); if (eq) { *eq = '\0'; // Split key=value char* key = token; char* value = eq + 1; if (strcmp(key, "lat") == 0) { strncpy(out_lat, value, MAX_QUERY_LEN); found_lat = 1; } else if (strcmp(key, "lon") == 0) { strncpy(out_lon, value, MAX_QUERY_LEN); found_lon = 1; } else if (strcmp(key, "time") == 0) { strncpy(out_time, value, MAX_QUERY_LEN); found_time = 1; } else if (strcmp(key, "date") == 0) { strncpy(out_date, value, MAX_QUERY_LEN); found_date = 1; } } token = strtok(NULL, "&"); } free(q); return found_lat && found_lon && found_time && found_date; } // Function to send HTTP response void send_response(int client_sock, int status, const char* body) { char response[BUFFER_SIZE]; const char* status_text = (status == 200) ? "OK" : "Bad Request"; const char* content_type = "application/json"; snprintf(response, sizeof(response), "HTTP/1.1 %d %s\r\n" "Content-Type: %s\r\n" "Content-Length: %lu\r\n" "Connection: close\r\n\r\n" "%s", status, status_text, content_type, strlen(body), body); send(client_sock, response, strlen(response), 0); } int main() { int server_sock, client_sock; struct sockaddr_in server_addr, client_addr; socklen_t addr_len = sizeof(client_addr); char buffer[BUFFER_SIZE]; // Create socket server_sock = socket(AF_INET, SOCK_STREAM, 0); if (server_sock < 0) { perror("socket failed"); exit(EXIT_FAILURE); } // Bind to port memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(PORT); if (bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) { perror("bind failed"); close(server_sock); exit(EXIT_FAILURE); } // Listen if (listen(server_sock, 5) < 0) { perror("listen failed"); close(server_sock); exit(EXIT_FAILURE); } printf("Server listening on port %d\n", PORT); while (1) { // Accept connection client_sock = accept(server_sock, (struct sockaddr*)&client_addr, &addr_len); if (client_sock < 0) { perror("accept failed"); continue; } // Read request memset(buffer, 0, sizeof(buffer)); ssize_t bytes_read = recv(client_sock, buffer, sizeof(buffer) - 1, 0); if (bytes_read <= 0) { close(client_sock); continue; } // Parse request line (e.g., "GET /api?lat=... HTTP/1.1") char method[16], path[MAX_QUERY_LEN], query[MAX_QUERY_LEN], version[16]; query[0] = '\0'; // Default empty query if (sscanf(buffer, "%15s %255s %15s", method, path, version) != 3) { send_response(client_sock, 400, "{\"error\": \"Invalid request\"}"); close(client_sock); continue; } // Only allow GET if (strcmp(method, "GET") != 0) { send_response(client_sock, 400, "{\"error\": \"Only GET supported\"}"); close(client_sock); continue; } // Check path is /api char* query_start = strchr(path, '?'); if (query_start) { *query_start = '\0'; // Split path and query strncpy(query, query_start + 1, MAX_QUERY_LEN); } if (strcmp(path, "/api") != 0) { send_response(client_sock, 400, "{\"error\": \"Invalid path, use /api\"}"); close(client_sock); continue; } // Parse query params char lat[MAX_QUERY_LEN] = {0}, lon[MAX_QUERY_LEN] = {0}, time[MAX_QUERY_LEN] = {0}, date[MAX_QUERY_LEN] = {0}; if (!parse_query(query, lat, lon, time, date)) { send_response(client_sock, 400, "{\"error\": \"Missing params: lat, lon, time, date\"}"); close(client_sock); continue; } // Construct JSON response (dummy echo for demo; customize here) char body[BUFFER_SIZE]; snprintf(body, sizeof(body), "{\"lat\": \"%s\", \"lon\": \"%s\", \"time\": \"%s\", \"date\": \"%s\"}", lat, lon, time, date); send_response(client_sock, 200, body); close(client_sock); } close(server_sock); return 0; }Explanation
- Server Setup: Creates a TCP socket, binds to port 8080, and listens for connections.
- Request Handling: Accepts connections, reads the HTTP request into a buffer, parses the method, path, and query string manually using
sscanfandstrtok. - Param Parsing: Extracts
lat,lon,time,datefrom the query string. Requires all four. - Response: Sends a hardcoded HTTP response with JSON body (using
snprintffor simplicity; no JSON lib needed). - Limitations:
- Handles only the request line (ignores headers, bodies).
- No URL decoding (assumes params are simple; add if needed).
- Blocking and single-threaded.
- Error handling is basic.
If you need modifications (e.g., actual logic for the params, HTTPS, or more robust parsing), let me know!
- REST API backend: It exposes a single endpoint
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.