Coding the App
In this tutorial, we'll take advantage of the FastAPI library in Python. If you are familiar with any other language and framework, feel free to just replace the code samples in this section with your preferred alternative.
Creating the Required Files
First, create a new git repository with GitHub. We'll need to add the following files:
โโโ api.py
โโโ requirements.txt
โโโ Dockerfile
โโโ README.md (optional)
โโโ .gitignore (optional)
Fill in the Code
Next, we'll fill in the code just like we would do if we were planning to run on a normal server.
A Simple Server
Next, we can write the simplest of FastAPI servers:
from fastapi import FastAPI, Header
from typing import Optional
app = FastAPI()
@app.get("/say_hello")
async def say_hello(x_oblv_user_name: Optional[str] = Header(None)):
return {"message": "Hello " + x_oblv_user_name}
The only thing that may look unfamiliar from a standard FastAPI server is that we are reading the optional header field X-OBLV-User-Name
which gets autocast to be snake case (lowercase with underscores) as x_oblv_user_name
. When we use PKI pre-shared keys (PSK) with field is added by the proxy so the application can know who it was who made the request.
The simple server above will reply to a request by responding Hello
to the user's name.
Requirements
In the requirements.txt
file, add the requirements for a basic FastAPI server:
fastapi>=0.68.0,<0.69.0
pydantic>=1.8.0,<2.0.0
uvicorn>=0.15.0,<0.16.0
Dockerfile
As a last step, let's write a simple Dockerfile
to package the api. It should look something like this:
FROM python:3.9
WORKDIR /code
COPY ./requirements.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
COPY ./api.py /code/api.py
CMD ["uvicorn", "api:app", "--host", "0.0.0.0", "--port", "80"]
To build and run the above packaged application we can simply do the following:
docker build -t example .
docker run -p 1234:80 -t example
Quick Test
The above should make a simple api when we build and deploy it with docker. To test it from the command line you can use a curl
command as follows:
curl --header "X-OBLV-User-Name: Bob" localhost:1234/say_hello
Equally, if you use Postman or equivalent, simply call localhost:1234 with the header field set from your Postman application:
Push to GitHub
Finally push your code to GitHub as a new repository. For the sake of simplicity let's call is my-first-oblivious-app
.