# Your first endpoint with your own code

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](/docs/tutorial-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](/docs/templates#private-registries)).
- An [API key](/docs/api-keys) with the **Servers** scope, stored in `APIDLY_API_KEY`.

## 1. Write the handler

Make a folder and save this as `handler.py`:

```python
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](/docs/endpoints#worker-kit).

## 2. Test it on your computer

Download the worker kit into the same folder, check it and install it:

```bash
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.whl
```

Run the handler once with a test input. Nothing is started and nothing is sent to us:

```bash
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:

```dockerfile
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`:

```bash
docker build --platform linux/amd64 -t YOUR_USER/hello-worker:1 .
docker push YOUR_USER/hello-worker:1
```

A 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](/docs/endpoints#worker-kit)).

## 4. Make a template

1. Open **Templates** and select **New template**.
2. Name it `hello-worker` and enter the image `YOUR_USER/hello-worker` with the tag `1`.
3. Under **Launch mode** choose **Container (entrypoint)** and leave the arguments empty, so the image's own command runs.
4. Add port `8000` (TCP) and set **App port** to `8000`.
5. Set the disk to the smallest size offered and select **Save template**.

## 5. Create the endpoint

1. Open **Endpoints** and select **New endpoint**.
2. Pick the cheapest GPU in stock (this handler does not use the GPU) and select **Next**.
3. Choose your `hello-worker` template and select **Next**.
4. Name it `hello`, keep **Minimum workers** 0 and **Maximum workers** 1, and check that **Health path** is `/health`.
5. 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:

```bash
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; done
```

The 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 (`yield` each piece) or `Response.sse(...)` for server-sent events.
- **Long work:** set the endpoint's job mode to *Worker kit* and send [async jobs](/docs/endpoints#async-jobs) of up to an hour; call `req.progress({"step": 3, "of": 10})` and the job shows it as `progress`.
- **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 with `worker_stopped`.
- [Serverless endpoints](/docs/endpoints) for every setting.
