Skip to main content
Build a complete REST API with CRUD operations, input validation, and error handling. What you’ll learn:
  • Routing requests to different handlers
  • Parsing JSON request bodies
  • Returning proper HTTP status codes
  • Error handling patterns

Prerequisites

  • Telnyx account with Edge Compute enabled
  • telnyx-edge CLI installed

Step 1: Create the Function

telnyx-edge new-func -l=python -n=my-api
cd my-api

Step 2: Implement the API

Replace src/main.py:
import json
from urllib.parse import urlparse, parse_qs

# In-memory storage (use KV for persistence)
items = {}
next_id = 1

class Function:
    async def handler(self, request):
        path = urlparse(request.url).path
        method = request.method
        
        # Route requests
        if path == "/items" and method == "GET":
            return self.list_items()
        elif path == "/items" and method == "POST":
            return await self.create_item(request)
        elif path.startswith("/items/") and method == "GET":
            return self.get_item(path.split("/")[-1])
        elif path.startswith("/items/") and method == "DELETE":
            return self.delete_item(path.split("/")[-1])
        else:
            return self.json_response({"error": "Not found"}, 404)
    
    def list_items(self):
        return self.json_response(list(items.values()))
    
    async def create_item(self, request):
        global next_id
        try:
            body = json.loads(await request.text())
        except json.JSONDecodeError:
            return self.json_response({"error": "Invalid JSON"}, 400)
        
        if "name" not in body:
            return self.json_response({"error": "name is required"}, 400)
        
        item = {"id": str(next_id), "name": body["name"]}
        items[str(next_id)] = item
        next_id += 1
        
        return self.json_response(item, 201)
    
    def get_item(self, item_id):
        if item_id in items:
            return self.json_response(items[item_id])
        return self.json_response({"error": "Not found"}, 404)
    
    def delete_item(self, item_id):
        if item_id in items:
            del items[item_id]
            return self.json_response({"deleted": True})
        return self.json_response({"error": "Not found"}, 404)
    
    def json_response(self, data, status=200):
        return {
            "status": status,
            "headers": {"Content-Type": "application/json"},
            "body": json.dumps(data)
        }

Step 3: Test Locally

telnyx-edge dev
In another terminal:
# Create an item
curl -X POST http://localhost:8787/items \
  -H "Content-Type: application/json" \
  -d '{"name": "Test Item"}'

# List items
curl http://localhost:8787/items

# Get single item
curl http://localhost:8787/items/1

# Delete item
curl -X DELETE http://localhost:8787/items/1

Step 4: Deploy

telnyx-edge ship
Your API is now live at https://my-api-{orgId}.telnyxcompute.com.