%%file app.py
###
# YOUR CODE HERE
###
Writing app.py
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.
First, we will create a basic Flask application.
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!.
Now, start the API in the terminal by typing:
Flask will start the server locally at http://127.0.0.1:5000/
.
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.
If everything is working correctly, you will see the message Welcome to my API!
.
Let’s add a new subpage mypage
that will return the message This is my page!
.
Restart the API and make a request to the page "http://127.0.0.1:5000/mypage"
:
You should see: This is my page!
Close the previously started server (Ctrl+C
in the terminal) and restart it directly from Jupyter Notebook using subprocess.Popen
:
After testing, close the server using the kill
method:
Let’s add a new subpage /hello that will accept a name parameter.
Edit app.py by adding the appropriate 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!"
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}}
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? 🚀