Skip to content

Commit c7f4571

Browse files
Merge pull request #81 from josemoracard/jose3-05-returning-json
exercises 05-returning-json to 08.2-finish-todos
2 parents 0389b22 + 9e099c9 commit c7f4571

File tree

24 files changed

+115
-120
lines changed

24 files changed

+115
-120
lines changed

.learn/exercises/05-returning-json/README.es.md

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,25 @@
22

33
Las REST APIs tienen que retornar datos en formato JSON, no en formato HTML.
44

5-
Puedes usar la función [flask jsonify](https://flask.palletsprojects.com/en/1.1.x/api/#flask.json.jsonify) para convertir con facilidad cualquier tipo de datos básico a JSON de esta forma:
5+
Puedes usar la función [flask jsonify](https://flask.palletsprojects.com/en/3.0.x/api/#flask.json.jsonify) para convertir con facilidad cualquier tipo de datos básico a JSON de esta forma:
66

77
```python
8-
# añade el método jsonify a tu importación de Flask
9-
from flask import Flask, jsonify
8+
# Añade el método jsonify a tu importación de Flask
9+
from flask import Flask, jsonify
1010

11-
# supongamos que tienes tus datos en la variable some_data
12-
some_data = { "name": "Bobby", "lastname": "Rixer" }
11+
# Supongamos que tienes tus datos en la variable some_data
12+
some_data = { "name": "Bobby", "lastname": "Rixer" }
1313

14-
@app.route('/blahblah', methods=['GET'])
14+
@app.route('/myroute', methods=['GET'])
1515
def hello_world():
16-
# puedes convertir esa variable en una cadena json de la siguiente manera
16+
# Puedes convertir esa variable en una cadena json de la siguiente manera
1717
json_text = jsonify(some_data)
1818

19-
# y luego puedes devolverlo al front-end en el cuerpo de la respuesta de la siguiente manera
19+
# Y luego puedes devolverlo al front-end en el cuerpo de la respuesta de la siguiente manera
2020
return json_text
2121
```
2222

23-
Si aplicamos estos conocimientos a nuestro proyecto de todo-list, podemos crear una variable global `todos` que va a contener la lista de todos de esta forma:
23+
Si aplicamos estos conocimientos a nuestro proyecto de todo-list, podemos crear una variable global `todos` que va a contener la lista de todos de esta forma:
2424

2525
```python
2626
todos = [
@@ -29,12 +29,12 @@ todos = [
2929
]
3030
```
3131

32-
## 📝 Instrucciones
32+
## 📝 Instrucciones:
3333

34-
1. Crea una variable global todos, declárala globalmente. No la declares dentro de una función, declárala en cualquier lado pero a nivel global. Asegúrate de que la variable contenga por lo menos una tarea (task) con la siguiente estructura:
34+
1. Crea una variable global `todos`, declárala globalmente. No la declares dentro de una función, declárala en cualquier lado pero a nivel global. Asegúrate de que la variable contenga por lo menos una tarea (task) con la siguiente estructura:
3535

3636
```python
37-
{ "label": "My first task", "done": False }
37+
[ { "label": "My first task", "done": False } ]
3838
```
3939

4040
2. Cambia la función del endpoint de tu método GET para que retorne la versión en json (Usando jsonify) de la variable de `todos` recién creada.

.learn/exercises/05-returning-json/README.md

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,25 @@
22

33
REST APIs have to return data in JSON format, not HTML format.
44

5-
You can use the [flask jsonify](https://flask.palletsprojects.com/en/1.1.x/api/#flask.json.jsonify) function to easily convert any of the basic data-types to JSON data like this:
5+
You can use the [flask jsonify](https://flask.palletsprojects.com/en/3.0.x/api/#flask.json.jsonify) function to easily convert any of the basic data-types to JSON data, like this:
66

77
```python
8+
# Add the jsonify method to your Flask import
9+
from flask import Flask, jsonify
810

9-
# add the jsonify method to your Flask import
10-
from flask import Flask, jsonify
11-
12-
# suppose you have your data in the variable named some_data
13-
some_data = { "name": "Bobby", "lastname": "Rixer" }
11+
# Suppose you have your data in the variable named some_data
12+
some_data = { "name": "Bobby", "lastname": "Rixer" }
1413

1514
@app.route('/myroute', methods=['GET'])
1615
def hello_world():
17-
# you can convert that variable into a json string like this
16+
# You can convert that variable into a json string like this
1817
json_text = jsonify(some_data)
1918

20-
# and then you can return it to the front end in the response body like this
19+
# And then you can return it to the front end in the response body like this
2120
return json_text
2221
```
2322

24-
If we apply this knowledge to our ToDo-list project, we can create a global variable named `todos` that will hold the list of todos like this:
23+
If we apply this knowledge to our todo-list project, we can create a global variable named `todos` that will hold the list of todos like this:
2524

2625
```python
2726
todos = [
@@ -30,12 +29,12 @@ todos = [
3029
]
3130
```
3231

33-
## 📝Instructions:
32+
## 📝 Instructions:
3433

3534
1. Create a global variable called `todos`. Do not declare the variable inside any function. Declare the variable in the global scope and make sure the variable contains at least one task item (our task objects) inside with the following structure:
3635

3736
```python
3837
[ { "label": "My first task", "done": False } ]
3938
```
4039

41-
2. Change the function on the GET method's endpoint from string output so that it will return the jsonified version of the global variable `todos`.
40+
2. Change the function on the GET method's endpoint from string output so that it will return the jsonified version of the global variable `todos`.

.learn/exercises/05-returning-json/solution.hide.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,6 @@
77
def hello_world():
88
return jsonify(todos)
99

10-
# These two lines should always be at the end of your app.py file.
10+
# These two lines should always be at the end of your app.py file
1111
if __name__ == '__main__':
12-
app.run(host='0.0.0.0', port=3245, debug=True)
12+
app.run(host='0.0.0.0', port=3245, debug=True)

.learn/exercises/05-returning-json/test.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@ def client():
1616
os.close(db_fd)
1717
os.unlink(app.config['DATABASE'])
1818

19-
@pytest.mark.it("folder src must exist")
19+
@pytest.mark.it("Folder src must exist")
2020
def test_src_folder():
2121
assert os.path.isdir("./src/")
2222

23-
@pytest.mark.it("app.py must exist")
23+
@pytest.mark.it("File app.py must exist")
2424
def test_pipfile_exists():
2525
assert os.path.isfile("src/app.py")
2626

@@ -63,7 +63,7 @@ def test_labels_string():
6363
if "label" in task:
6464
assert isinstance(task["label"], str)
6565

66-
@pytest.mark.it('The value of the "done" key on each todo should be boolean')
66+
@pytest.mark.it('The value of the "done" key on each todo should be a boolean')
6767
def test_done_bool():
6868
from src import app
6969
for task in app.todos:
@@ -84,4 +84,4 @@ def test_return(client):
8484

8585
for task in _body:
8686
assert "label" in task
87-
assert "done" in task
87+
assert "done" in task
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# `06` Check the API
22

3-
Now you can check your endpoint live in the browser. It should be returning the list of todos in JSON format like this:
3+
Now you can check your endpoint live in the browser. It should be returning the list of todos in JSON format, like this:
44

55
![check live todos](../../assets/return_todos.gif?raw=true)

.learn/exercises/07-post_todo/README.es.md

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# `07` POST /todos (añade un nuevo task)
1+
# `07` POST /todos (add a new task)
22

33
Ahora que ya está hecho el método GET `/todos`, debemos pensar en el resto de los endpoints de nuestra API:
44

@@ -8,26 +8,23 @@ POST /todos
88
DELETE /todos
99
```
1010

11-
Para poder construir el `POST /todos` debemos hacer algo similar a lo que hicimos en el primer endpoint, recuerda que cada endpoint en una Flask API está representada por una función y decorador como este:
11+
Para poder construir el `POST /todos` debemos hacer algo similar a lo que hicimos en el primer endpoint, recuerda que cada endpoint en una Flask API está representada por una función y un decorador de esta manera:
1212

1313
```python
14-
@app.route('/blabla', methods=['GET'])
14+
@app.route('/myroute', methods=['GET'])
1515
def hello_world():
16-
return 'Hello, World!'
16+
return 'Hello World!'
1717
```
1818

19-
Pero en este caso no esperaremos una solicitud `GET`.
19+
Pero en este caso no esperaremos una solicitud `GET`, sino una solicitud `POST`.
2020

21-
También, esperamos recibir el `todo` (tarea) que el cliente quiere añadir dentro del `request_body` (cuerpo de la solicitud), solo que en este caso, no esperaremos una `request`(solicitud) `GET`.
22-
23-
Esperamos recibir el `todo` que el cliente desea añadir dentro del `request_body`.
21+
También, esperamos recibir el TODO que el cliente quiere añadir dentro del `request_body` (cuerpo de la solicitud).
2422

2523
```python
2624
from flask import request
2725

28-
# el request_body o cuerpo de la solicitud ya fue decodificado por json y se encuentra en la variable request.data
29-
30-
print(request.data)
26+
# El request_body o cuerpo de la solicitud ya está decodificado en formato JSON y se encuentra en la variable request.json
27+
print(request.json)
3128
```
3229

3330
## 📝 Instrucciones:
@@ -37,7 +34,7 @@ print(request.data)
3734
```python
3835
@app.route('/todos', methods=['POST'])
3936
def add_new_todo():
40-
request_body = request.data
37+
request_body = request.json
4138
print("Incoming request with the following body", request_body)
4239
return 'Response for the POST todo'
4340
```

.learn/exercises/07-post_todo/README.md

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,12 @@ POST /todos
88
DELETE /todos
99
```
1010

11-
In order to build the `POST /todos` endpoint, we have to do something similar to what we did in the first endpoint with our GET method. Remember that each endpoint in a Flask API is represented by a function ( def my_function(): ) and a decorator ( @app.route() ) like this:
11+
In order to build the `POST /todos` endpoint, we have to do something similar to what we did in the first endpoint with our GET method. Remember that each endpoint in a Flask API is represented by decorator and a function, like this:
1212

1313
```python
1414
@app.route('/myroute', methods=['GET'])
1515
def hello_world():
16-
return 'Hello, World!'
16+
return 'Hello World!'
1717
```
1818

1919
In this case, we are not going to be expecting a `GET` request, but rather a `POST` request.
@@ -23,24 +23,26 @@ Also, we are expecting to receive the TODO that the client wants to add inside o
2323
```python
2424
from flask import request
2525

26-
# the request body is already json decoded and it comes in the request.json variable
26+
# The request body is already JSON decoded, and it comes in the request.json variable
2727
print(request.json)
2828
```
2929

3030
## 📝 Instructions:
3131

32-
1. Remember to import `request` at the top of the file:
33-
34-
```python
35-
from flask import request
36-
```
37-
38-
2. Then, Add the folowing endpoint to your app.py and test it:
32+
1. Add the following endpoint to your `app.py` and test it:
3933

4034
```python
4135
@app.route('/todos', methods=['POST'])
4236
def add_new_todo():
43-
request_body = request.data
37+
request_body = request.json
4438
print("Incoming request with the following body", request_body)
4539
return 'Response for the POST todo'
4640
```
41+
42+
2. Remember to import `request` at the top of the file:
43+
44+
```python
45+
from flask import request
46+
```
47+
48+

.learn/exercises/07-post_todo/solutions.hide.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,11 @@ def hello_world():
99

1010
@app.route('/todos', methods=['POST'])
1111
def add_new_todo():
12-
request_body = request.data
12+
request_body = request.json
1313
print("Incoming request with the following body", request_body)
1414
return 'Response for the POST todo'
1515

1616

17-
# These two lines should always be at the end of your app.py file.
17+
# These two lines should always be at the end of your app.py file
1818
if __name__ == '__main__':
19-
app.run(host='0.0.0.0', port=3245, debug=True)
19+
app.run(host='0.0.0.0', port=3245, debug=True)

.learn/exercises/07-post_todo/test.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@ def client():
1616
os.close(db_fd)
1717
os.unlink(app.config['DATABASE'])
1818

19-
@pytest.mark.it("folder src must exist")
19+
@pytest.mark.it("Folder src must exist")
2020
def test_src_folder():
2121
assert os.path.isdir("./src/")
2222

23-
@pytest.mark.it("app.py must exist")
23+
@pytest.mark.it("File app.py must exist")
2424
def test_pipfile_exists():
2525
assert os.path.isfile("src/app.py")
2626

@@ -63,7 +63,7 @@ def test_labels_string():
6363
if "label" in task:
6464
assert isinstance(task["label"], str)
6565

66-
@pytest.mark.it('The value of the "done" key on each todo should be boolean')
66+
@pytest.mark.it('The value of the "done" key on each todo should be a boolean')
6767
def test_done_bool():
6868
from src import app
6969
for task in app.todos:

.learn/exercises/07.1-test-post-todo/README.es.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ Hasta ahora esto lo que tienes sobre el endpoint `POST /todos`, tomate el tiempo
55
```python
66
@app.route('/todos', methods=['POST'])
77
def add_new_todo():
8-
request_body = request.data
8+
request_body = request.json
99
print("Incoming request with the following body", request_body)
1010
return 'Response for the POST todo'
1111
```

0 commit comments

Comments
 (0)