import subprocess
import requests
REST API with Flask
The goal of the lab is to introduce students to developing REST API applications in Python using the Flask library and containerizing them with Docker.
You will learn:
- How to create a simple REST API,
- How to handle HTTP requests and manage errors in the API,
- How to test the API using pytest,
- How to deploy the application into a Docker container.
%%file app1.py
from flask import Flask
# Create a flask
= Flask(__name__)
app
# Create an API end point
@app.route('/hello')
def say_hello():
return "Hello World"
@app.route('/')
def say_he():
return "Hello from main site"
if __name__ == '__main__':
app.run()
= subprocess.Popen(["python", "app1.py"]) p
= "http://127.0.0.1:5000/hello"
adres_url = requests.get(adres_url) response
# take content field from response object
# YOUR CODE
# take bad adress
= " "
adres_url
= requests.get(adres_url)
response
# Check if status_code field is 200
# YOUR CODE
run kill()
method for p
object
# YOUR CODE
Check any request and raspone whe your serwer is down
# YOUR CODE
= ... response
URL Adress with GET method for a sanding data
%%file app2.py
from flask import Flask
from flask import request
# Create a flask
= Flask(__name__)
app
# Create an API end point
@app.route('/hello', methods=['GET'])
def say_hello():
= request.args.get("name", "") # tutaj leci str
name = request.args.get("title", "")
title if name:
= f"Hello {title} {name}" if title else f"Hello {name}"
resp else:
= f"Hello {title}" if title else "Hello"
resp return resp
if __name__ == '__main__':
=5005) app.run(port
= subprocess.Popen(["python", "app2.py"]) p
= requests.get("http://127.0.0.1:5005/hello")
response response.content
add variables for url adress ?name=....
= requests.get("http://127.0.0.1:5005/hello?name=Sebastian")
response response.content
Try json answear
from flask import jsonify
def moja_f():
...return jsonify(reponse=resp)
and more functional solution for ML models is the [litServe](https://lightning.ai/litserve) library.
An interesting
is written in a functional style.
Notice the pipeline, which
#389512cc-55fe-43e6-b0d5-a627e60399a7 .cell execution_count=4}
::: {-code}
``` {.python .cell%%file app_lit.py
import litserve as ls
class SimpleLitAPI(ls.LitAPI):
def setup(self, device):
self.model1 = lambda x: x**2
self.model2 = lambda x: x**3
def decode_request(self, request):
return request["input"]
def predict(self, x):
= self.model1(x)
squared = self.model2(x)
cubed = squared + cubed
output return {"output": output}
def encode_response(self, output):
return {"output": output}
if __name__ == "__main__":
= SimpleLitAPI()
api = ls.LitServer(api)
server =5001) server.run(port
Overwriting app_lit.py
:::
import subprocess
= subprocess.Popen(["python", "app_lit.py"]) p
import requests
= requests.post("http://127.0.0.1:5001/predict", json={"input": 4.0})
response print(f"Status: {response.status_code}\nResponse:\n {response.text}")
Status: 200
Response:
{"output":{"output":80.0}}
p.kill()
Docker container
Plik aplikacji app.py
%%file app.py
from flask import Flask
= Flask(__name__)
app
@app.route('/')
def hello():
return "<h1>hello world</h1>"
if __name__ == '__main__':
='0.0.0.0', port=5000) app.run(host
plik requirements.txt w którym zamieścimy potrzebne biblioteki
%%file requirements.txt
==3.0.1 Flask
Dockerfile
- pobranie obrazu systemu z pythonem
- kopia pliku z wymaganymi bibliotekami
- instalacja wymaganych bibliotek w środowisku
- skopiowanie pliku aplikacji
- uruchomienie aplikacji
%%file Dockerfile
3.11-slim-buster
FROM python:
/app
WORKDIR
COPY requirements.txt requirements.txt
-r requirements.txt
RUN pip install
COPY app.py .
=app
ENV FLASK_APP
5000
EXPOSE "flask", "run", "--host", "0.0.0.0", "--port", "5000"] CMD [
docker build -t test_hello .
docker run -p 5000:5000 test_hello