Skip to content

Commit 5a6b496

Browse files
committed
readme for new exercises
1 parent a38b477 commit 5a6b496

File tree

1 file changed

+175
-109
lines changed

1 file changed

+175
-109
lines changed

README.md

Lines changed: 175 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -1,169 +1,235 @@
1-
# Flask Take Home Exercises
1+
# Flask Exercise
2+
This exercise is intended for you to get familiar with fundamental backend/server side programming in an interactive way, as well as for you to get comfortable developing in a modern Python/Flask environment.
23

3-
## Setup
4-
You must have python3.6 and pip installed. To do this, check out the wiki and the page named "Mac Setup".
4+
Reading the following will help you get a sense of the big picture when it comes to developing APIs/writing server side code, and how it fits in the context of a larger web application:
5+
* [How the Web Works](https://medium.freecodecamp.org/how-the-web-works-a-primer-for-newcomers-to-web-development-or-anyone-really-b4584e63585c) - Read all 3 parts, especially part 3!
6+
* [Basics of HTTP](https://egghead.io/courses/understand-the-basics-of-http)
7+
8+
This project will be broken down into multiple parts. After you finish this project, submit a pull request and assign your tech lead to review it!
9+
10+
This exercise is due before the next all hands meeting (Sunday Feb 18th). However, the sooner you put up your PR, the sooner you will get a review, and the faster you will get feedback and learn!
11+
12+
### Guidance
13+
We understand that a lot of you are new to Flask and backend development in general. We think going through this exercise will really help you get up to speed in order to start being productive contributing to your nonprofit project.
14+
15+
A lot of what makes a good software developer is being resourceful and knowing where/how to find information you need. At the same time, the entire Hack4Impact community is available if you get stuck, have unanswered questions, or want to discuss anything!
16+
17+
Ask questions and discuss about python as a language and its features or syntax in the `#python` Slack channel.
18+
19+
Ask questions and discuss about Flask, creating endpoints, or any other backend related topics in the `#backend` Slack channel.
20+
21+
And of course, if you are already familiar with this or have figured it out, please hop in these channels and help those who need it! :)
22+
23+
### Requirements
24+
* python version 3.x
25+
* pip
26+
* [Postman](https://www.getpostman.com/)
27+
28+
Installation instructions for [Mac](https://github.com/hack4impact-uiuc/wiki/wiki/Mac-Setup) and [Windows](https://github.com/hack4impact-uiuc/wiki/wiki/Windows-Subsystem-for-Linux-Setup#setting-up-python)
29+
30+
Check if you have the correct versions by running the following commands in your terminal:
31+
```
32+
python3 -V
33+
```
34+
```
35+
pip3 -V
36+
```
37+
38+
### Setup
539
First, clone this repository and go into it:
640
```
741
$ git clone https://github.com/hack4impact-uiuc/FlaskTutorial.git
842
$ cd FlaskTutorial
943
```
10-
Then, install `virtualenv` and go into it. This allows you to have a virtual environment that for your specific application.
44+
45+
Then, install `virtualenv` and run it. This allows you to have a virtual environment for your specific application.
1146
```
1247
$ pip3 install virtualenv
1348
$ virtualenv -p python3 venv
1449
$ source venv/bin/activate
1550
```
16-
You will then have a (venv) before the $, meaning that you are now in your virtual environment. Then, install the Flask.
51+
52+
You will then have a `(venv)` before the `$`, meaning that you are now in your virtual environment. Then, install Flask.
1753
```
1854
(venv)$ pip3 install Flask
1955
(venv)$ pip3 install requests
2056
```
57+
2158
You must be in this virtual environment to start this server. To start the server run:
2259
```
2360
(venv)$ python app.py
2461
```
25-
To stop the server, do `Control-C`. Also, to exit your virtual environment, which is named `venv` run:
62+
63+
Note: This will remain a running process in your terminal, so you will need to open a new tab or window to execute other commands.
64+
65+
To stop the server, press `Control-C`.
66+
67+
To exit your virtual environment, which is named `venv`, run:
2668
```
27-
(venv)$ deactivate venv
69+
(venv)$ deactivate venv
2870
```
2971

30-
## Exercises
31-
This creates an application instance
32-
__name__ is used to determine the root path of the application folder
33-
34-
```python
35-
from flask import Flask
36-
app = Flask(__name__)
72+
Before you make any changes to the code, make sure to create a new branch. Typically branches are named based on the feature or bugfix being addressed, but for this project, name your branch with your own name so your reviewer can easily follow:
73+
```
74+
git checkout -b <YOUR_NAME>
3775
```
76+
Branch names should be all lowercase and can't contain spaces. Instead of spaces, use hyphens. For example:
77+
```
78+
git checkout -b varun-munjeti
79+
```
80+
81+
### Running The Server And Calling Endpoints
82+
Starting the server will make it a continuously running process on `localhost:5000`. In order to make requests to your server, use [Postman](https://www.getpostman.com/).
3883

39-
Running the Server:
84+
First, make a `GET` request to the `/` endpoint. Since the server is running on `localhost:5000`, the full endpoint url is `localhost:5000/`.
4085

41-
```python
42-
if __name__ == '__main__':
43-
app.run(debug=True)
86+
![Postman GET](https://lh3.googleusercontent.com/OoYCfIN8P18QWgOdqEk9RVpAp_AFR0P53JYJbhC5wS-nipfiP-7H0PncamS6xNxoFwBMfsikWch6Sg=w2880-h1598-rw)
87+
88+
Try calling the `/mirror` endpoint. First, look at the code for the endpoint to see how you can specify url parameters. Then make a request on Postman to `localhost:5000/mirror/<name>`:
89+
90+
![Postman GET mirror](https://lh5.googleusercontent.com/lwMNP5HUGC2EKe82muv0AJnc55xPkR-vDayI5z1oxIkbC4MkdSqnKi8KwXlOEsJsyyvICYWeK4uHBA=w2880-h1598-rw)
91+
92+
# Exercises
93+
These exercises will walk you through creating a RESTful API using Flask! We don't want you to go through all the hassle of setting up a database instance, so we have created dummy data and a mock database interface to interact with it. For the sake of ease, the entire app logic minus the mockdb logic will by implemented in `app.py`. For larger projects, the API endpoints will usually be separated out into different files called `views`.
94+
95+
Before you start, take a good look at the `create_response` function and how it works. Make sure you follow the guidelines for how to use this function, otherwise your API will not follow the proper conventions!
96+
97+
Also take a look into the mock database. The initial dummy data is defined in `mockdb/dummy_data.py`. This is what will "exist" in the "database" when you start the server.
98+
99+
The functions defined in `mockdb/mockdb_interface.py` are how you can query the mockdb. In `app.py`, where you will be writing your API, this has been imported with the name `db`. Therefore when you write the code for your endpoints, you can call the db interface functions like `db.get('users')`.
100+
101+
When you modify your code, the server will automatically update, *unless* your code doesn't compile, in which case the server will stop running and you have to manually restart it after fixing your code.
102+
103+
## Part 1
104+
Define the endpoint:
105+
```
106+
GET /users
44107
```
45108

46-
App routes define the path to different pages in your application. This means that when you run python app.py, on http://127.0.0.1:5000/ it will run the function `my_first_route` that will print hello world.
47-
```python
48-
@app.route('/')
49-
def my_first_route():
50-
return "<h1> Hello World! </h1>"
109+
This should return a properly formatted JSON response that contains a list of all the `user`s in the mockdb. If you call this endpoint immediately after starting the server, you should get this response in Postman:
110+
```
111+
{
112+
"code": 200,
113+
"message": "",
114+
"result": {
115+
"users": [
116+
{
117+
"age": 19,
118+
"id": 1,
119+
"name": "Aria",
120+
"team": "LWB"
121+
},
122+
{
123+
"age": 20,
124+
"id": 2,
125+
"name": "Tim",
126+
"team": "LWB"
127+
},
128+
{
129+
"age": 23,
130+
"id": 3,
131+
"name": "Varun",
132+
"team": "NNB"
133+
},
134+
{
135+
"age": 24,
136+
"id": 4,
137+
"name": "Alex",
138+
"team": "C2TC"
139+
}
140+
]
141+
},
142+
"success": true
143+
}
51144
```
52-
You can have multiple routes. So for instance, the code below would run on http://127.0.0.1:5000/route/aria,
53-
"aria" in this case is the parameter name, which can be anything you want. This is taken as an a input into the function my_second_route, and then the name is printed to the screen.
54145

55-
```python
56-
@app.route('/route/<name>')
57-
def my_second_route(name):
58-
return name
146+
## Part 2
147+
Define the endpoint:
148+
```
149+
GET /users/<id>
59150
```
60151

61-
**Problem 1**
62-
**Write a route that takes a first name, last name, and graduating year in the route. If this route is hit, wit print out the line `<firstname> <lastname> will graduate in <graduating_year>`**
152+
This should retrieve a single user that has the `id` provided from the request.
63153

154+
If there doesn't exist a user with the provided `id`, return a `404` with a descriptive `message`.
64155

65-
So, what are we using Flask for and why are routes useful ... to build an API.
156+
## Part 3
157+
Extend the first `/users` enpoint by adding the ability to query the users based on the team they are on. You should *not* use a url parameter like you did in Part 2. Instead, use a [query string](https://en.wikipedia.org/wiki/Query_string).
66158

67-
An API, or Application Programming Interface, is a set of subroutine definitions, protocols, and tools for building application software. It defines communication between various software components.
159+
If `team` is provided as a query string parameter, only return the users that are in that team. If there are no users on the provided `team`, return an empty list.
68160

69-
Lets give an example. Let's say on the frontend you want to display all a list of names that are stored in your database. You are going to send a GET request that will be sent to one of these routes that you define in Flask. The function to handle the route will understand that you are trying to get some information, retrieve it from the database, and set in back to the frontend in a json format.
161+
For this exercise, you can ignore any query string parameters other than `team`.
70162

163+
In Postman, you can supply query string parameters writing the query string into your request url or by hitting the `Params` button next to `Send`. Doing so will automatically fill in the request url.
71164

72-
The `GET` request is part of a protocol called REST, which stands for Representational State Transfer.
165+
![Postman Query String Request](https://lh3.googleusercontent.com/ESHTpXvW5xZa4jtT7_sn4dVbB000nQQq8T6ejGYDvEC-adJ9WplSuhEhMraijmldebjZ_smrnLAt6Q=w2880-h1598-rw)
73166

74-
There are many types of requests, put the most important ones are:
167+
## Part 4
168+
Define the endpoint:
169+
```
170+
POST /users
171+
```
75172

76-
`GET`: gets information from a database
173+
This endpoint should create a new user. Each request should also send a `name`, `age`, and `team` parameter in the request's `body`. The `id` property will be created automatically in the mockdb.
77174

78-
`POST`: adds information to a database
175+
A successful request should return a status code of `201` and return the newly created user.
79176

80-
`PUT`: modifies information in a database
177+
If any of the three required parameters aren't provided, return a `422` and a useful `message`. In general, your messages should provide the user/developer useful feedback on what they did wrong and how they can fix it.
81178

82-
`DELETE`: deletes information in a database
179+
This is how you can send `body` parameters from Postman. Make sure you don't mistake this for query parameters!
180+
![Postman POST](https://lh6.googleusercontent.com/suUZy0RIw0YyB87IymmSF2LZBKLt_RicE4Z1Nzm6gptqeN-FH5GTDlDHuFQ4yekamuw7Xc7m8FCvOA=w2880-h1598-rw)
83181

84-
From the nnb project from last semester, you can see an example of a get request that uses postgress database. Maps.query.all() goes into postgress, finds the table labeled `Maps`, and gets everything. The data is then put into a list and turned into a json object. If it fails, it will send the correct error message
85-
```python
86-
#Gets all maps
87-
@app.route('/maps', methods=['GET'])
88-
def getallyears():
89-
if request.method == 'GET':
90-
try:
91-
print(len(Maps.query.all()))
92-
return jsonify({'status': 'success', 'data': serializeList((Maps.query.all()))})
93-
except Exception as ex:
94-
raise InvalidUsage('Error: ' + str(ex), status_code=404)
95-
else:
96-
return jsonify({"status": "failed", "message": "Endpoint, /years, needs a GET request"})
182+
## Part 5
183+
Define the endpoint:
97184
```
98-
99-
Here's a POST request example from the same project:
100-
```python
101-
#Add a map
102-
@app.route('/maps', methods=['POST'])
103-
# @login_required
104-
def addmapforyear():
105-
if request.method == 'POST':
106-
try:
107-
json_dict = json.loads(request.data)
108-
result = Maps(
109-
image_url = json_dict['image_url'],
110-
year = (int)(json_dict['year'])
111-
)
112-
db.session.add(result)
113-
db.session.commit()
114-
return jsonify({"status": "success", "message": "successfully added maps and year"})
115-
except Exception as ex:
116-
raise InvalidUsage('Error: ' + str(ex), status_code=404)
117-
else:
118-
return jsonify({"status": "failed", "message": "Endpoint, /maps, needs a GET or POST request"})
185+
PUT /users/<id>
119186
```
120187

121-
Everything that I described above is what you're going to be working on in the Flask backend. This means figuring out how to design your database, and then define the API to make changes in your database.
188+
Here we need to provide a user's `id` since we need to specify which user to update. The `body` for this request should contain the same attributes as the `POST` request from Part 4.
122189

190+
However, the difference with this `PUT` request is that only values with the provided keys (`name`, `age`, `team`) will be updated, and any parameters not provided will not change the corresponding attribute in the user being updated.
123191

192+
You do not need to account for `body` parameters provided that aren't `name`, `age`, or `team`.
124193

125-
**Problem 2:**
194+
If the user with the provided `id` cannot be found, return a `404` and a useful `message`.
126195

127-
**So instead of making you guys actually use a database, simply make an array called *users* thats global in your app.py file. Each element in the array is a user with a id, name, and age**
196+
## Part 6
197+
Define the endpoint:
198+
```
199+
DELETE /users/<id>
200+
```
128201

129-
For example
130-
```json
202+
This will delete the user with the associated `id`. Return a useful `message`, although nothing needs to be specified in the response's `result`.
131203

132-
users = [
133-
{
134-
"id": 1,
135-
"name": "Aria",
136-
"age": 19
137-
},
138-
{
139-
"id": 2,
140-
"name": "Tim",
141-
"age": 20
142-
},
143-
{
144-
"id": 3,
145-
"name": "Varun",
146-
"age": 23
147-
},
148-
{
149-
"id": 4,
150-
"name": "Alex",
151-
"age": 24
152-
}
153-
]
154-
```
204+
If the user with the provided `id` cannot be found, return a `404` and a useful `message`.
155205

156-
**Then create a route for `/get_all_users` that will receive a GET request and return the list of all current users in a json format. It will return an error message for everything other than a GET request.**
206+
## Submitting
207+
When you're done with all the steps, open a pull request (PR) and assign your tech lead to review it!
157208

158-
**Next create a route called `/add_user` that will receieve a POST request. Inside the request data there will be a user with an id, name, and age. The function will take the request data and add a new user to the globale list of users. Also, add appropriate success/error responses in a json format.**
209+
Before you can submit a PR, you'll have to push your branch to a remote branch (the one that's on GitHub, not local).
159210

160-
**Next create a route called `/modify_user` that will receieve a PUT request. In the request data have an id so they know which user is being modified, and then have a new name or age for the user. In the function, edit the user with that id in the global list of users. Also, add appropriate success/error responses in a json format.**
211+
Check to see that you're on your branch:
212+
```
213+
git branch
214+
```
161215

162-
**Next create a route called `/delete_user` that will receieve a DELETE request and a name. The request data will have an id,and then that user is deleted from teh global array. Also, add appropriate sucess/error responses in a json format.**
216+
If you want to make sure all of your commits are in:
217+
```
218+
git log
219+
```
220+
Press `Q` to quit the `git log` screen.
163221

164-
**To test everything, download postman and make requests**
222+
Push your commits to your remote branch:
223+
```
224+
git push
225+
```
165226

166-
Setting up the database and defining it is alot of work, so we'll leave that for your tech leads to teach you. Also, for the course of this intro project, we're doing everything in app.py. **In your projects though, you are going to organize the endpoints into different files, have a folder to define the models, and other files for the database connection. **
227+
The first time you do this, you might get an error since your remote branch doesn't exist yet. Usually it will tell you the correct command to use:
228+
```
229+
git push --set-upstream origin <YOUR_BRANCH_NAME>
230+
```
231+
Note: this only needs to be done the first time you push a new branch. You can use just `git push` afterwards.
167232

233+
Follow the instructions on the [wiki](https://github.com/hack4impact-uiuc/wiki/wiki/Git-Reference-Guide#opening-a-pull-request-pr-on-github) to open the PR.
168234

169-
## Message Shreyas for help but please use the channel #backend :)
235+
Note: make sure that you don't actually merge your PR in! We are only using it as a mechanism for providing code reviews.

0 commit comments

Comments
 (0)