Using cURL with REST APIs

Aug 22, 2024

Notes on Using cURL to Interact with REST API

Overview of cURL

  • cURL is a command-line tool for making HTTP requests.
  • It’s minimal and widely available (Linux, Mac, Windows via WSL).
  • Can be incorporated into bash scripts.

REST API Basics

  • REST API allows interaction with resources through methods.
  • Key HTTP methods:
    • GET: Retrieve data.
    • POST: Create new data.
    • PUT: Update existing data.
    • DELETE: Remove data.

Example: To-Do List API

  • Resource Structure:

    • Base URL: /api/{user} where {user} is the user's name.
    • Operations for User's To-Do List:
      • GET: Returns all to-do items for a user.
      • POST: Appends a new to-do item.
        • Requires JSON object with a field text.
  • Operations for a Specific To-Do Item:

    • GET: Retrieve a specific item by ID.
    • PUT: Update completion status (completed or not). Defaults to uncompleted.
    • DELETE: Remove a specific to-do item.

Using cURL Commands

  1. Creating a To-Do Item (POST):

    • Command structure:
      curl -H "Content-Type: application/json" -X POST -d '{"text": "my thing to do"}' http://localhost/api/adam
      
    • Returns an empty JSON object or nothing.
  2. Retrieving All To-Do Items (GET):

    • Command:
      curl -H "Content-Type: application/json" -X GET http://localhost/api/adam
      
    • Returns a list of items in JSON format.
  3. Updating a To-Do Item (PUT):

    • Command:
      curl -H "Content-Type: application/json" -X PUT -d '{"completed": true}' http://localhost/api/adam/15
      
    • Updates the completion status of the item with ID 15.
  4. Retrieving a Specific To-Do Item (GET):

    • Command:
      curl -H "Content-Type: application/json" -X GET http://localhost/api/adam/15
      
    • Returns the specific item in JSON format.
  5. Deleting a To-Do Item (DELETE):

    • Command:
      curl -H "Content-Type: application/json" -X DELETE http://localhost/api/adam/15
      
    • Removes the item with ID 15.

Tips for Using cURL

  • Ensure the correct HTTP method is used according to the operation (GET, POST, PUT, DELETE).
  • Watch for syntax errors, especially with slashes in URLs, as they can affect request outcomes.
  • Test requests after each operation to verify that the API behaves as expected.