API with Flask Excercises

In this exercise, you will learn how to create a simple API in Flask, run it, send requests to it, and use a decision model based on a basic logical rule.

1️⃣ Creating a Basic API

First, we will create a basic Flask application.

Saving the API Code to a File

In Jupyter Notebook, use the magic command %%file to save the basic Flask application code to a file named app.py. You can find the code at lab1.

For the main page text, use Welcome to my API!.

%%file app.py
###
# YOUR CODE HERE
###
Writing app.py

Now, start the API in the terminal by typing:

python app.py

Flask will start the server locally at http://127.0.0.1:5000/.

Checking API Functionality

In Jupyter Notebook, perform a GET request to the homepage. Based on the status_code field, write a conditional expression that will display the response content (from the content field) if the status_code is 200.

import requests
response = #YOUR CODE

If everything is working correctly, you will see the message Welcome to my API!.


2️⃣ Adding a New Subpage

Let’s add a new subpage mypage that will return the message This is my page!.

%%file app.py
###
# YOUR CODE HERE 
###

Restart the API and make a request to the page "http://127.0.0.1:5000/mypage":

response = pass # YOUR CODE HERE

You should see: This is my page!


3️⃣ Automatically Starting the Server from Jupyter Notebook

Close the previously started server (Ctrl+C in the terminal) and restart it directly from Jupyter Notebook using subprocess.Popen:

import subprocess
# YOUR CODE 
server = pass

After testing, close the server using the kill method:

# Your code here

4️⃣ Handling Parameters in the URL

Let’s add a new subpage /hello that will accept a name parameter.

Edit app.py by adding the appropriate code.

%%file app.py
###
# Your Code
###

Start the server and check the API functionality:

res1 = requests.get("http://127.0.0.1:5000/hello")
print(res1.content)  # Powinno zwrócić "Hello!"

res2 = requests.get("http://127.0.0.1:5000/hello?name=Sebastian")
print(res2.content)  # Powinno zwrócić "Hello Sebastian!"

5️⃣ Creating an API with a Simple ML Model

We will create a new subpage /api/v1.0/predict, which accepts two numbers and returns the result of a decision rule: - If the sum of the two numbers is greater than 5.8, it returns 1. - Otherwise, it returns 0.

Verify API

res = requests.get("http://127.0.0.1:5000/api/v1.0/predict?num1=3&num2=4")
print(res.json())  # Powinno zwrócić {"prediction": 1, "features": {"num1": 3.0, "num2": 4.0}}

Summary

After completing this exercise, students will be able to: ✅ Create a basic API in Flask. ✅ Add subpages and handle URL parameters. ✅ Send GET requests and analyze responses. ✅ Automatically start the server from Jupyter Notebook. ✅ Implement a simple decision model in the API.

Ready for the next challenges? 🚀