Skip to content

Instantly share code, notes, and snippets.

@araujo88
Created February 23, 2024 03:20
Show Gist options
  • Save araujo88/a68798fbeb79d9e8f5a7d4d0747237f7 to your computer and use it in GitHub Desktop.
Save araujo88/a68798fbeb79d9e8f5a7d4d0747237f7 to your computer and use it in GitHub Desktop.
REST API in bash script

This script use nc (netcat) and will rudimentarily parse HTTP requests to match CRUD operations. Each operation will be mapped to HTTP methods as follows:

  • POST for create,
  • GET for read,
  • PUT for update,
  • DELETE for delete.
#!/bin/bash

PORT=12345
DATA_FILE="data.txt"

while true; do
  # Listen for connections
  { 
    read line
    METHOD=$(echo "$line" | cut -d ' ' -f1)
    PATH=$(echo "$line" | cut -d ' ' -f2)
    # Remove leading and trailing slashes
    KEY=$(echo "$PATH" | sed 's/^\/\|\/$//g')
    
    # Read headers (stop at empty line)
    while read -r line; do
      [[ "$line" == $'\r' ]] && break
    done

    case $METHOD in
      POST)
        # Assume the body is a single line for simplicity
        read -r VALUE
        echo "$KEY $VALUE" >> $DATA_FILE
        RESPONSE="HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nRecord created"
        ;;
      GET)
        VALUE=$(grep "^$KEY " $DATA_FILE | cut -d " " -f 2-)
        RESPONSE="HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n$VALUE"
        ;;
      PUT)
        read -r VALUE
        sed -i "/^$KEY /c\\$KEY $VALUE" $DATA_FILE
        RESPONSE="HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nRecord updated"
        ;;
      DELETE)
        sed -i "/^$KEY /d" $DATA_FILE
        RESPONSE="HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nRecord deleted"
        ;;
      *)
        RESPONSE="HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\n\r\nUnknown method"
        ;;
    esac

    # Send response
    echo -en "$RESPONSE"
  } | nc -l -p $PORT
done

Usage:

  • POST/Create: curl -X POST -d 'Hello, World' http://localhost:12345/1
  • GET/Read: curl http://localhost:12345/1
  • PUT/Update: curl -X PUT -d 'Hello, Universe' http://localhost:12345/1
  • DELETE/Delete: curl -X DELETE http://localhost:12345/1

Notes:

  1. This script is a very basic example and might not fully adhere to REST principles or HTTP standards.
  2. It lacks security, error handling, and concurrent connection management.
  3. HTTP body parsing is simplified to assume a single line of text, which might not be suitable for all use cases.
  4. The script must be run with sufficient permissions to listen on the specified port.
  5. As with the previous example, this script is meant for educational purposes and is not suitable for production use.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment