This tutorial turns a Python function into a serverless endpoint. You write the function, test it on your own computer, put it in a container image and run it on GPU workers that start when requests arrive and are released when it is quiet. Writing and testing take about five minutes; building the image and the first cold start take longer. If the Endpoints page says endpoints are not available yet, they are not switched on for your account.
To serve an existing model behind an OpenAI-compatible address without writing code, follow Scale to zero with a serverless endpoint instead.
What you need
- Python 3.9 or newer on your computer.
- Docker, and an account on a container registry such as Docker Hub (a private registry works too, see Templates).
- An API key with the Servers scope, stored in
APIDLY_API_KEY.
1. Write the handler
Make a folder and save this as handler.py:
from apidly_worker import serve
def handler(req):
data = req.json() or {}
name = data.get("name", "world")
return {"greeting": f"Hello, {name}!"}
serve(handler)req.json() is the request body as JSON. What you return becomes the answer: a dict or list is sent as JSON, a string as text. This handler answers every path; to serve several paths, see Worker kit.
2. Test it on your computer
Download the worker kit into the same folder, check it and install it:
curl -fsSLO https://apidly.com/downloads/SHA256SUMS
curl -fsSLO https://apidly.com/downloads/apidly_worker-0.2.4-py3-none-any.whl
grep -F apidly_worker-0.2.4-py3-none-any.whl SHA256SUMS | sha256sum -c - # macOS: shasum -a 256 -c -
pip install ./apidly_worker-0.2.4-py3-none-any.whlRun the handler once with a test input. Nothing is started and nothing is sent to us:
python handler.py --test_input '{"name": "Ada"}'It prints status: 200 and {"greeting": "Hello, Ada!"}. If your code raises an error, you see the full traceback and the command exits with code 1. You can also keep the input in a file: --test_input @input.json.
To try it as a server, run python handler.py and, in another terminal, curl -X POST localhost:8000/hello -d '{"name": "Ada"}'. Stop it with Ctrl-C.
3. Put it in an image
Save this as Dockerfile in the same folder:
FROM python:3.12-slim
COPY apidly_worker-*.whl /tmp/
RUN pip install --no-cache-dir /tmp/apidly_worker-*.whl
COPY handler.py /app/handler.py
EXPOSE 8000
CMD ["python", "/app/handler.py"]Build it for the x86-64 (linux/amd64) processors our machines use and push it to your registry, with your own user name in place of YOUR_USER:
docker build --platform linux/amd64 -t YOUR_USER/hello-worker:1 .
docker push YOUR_USER/hello-worker:1A real model needs a GPU image instead of python:3.12-slim, for example one with PyTorch and CUDA, and the model loaded in a setup function so it is loaded once per worker (see Worker kit).
4. Make a template
- Open Templates and select New template.
- Name it
hello-workerand enter the imageYOUR_USER/hello-workerwith the tag1. - Under Launch mode choose Container (entrypoint) and leave the arguments empty, so the image's own command runs.
- Add port
8000(TCP) and set App port to8000. - Set the disk to the smallest size offered and select Save template.
5. Create the endpoint
- Open Endpoints and select New endpoint.
- Pick the cheapest GPU in stock (this handler does not use the GPU) and select Next.
- Choose your
hello-workertemplate and select Next. - Name it
hello, keep Minimum workers 0 and Maximum workers 1, and check that Health path is/health. - Select Create endpoint.
The kit answers /health for you, and checks the worker token we give each worker, so only requests that come through your endpoint reach your code.
6. Call it
Copy the endpoint id (epn_...) from its page. With no worker running, the first request waits while one starts; that takes a few minutes, and a single request is held for at most 240 seconds. This loop retries on 503 until the worker is ready:
until curl -sf https://apidly.com/api/v1/endpoints/EPN_ID/proxy/hello \
-H "Authorization: Bearer $APIDLY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name": "Ada"}'; do echo "No worker ready yet, trying again in 30 s"; sleep 30; doneThe answer is {"greeting": "Hello, Ada!"}. Further requests are answered at once while the worker runs. After the idle timeout with no request, the worker is released and the endpoint costs nothing again.
What it costs
There is no price per request. A worker is billed by the second at its GPU and disk price from the moment its server runs until it is released, like any server; the endpoint page shows the price per worker and, under Metrics, what was actually charged. With a minimum of 0 workers an idle endpoint costs nothing. To be sure, set a Spending cap per hour. When you are done, Pause or delete the endpoint.
Next steps
- Stream the answer: return a generator (
yieldeach piece) orResponse.sse(...)for server-sent events. - Long work: set the endpoint's job mode to Worker kit and send async jobs of up to an hour; call
req.progress({"step": 3, "of": 10})and the job shows it asprogress. - Several requests at once:
serve(handler, max_concurrency=4). - Scale-down during a job: a stopping worker gives running jobs 25 seconds to finish; with
requeue_on_stop=True(only for handlers that are safe to run twice) an unfinished job is sent to another worker, otherwise it fails withworker_stopped. - Serverless endpoints for every setting.
Ready to try it?
Create a free account and add credit when you want to start a server. The smallest top-up is $10.
Was this helpful?