diff --git a/.gitignore b/.gitignore index 09609ff..22f8747 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ !/exercises !/exercises/* +exercises/*/__pycache__/ !/.learn /.learn/** diff --git a/exercises/00-hello-world/README.es.md b/exercises/00-hello-world/README.es.md deleted file mode 100644 index 30f83f8..0000000 --- a/exercises/00-hello-world/README.es.md +++ /dev/null @@ -1,13 +0,0 @@ -# Python API Requests - -Python Requests es el paquete más popular para consumir API y hacer solicitudes HTTP. - -Aquí aprenderás: - -1. Cómo hacer solicitudes GET. -2. Cómo obtener propiedades de una data e información. -3. Cómo configurar request headers. -4. Cómo configurar request content-type. -5. Cómo hacer solicitudes POST. - -Haga click en el botón `next →` en la esquina superior derecha para continuar. \ No newline at end of file diff --git a/exercises/00-hello-world/README.md b/exercises/00-hello-world/README.md deleted file mode 100644 index 3cb9e7e..0000000 --- a/exercises/00-hello-world/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# Python API Requests - -Python Requests is the most popular package for consuming API's and doing HTTP requests. - -Here you will learn: - -1. How to do GET requests. -2. How to fech data properties and information. -3. How to set request headers. -4. How to set request content-type. -5. How to do POST requests. - -Click the `next →` button on the top right to continue. \ No newline at end of file diff --git a/exercises/00-welcome/README.es.md b/exercises/00-welcome/README.es.md new file mode 100644 index 0000000..51c6c3d --- /dev/null +++ b/exercises/00-welcome/README.es.md @@ -0,0 +1,15 @@ +# `00` Welcome to Python API Requests! + +Python Requests es una herramienta potente y ampliamente utilizada para interactuar con APIs y realizar solicitudes HTTP en aplicaciones Python. Simplifica el proceso de enviar solicitudes HTTP y manejar respuestas, convirtiéndose en una herramienta favorita entre los desarrolladores para integrarse con servicios web y obtener datos de APIs. + +Con Python Requests, puedes hacer fácilmente solicitudes GET, POST, PUT, DELETE para comunicarte con servidores web y obtener datos. Admite el manejo de autenticación, encabezados, cookies y sesiones, permitiendo una integración sin problemas con diversos servicios web. + +Aquí aprenderás: + +1. ¿Cómo hacer solicitudes GET? +2. ¿Cómo obtener propiedades de datos e información? +3. ¿Cómo configurar request headers? +4. ¿Cómo configurar request content-type? +5. ¿Cómo hacer solicitudes POST? + +Haga clic en el botón `Next →` en la esquina superior derecha para continuar. diff --git a/exercises/00-welcome/README.md b/exercises/00-welcome/README.md new file mode 100644 index 0000000..14b765e --- /dev/null +++ b/exercises/00-welcome/README.md @@ -0,0 +1,15 @@ +# `00` Welcome to Python API Requests! + +Python Requests is a powerful and widely-used package for interacting with APIs and performing HTTP requests in Python applications. It simplifies the process of sending HTTP requests and handling responses, making it a favorite tool among developers for integrating with web services and fetching data from APIs. + +With Python Requests, you can easily make GET, POST, PUT, DELETE, to communicate with web servers and retrieve data. It supports handling authentication, headers, cookies, and sessions, allowing for seamless integration with various web services. + +Here you will learn: + +1. How to do GET requests? +2. How to fetch data properties and information? +3. How to set request headers? +4. How to set request content-type? +5. How to do POST requests? + +Click the `Next →` button on the top right to continue. diff --git a/exercises/01-creating-a-request/README.es.md b/exercises/01-creating-a-request/README.es.md new file mode 100644 index 0000000..652d819 --- /dev/null +++ b/exercises/01-creating-a-request/README.es.md @@ -0,0 +1,20 @@ +# `01` Creating a Request + +Python tiene integrado un [paquete de solicitudes (*requests package*)](https://requests.readthedocs.io/en/master/) eso permite a los desarrolladores crear solicitudes HTTP con bastante facilidad. + +Así es como en Python hacemos una solicitud HTTP GET: + +```python +response = requests.get('') +print(response.status_code) +``` + +## 📝 Instrucciones: + +Actualiza la variable `url` para que solicite a esta dirección: + +```bash +https://assets.breatheco.de/apis/fake/sample/hello.php +``` + +> Nota: La consola debe imprimir un código de estado 200. \ No newline at end of file diff --git a/exercises/01-what-is-a-request/README.md b/exercises/01-creating-a-request/README.md similarity index 66% rename from exercises/01-what-is-a-request/README.md rename to exercises/01-creating-a-request/README.md index 7b1fb42..6ff6b36 100644 --- a/exercises/01-what-is-a-request/README.md +++ b/exercises/01-creating-a-request/README.md @@ -1,4 +1,4 @@ -# 01 Creating a request +# `01` Creating a Request Python has a [requests package](https://requests.readthedocs.io/en/master/) that allows developers to create HTTP request pretty easily. @@ -9,12 +9,12 @@ response = requests.get('') print(response.status_code) ``` -# 📝 Instructions +## 📝 Instructions: -Change the variable url to make it request to: +Update the `url` variable to make it request to this address: -```bash +```text https://assets.breatheco.de/apis/fake/sample/hello.php ``` -Note: The console should print a 200 status code. \ No newline at end of file +> Note: The console should print a 200 status code. \ No newline at end of file diff --git a/exercises/01-what-is-a-request/app.py b/exercises/01-creating-a-request/app.py similarity index 100% rename from exercises/01-what-is-a-request/app.py rename to exercises/01-creating-a-request/app.py diff --git a/exercises/01-creating-a-request/solution.hide.py b/exercises/01-creating-a-request/solution.hide.py new file mode 100644 index 0000000..4834ba5 --- /dev/null +++ b/exercises/01-creating-a-request/solution.hide.py @@ -0,0 +1,6 @@ +import requests + +url = "https://assets.breatheco.de/apis/fake/sample/hello.php" +response = requests.get(url) + +print("The response status is: "+str(response.status_code)) \ No newline at end of file diff --git a/exercises/01-what-is-a-request/test.py b/exercises/01-creating-a-request/test.py similarity index 100% rename from exercises/01-what-is-a-request/test.py rename to exercises/01-creating-a-request/test.py diff --git a/exercises/01-what-is-a-request/README.es.md b/exercises/01-what-is-a-request/README.es.md deleted file mode 100644 index e959289..0000000 --- a/exercises/01-what-is-a-request/README.es.md +++ /dev/null @@ -1,20 +0,0 @@ -# 01 Creando una solicitud (request) - -Python tiene un [paquete de solicitud (requests package)](https://requests.readthedocs.io/en/master/) eso permite a los desarrolladores crear solicitudes HTTP con bastante facilidad. - -Así es como en Python hacemos una solicitud HTTP GET: - -```python -response = requests.get('') -print(response.status_code) -``` - -# 📝 Instrucciones - -Cambie la variable URL para que solicite: - -```bash -https://assets.breatheco.de/apis/fake/sample/hello.php -``` - -Nota: La consola debe imprimir un código de estado 200. \ No newline at end of file diff --git a/exercises/02-random-status/README.es.md b/exercises/02-random-status/README.es.md index a1a3d54..e670821 100644 --- a/exercises/02-random-status/README.es.md +++ b/exercises/02-random-status/README.es.md @@ -1,14 +1,15 @@ -# `02` Manejar el Status de Respuesta +# `02` Handle Response Status La siguiente solicitud GET siempre devuelve un código de status diferente, nunca se sabe qué respuesta está recibiendo del servidor. -## 📝Instrucciones +## 📝 Instrucciones: Crea una condición para imprimir en la consola los siguientes mensajes según el status de respuesta: -| Status | Message | +| Status | Mensaje | | ----- | ----- | -| 404 | The URL you asked is not found | +| 404 | The URL you asked for is not found | | 503 | Unavailable right now | | 200 | Everything went perfect | -| 400 | Something is wrong on the request params | \ No newline at end of file +| 400 | Something is wrong with the request params | +| Otro código de status | Unknown status code | \ No newline at end of file diff --git a/exercises/02-random-status/README.md b/exercises/02-random-status/README.md index 7cbf29c..93df280 100644 --- a/exercises/02-random-status/README.md +++ b/exercises/02-random-status/README.md @@ -1,15 +1,15 @@ # `02` Handle Response Status -The following GET request is always returning a different status code, you never know what reponse you are getting form the server. +The following GET request is always returning a different status code; you never know what response you are getting from the server. -## 📝Instructions +## 📝 Instructions: -Create a condition to print on the console the following messages depending on the response status: +Create a condition to print on the console the following messages, depending on the response status: | Status | Message | | ----- | ----- | -| 404 | The URL you asked is not found | +| 404 | The URL you asked for is not found | | 503 | Unavailable right now | | 200 | Everything went perfect | -| 400 | Something is wrong on the request params | -| anything else | anything | \ No newline at end of file +| 400 | Something is wrong with the request params | +| Any other code | Unknown status code | \ No newline at end of file diff --git a/exercises/02-random-status/solution.hide.py b/exercises/02-random-status/solution.hide.py new file mode 100644 index 0000000..c5f53cb --- /dev/null +++ b/exercises/02-random-status/solution.hide.py @@ -0,0 +1,14 @@ +import requests + +response = requests.get("https://assets.breatheco.de/apis/fake/sample/random-status.php") + +if response.status_code == 404: + print("The URL you asked for is not found") +elif response.status_code == 503: + print("Unavailable right now") +elif response.status_code == 200: + print("Everything went perfect") +elif response.status_code == 400: + print("Something is wrong with the request params") +else: + print("Unknown status code") \ No newline at end of file diff --git a/exercises/02-random-status/test.py b/exercises/02-random-status/test.py index e552c51..9e774ac 100644 --- a/exercises/02-random-status/test.py +++ b/exercises/02-random-status/test.py @@ -16,13 +16,13 @@ def test_url_200(capsys, app): captured = capsys.readouterr() assert "Everything went perfect\n" == captured.out -@pytest.mark.it("When testing for 404 it should print The URL you asked is not found'") +@pytest.mark.it("Testing for 404: The URL you asked for is not found'") def test_url_404(capsys, app): with patch('requests.get') as mock_request: mock_request.return_value.status_code = 404 app() captured = capsys.readouterr() - assert "The URL you asked is not found\n" == captured.out + assert "The URL you asked for is not found\n" == captured.out @pytest.mark.it("Testing for 503: Unavailable right now") def test_url_503(capsys, app): @@ -32,10 +32,18 @@ def test_url_503(capsys, app): captured = capsys.readouterr() assert "Unavailable right now\n" == captured.out -@pytest.mark.it("Testing for 400: Something is wrong on the request params") +@pytest.mark.it("Testing for 400: Something is wrong with the request params") def test_url_400(capsys, app): with patch('requests.get') as mock_request: mock_request.return_value.status_code = 400 app() captured = capsys.readouterr() - assert "Something is wrong on the request params\n" == captured.out + assert "Something is wrong with the request params\n" == captured.out + +@pytest.mark.it("Testing for any other code: Unknown status code") +def test_url_generic_response(capsys, app): + with patch('requests.get') as mock_request: + mock_request.return_value.status_code = 500 # For example, using status code 500 for generic response + app() + captured = capsys.readouterr() + assert "Unknown status code\n" == captured.out \ No newline at end of file diff --git a/exercises/03-response-body/README.es.md b/exercises/03-response-body/README.es.md index 8e93d07..348bb72 100644 --- a/exercises/03-response-body/README.es.md +++ b/exercises/03-response-body/README.es.md @@ -1,14 +1,18 @@ -# `03` Respuesta en Body +# `03` Response Body Haga clic en este enlace para ver la respuesta que esta solicitud GET está dando en el body: [https://assets.breatheco.de/apis/fake/sample/random-status.php](https://assets.breatheco.de/apis/fake/sample/random-status.php) -Ahora, si deseas obtener ese body como respuesta (texto), todo lo que tiene que hacer es: +Ahora, si deseas obtener el *body* de la respuesta (texto/contenido), todo lo que tienes que hacer es: + ```py -# plain text print(response.text) ``` -# 📝 Instrucciones +## 📝 Instrucciones: + +Imprime en la consola el *body* de la respuesta solo para solicitudes con status `200`, para el resto imprime: -Imprime en la consola la the responde body solo para solicitudes 200, para el resto imprima "Something went wrong". \ No newline at end of file +```text +"Something went wrong" +``` \ No newline at end of file diff --git a/exercises/03-response-body/README.md b/exercises/03-response-body/README.md index abe927f..2f7d516 100644 --- a/exercises/03-response-body/README.md +++ b/exercises/03-response-body/README.md @@ -3,12 +3,16 @@ Click on this link to see the response body that this GET request is giving: [https://assets.breatheco.de/apis/fake/sample/random-status.php](https://assets.breatheco.de/apis/fake/sample/random-status.php) -Now, if you want to get that response body (text) all you have to do is: +Now, if you want to get that response body (text/content) all you have to do is this: + ```py -# plain text print(response.text) ``` -# 📝 Instructions +## 📝 Instructions: + +Print on the console the response body for status code `200`, for all the other print: -Print on the console the response body only for 200 requests, for all the other print "Something went wrong". \ No newline at end of file +```text +"Something went wrong" +``` \ No newline at end of file diff --git a/exercises/03-response-body/app.py b/exercises/03-response-body/app.py index 37cdac0..66b2f6b 100644 --- a/exercises/03-response-body/app.py +++ b/exercises/03-response-body/app.py @@ -1,3 +1,3 @@ import requests -url = "https://assets.breatheco.de/apis/fake/sample/random-status.php" \ No newline at end of file +url = "https://assets.breatheco.de/apis/fake/sample/random-status.php" diff --git a/exercises/03-response-body/solution.hide.py b/exercises/03-response-body/solution.hide.py new file mode 100644 index 0000000..9409dea --- /dev/null +++ b/exercises/03-response-body/solution.hide.py @@ -0,0 +1,10 @@ +import requests + +url = "https://assets.breatheco.de/apis/fake/sample/random-status.php" + +response = requests.get(url) + +if response.status_code == 200: + print(response.text) +else: + print("Something went wrong") \ No newline at end of file diff --git a/exercises/03-response-body/test.py b/exercises/03-response-body/test.py index c138063..09972c4 100644 --- a/exercises/03-response-body/test.py +++ b/exercises/03-response-body/test.py @@ -7,7 +7,7 @@ def test_url_call(capsys, app): app() mock_request.assert_called_once_with("https://assets.breatheco.de/apis/fake/sample/random-status.php") -@pytest.mark.it("Testing for 200: Everythign went perfect") +@pytest.mark.it("Testing for 200: Ok") def test_url_200(capsys, app): with patch('requests.get') as mock_request: mock_request.return_value.status_code = 200 @@ -16,7 +16,7 @@ def test_url_200(capsys, app): captured = capsys.readouterr() assert "something\n" == captured.out -@pytest.mark.it("When testing for 404 it should print 'Something went wrong'") +@pytest.mark.it("Testing for any other code: Something went wrong") def test_url_404(capsys, app): with patch('requests.get') as mock_request: mock_request.return_value.status_code = 404 diff --git a/exercises/04-response-body-json/README.es.md b/exercises/04-response-body-json/README.es.md index 5b00639..600a412 100644 --- a/exercises/04-response-body-json/README.es.md +++ b/exercises/04-response-body-json/README.es.md @@ -1,8 +1,8 @@ -# `04` Respuesta JSON +# `04` Response JSON Pero tener una respuesta basada en texto no es muy útil, es por eso que las API normalmente responden en formato CSV, JSON, YAML o XML. -# 📝 Instrucciones +## 📝 Instrucciones: El siguiente endpoint devuelve la hora actual en un formato JSON cada vez que se solicita utilizando el método GET. @@ -22,15 +22,15 @@ Response body: } ``` -Haga una solicitud GET a ese endpoint e imprima la hora en la consola con este formato: +1. Haz una solicitud GET a ese endpoint e imprime la hora en la consola con este formato: ```bash Current time: 17 hrs 06 min and 23 sec ``` -## 💡Pista +## 💡 Pistas: -1. Usa el [metodo .json()](https://www.w3schools.com/python/ref_requests_response.asp) para obtener el response body como un diccionario y almacenarlo en una variable -2. Obtenga las propiedades `horas`,` minutos` y `segundos` del diccionario -3. Concatenar todo de esta manera: `Hora actual: 17 h 06 min y 23 seg` ++ Usa el [metodo .json()](https://www.w3schools.com/python/ref_requests_response.asp) para obtener el response body como un diccionario y almacenarlo en una variable. ++ Obtenga las propiedades `hours`, `minutes` y `seconds` del diccionario. ++ Concatenar todo de esta manera: `Hora actual: 17 h 06 min y 23 seg`. diff --git a/exercises/04-response-body-json/README.md b/exercises/04-response-body-json/README.md index bdd7ddb..5e7e6db 100644 --- a/exercises/04-response-body-json/README.md +++ b/exercises/04-response-body-json/README.md @@ -1,8 +1,8 @@ # `04` Response JSON -But having a text based response is not very useful, that is why API's normally respond in CSV, JSON, YAML or XML format. +But having a text based response is not very useful, that is why APIs normally respond in CSV, JSON, YAML or XML format. -# 📝 Instructions +## 📝 Instructions: The following endpoint returns the current time in a JSON format every time it is requested using the GET method. @@ -22,15 +22,15 @@ Response body: } ``` -Please do a GET request to that endpoint and print the time on the console with this format: +1. Please do a GET request to that endpoint and print the time on the console with this format: -```bash +```text Current time: 17 hrs 06 min and 23 sec ``` -## 💡Hint +## 💡 Hints: -1. Use the [.json() method](https://www.w3schools.com/python/ref_requests_response.asp) to get the response body as a dictionary and store it in a variable -2. Get the `hours`, `minutes` and `seconds` properties from the dictionary -3. Concatenate everything together like this: `Current time: 17 hrs 06 min and 23 sec` ++ Use the [.json() method](https://www.w3schools.com/python/ref_requests_response.asp) to get the response body as a dictionary and store it in a variable. ++ Get the `hours`, `minutes` and `seconds` properties from the dictionary. ++ Concatenate everything together like this: `Current time: 17 hrs 06 min and 23 sec`. diff --git a/exercises/04-response-body-json/solution.hide.py b/exercises/04-response-body-json/solution.hide.py new file mode 100644 index 0000000..cc2f069 --- /dev/null +++ b/exercises/04-response-body-json/solution.hide.py @@ -0,0 +1,16 @@ +import requests + +response = requests.get("https://assets.breatheco.de/apis/fake/sample/time.php") + +if response.status_code == 200: + # Parsing JSON response + time_data = response.json() + + # Extracting hours, minutes, and seconds + hours = time_data["hours"] + minutes = time_data["minutes"] + seconds = time_data["seconds"] + + print(f"Current time: {hours} hrs {minutes} min and {seconds} sec") +else: + print("Failed to fetch current time.") \ No newline at end of file diff --git a/exercises/04-response-body-json/test.py b/exercises/04-response-body-json/test.py index 28031b9..a057d36 100644 --- a/exercises/04-response-body-json/test.py +++ b/exercises/04-response-body-json/test.py @@ -14,7 +14,7 @@ def test_url_call(capsys, app): app() mock_request.assert_called_once_with("https://assets.breatheco.de/apis/fake/sample/time.php") -@pytest.mark.it("You should print on the console a stirng like: Current time: 19 hrs 45 min and 06 sec") +@pytest.mark.it("You should print on the console a string like: Current time: 19 hrs 45 min and 06 sec") def test_url_output(capsys, app): with patch('requests.get') as mock_request: mock_request.return_value = FakeResponse() diff --git a/exercises/05-project-name/README.es.md b/exercises/05-project-name/README.es.md index 65ddfed..002f6e1 100644 --- a/exercises/05-project-name/README.es.md +++ b/exercises/05-project-name/README.es.md @@ -1,4 +1,4 @@ -# `05` Nombre de Proyecto +# `05` Project name El siguiente endpoint es ideal para recuperar proyectos de estudiantes: @@ -8,7 +8,7 @@ GET [https://assets.breatheco.de/apis/fake/sample/project1.php](https://assets.b { "name": "Coursera eLearning", "thumb": "https://unsplash.it/450/320?image=178", - "description": "The coolest elarning site on the planet", + "description": "The coolest eLearning site on the planet", "images": [ "https://unsplash.it/450/320?image=178", "https://unsplash.it/450/320?image=179", @@ -18,19 +18,19 @@ GET [https://assets.breatheco.de/apis/fake/sample/project1.php](https://assets.b } ``` -# 📝 Instrucciones +## 📝 Instrucciones: -Llama al endpoint e imprime el nombre del proyecto en el terminal (solo el nombre del proyecto) +1. Llama al endpoint e imprime el nombre del proyecto en el terminal (solo el nombre del proyecto). -Example output: -```bash +Ejemplo de salida: + +```text Coursera eLearning ``` -## 💡Pista +## 💡 Pistas: -1. Ejercicio similar al anterior. -2. Haz una solicitud GET al endpoint. -3. Usa el [metodo .json()](https://www.w3schools.com/python/ref_requests_response.asp) para obtener el response body como un diccionario (igual que lo hizo en el último ejercicio). -4. Imprime el nombre del proyecto, puedes acceder al nombre de la propiedad en el diccionario de respuestas. ++ Haz una solicitud GET al endpoint. ++ Usa el [metodo .json()](https://www.w3schools.com/python/ref_requests_response.asp) para obtener el response body como un diccionario (igual que en el último ejercicio). ++ Imprime el nombre del proyecto, puedes acceder al nombre de la propiedad en el diccionario de respuestas. diff --git a/exercises/05-project-name/README.md b/exercises/05-project-name/README.md index 2543185..7731838 100644 --- a/exercises/05-project-name/README.md +++ b/exercises/05-project-name/README.md @@ -8,7 +8,7 @@ GET [https://assets.breatheco.de/apis/fake/sample/project1.php](https://assets.b { "name": "Coursera eLearning", "thumb": "https://unsplash.it/450/320?image=178", - "description": "The coolest elarning site on the planet", + "description": "The coolest eLearning site on the planet", "images": [ "https://unsplash.it/450/320?image=178", "https://unsplash.it/450/320?image=179", @@ -18,19 +18,19 @@ GET [https://assets.breatheco.de/apis/fake/sample/project1.php](https://assets.b } ``` -# 📝 Instructions +## 📝 Instructions: -Please call the endpoint and print the project name on the terminal (only the project name) +1. Please call the endpoint and print the project name on the terminal (only the project name). Example output: -```bash + +```text Coursera eLearning ``` -## 💡Hint +## 💡 Hints: -1. Similar exercise to the previous one. -2. Do a GET request to the endpoint. -3. Use the [.json() method](https://www.w3schools.com/python/ref_requests_response.asp) to get the response body as a dictionary (same as you did on last exercise). -4. Print the project name, you can access the property name on the response dictionary. ++ Make a GET request to the endpoint. ++ Use the [.json() method](https://www.w3schools.com/python/ref_requests_response.asp) to get the response body as a dictionary (same as you did on the last exercise). ++ Print the project name; you can access the property name in the response dictionary. diff --git a/exercises/05-project-name/app.py b/exercises/05-project-name/app.py index a471294..0ca5c86 100644 --- a/exercises/05-project-name/app.py +++ b/exercises/05-project-name/app.py @@ -1,3 +1,3 @@ import requests -# your code here \ No newline at end of file +# Your code here \ No newline at end of file diff --git a/exercises/05-project-name/solution.hide.py b/exercises/05-project-name/solution.hide.py new file mode 100644 index 0000000..c840be4 --- /dev/null +++ b/exercises/05-project-name/solution.hide.py @@ -0,0 +1,15 @@ +import requests + +# Your code here +response = requests.get("https://assets.breatheco.de/apis/fake/sample/project1.php") + +if response.status_code == 200: + # Parsing JSON response + project_data = response.json() + + # Extracting project name + project_name = project_data["name"] + + print(project_name) +else: + print("Failed to fetch project data.") \ No newline at end of file diff --git a/exercises/05-project-name/test.py b/exercises/05-project-name/test.py index e95a4da..1256d31 100644 --- a/exercises/05-project-name/test.py +++ b/exercises/05-project-name/test.py @@ -8,7 +8,7 @@ def json(self): return { "name": "Sample Project", "thumb": "https://unsplash.it/450/320?image=178", - "description": "The coolest elarning site on the planet", + "description": "The coolest eLearning site on the planet", "images": [ "https://unsplash.it/450/320?image=178", "https://unsplash.it/450/320?image=179", @@ -17,13 +17,14 @@ def json(self): ] } -@pytest.mark.it("requests.get has to be called to the project url") +@pytest.mark.it("requests.get has to be called for the project.php url") def test_url_call(capsys, app): with patch('requests.get') as mock_request: app() mock_request.assert_called_once_with("https://assets.breatheco.de/apis/fake/sample/project1.php") -@pytest.mark.it("You should print on the console a stirng like: Current time: 19 hrs 45 min and 06 sec") + +@pytest.mark.it("You should print the name of the project on the console") def test_url_output(capsys, app): with patch('requests.get') as mock_request: mock_request.return_value = FakeResponse() diff --git a/exercises/06-project-list/README.es.md b/exercises/06-project-list/README.es.md index 0850906..d54db13 100644 --- a/exercises/06-project-list/README.es.md +++ b/exercises/06-project-list/README.es.md @@ -1,15 +1,16 @@ -# `06` Lista de Proyectos +# `06` Project List -El siguiente endpoint devuelve una respuesta con formato JSON con varios proyectos en una lista: +El siguiente endpoint devuelve una respuesta en formato JSON con varios proyectos en una lista: GET: [https://assets.breatheco.de/apis/fake/sample/project_list.php](https://assets.breatheco.de/apis/fake/sample/project_list.php) Cada uno de los proyectos tiene el siguiente formato (ejemplo): + ```json { "name": "Coursera eLearning", "thumb": "https://unsplash.it/450/320?image=178", - "description": "The coolest elarning site on the planet", + "description": "The coolest eLearning site on the planet", "images": [ "https://unsplash.it/450/320?image=178", "https://unsplash.it/450/320?image=179", @@ -19,22 +20,23 @@ Cada uno de los proyectos tiene el siguiente formato (ejemplo): } ``` -# 📝 Instrucciones +## 📝 Instrucciones: + +1. Llama al endpoint e imprime el nombre del **SEGUNDO** proyecto en la lista: -Llame al punto final e imprima el nombre del **SEGUNDO** proyecto en la lista: +Ejemplo de salida: -Ejemplo: -```bash +```text Coursera eLearning ``` -## 💡Pista +## 💡 Pistas: -1. Abre el endpoint en tu navegador y analiza la respuesta que se encuentra en el body, necesitas saber qué esperar, cuál será la estructura de los datos (body response) que regresan del servidor. -2. En este caso, el body response comienza con un corchete `[`, es una lista, debe acceder al segundo proyecto utilizando posiciones numéricas. -2. Haga una solicitud GET al endpoint. -3. Usa el [metodo .json()](https://www.w3schools.com/python/ref_requests_response.asp)para obtener el body response como un diccionario. -4. Encuentra el segundo proyecto -5. Imprime el nombre del proyecto, puedes acceder a la propiedad nombre "name" del diccionario del proyecto. -6. No necesitas hacer un bucle (loop), solo accede al segundo elemento como una lista usando la posición ++ Abre el endpoint en tu navegador y analiza la respuesta que se encuentra en el body, necesitas saber qué esperar, cuál será la estructura de los datos (response body) que devuelve el servidor. ++ En este caso, el response body comienza con un corchete `[`, es una lista, debes acceder al segundo proyecto utilizando posiciones numéricas. ++ Haz una solicitud GET al endpoint. ++ Usa el [metodo .json()](https://www.w3schools.com/python/ref_requests_response.asp) para obtener el response body como un diccionario. ++ Encuentra el segundo proyecto de la lista. ++ Imprime el nombre del proyecto, puedes acceder a la propiedad `name` del diccionario del proyecto. ++ No necesitas hacer un bucle (loop), solo accede al segundo elemento como una lista usando la posición. diff --git a/exercises/06-project-list/README.md b/exercises/06-project-list/README.md index 1312bfd..c4c8e0e 100644 --- a/exercises/06-project-list/README.md +++ b/exercises/06-project-list/README.md @@ -1,15 +1,16 @@ # `06` Project List -The following endpoint returns a JSON formated response with several projects in a list: +The following endpoint returns a JSON formatted response with several projects in a list: GET: [https://assets.breatheco.de/apis/fake/sample/project_list.php](https://assets.breatheco.de/apis/fake/sample/project_list.php) Each of the projects has the following format (example): + ```json { "name": "Coursera eLearning", "thumb": "https://unsplash.it/450/320?image=178", - "description": "The coolest elarning site on the planet", + "description": "The coolest eLearning site on the planet", "images": [ "https://unsplash.it/450/320?image=178", "https://unsplash.it/450/320?image=179", @@ -19,22 +20,22 @@ Each of the projects has the following format (example): } ``` -# 📝 Instructions +## 📝 Instructions: -Please call the endpoint and print the name of the **SECOND** project on the list: +1. Please call the endpoint and print the name of the **SECOND** project on the list: Example output: -```bash +```text Coursera eLearning ``` -## 💡Hint +## 💡 Hints: -1. Open the endpoint on your browser and analyze the response body, you need to know what to expect, what is going to be the structure of the data (response body) coming back from the server. -2. In this case the response body starts with a square bracket `[`, it's a list, you have to access the second project by using numerical positions. -2. Do a GET request to the endpoint. -3. Use the [.json() method](https://www.w3schools.com/python/ref_requests_response.asp) to get the response body as a dictionary. -4. Find the second project on the list. -5. Print the project name, you can access the property name of the project dictionary. -6. You don't need to loop, just access the second item like a list using the position ++ Open the endpoint on your browser and analyze the response body, you need to know what to expect, what is going to be the structure of the data (response body) coming back from the server. ++ In this case, the response body starts with a square bracket `[`, it's a list, and you have to access the second project by using numerical positions. ++ Make a GET request to the endpoint. ++ Use the [.json() method](https://www.w3schools.com/python/ref_requests_response.asp) to get the response body as a dictionary. ++ Find the second project on the list. ++ Print the project name, you can access the property `name` of the project dictionary. ++ You don't need to loop, just access the second item like a list using the position. diff --git a/exercises/06-project-list/app.py b/exercises/06-project-list/app.py index a471294..0ca5c86 100644 --- a/exercises/06-project-list/app.py +++ b/exercises/06-project-list/app.py @@ -1,3 +1,3 @@ import requests -# your code here \ No newline at end of file +# Your code here \ No newline at end of file diff --git a/exercises/06-project-list/solution.hide.py b/exercises/06-project-list/solution.hide.py new file mode 100644 index 0000000..8cdcd5f --- /dev/null +++ b/exercises/06-project-list/solution.hide.py @@ -0,0 +1,15 @@ +import requests + +# Your code here +response = requests.get("https://assets.breatheco.de/apis/fake/sample/project_list.php") + +if response.status_code == 200: + # Parsing JSON response + project_list = response.json() + + # Extracting the name of the second project + second_project_name = project_list[1]["name"] + + print(second_project_name) +else: + print("Failed to fetch project list.") \ No newline at end of file diff --git a/exercises/06-project-list/test.py b/exercises/06-project-list/test.py index 4d7945b..66ba249 100644 --- a/exercises/06-project-list/test.py +++ b/exercises/06-project-list/test.py @@ -6,9 +6,9 @@ class FakeResponse(object): status_code = 200 def json(self): return [{ - "name": "Stackbucks for milkshakes", + "name": "Starbucks for milkshakes", "thumb": "https://unsplash.it/450/320?image=178", - "description": "The coolest elarning site on the planet", + "description": "", "images": [ "https://unsplash.it/450/320?image=178", "https://unsplash.it/450/320?image=179", @@ -19,7 +19,7 @@ def json(self): { "name": "Uber for trucks", "thumb": "https://unsplash.it/450/320?image=178", - "description": "The coolest elarning site on the planet", + "description": "", "images": [ "https://unsplash.it/450/320?image=178", "https://unsplash.it/450/320?image=179", @@ -28,9 +28,9 @@ def json(self): ] }, { - "name": "McDonals for tacos", + "name": "McDonalds for tacos", "thumb": "https://unsplash.it/450/320?image=178", - "description": "The coolest elarning site on the planet", + "description": "", "images": [ "https://unsplash.it/450/320?image=178", "https://unsplash.it/450/320?image=179", @@ -40,7 +40,7 @@ def json(self): } ] -@pytest.mark.it("requests.get has to be called to the project url") +@pytest.mark.it("requests.get has to be called for the project_list.php url") def test_url_call(capsys, app): with patch('requests.get') as mock_request: app() @@ -52,7 +52,7 @@ def test_url_output2(capsys, app): mock_request.return_value = FakeResponse() app() captured = capsys.readouterr() - assert "McDonals for tacos\n" != captured.out + assert "McDonalds for tacos\n" != captured.out @pytest.mark.it("Make sure you are printing the project name") def test_url_output1(capsys, app): diff --git a/exercises/07-project-list-image/README.es.md b/exercises/07-project-list-image/README.es.md index 0c5c96b..d155f02 100644 --- a/exercises/07-project-list-image/README.es.md +++ b/exercises/07-project-list-image/README.es.md @@ -1,20 +1,21 @@ -# `07` Lista de las Imagenes del Proyecto +# `07` Project List Image -# 📝 Instrucciones +## 📝 Instrucciones: -Haz una solicitud GET a la misma URL que en el ejercicio anterior, imprime la `última` url image (imagen de la url) en el `último` proyecto. +1. Haz una solicitud GET a la misma URL que en el ejercicio anterior, imprime la **última** URL de las imagenes del **último** proyecto. Ejemplo: -```bash + +```text https://image.shutterstock.com/image-vector/trophy-cup-award-vector-icon-260nw-592525184.jpg ``` -## 💡Pista +## 💡 Pistas: -1. Haz una solicitud GET al endpoint. -2. Usa el [metodo .json()](https://www.w3schools.com/python/ref_requests_response.asp) para obtener el response body como un diccionario. -3. Encuentra el último proyecto en la lista. -4. Encuentra la última imagen de ese proyecto. -5. Imprima la imagen de la URL en la consola. -6. No es necesario realizar un bucle (loop), solo use las posiciones numéricas (índice/index) para acceder a la información ++ Haz una solicitud GET al endpoint. ++ Usa el [metodo .json()](https://www.w3schools.com/python/ref_requests_response.asp) para obtener el response body como un diccionario. ++ Encuentra el último proyecto en la lista. ++ Encuentra la última imagen de ese proyecto. ++ Imprime la URL de esa imagen en la consola. ++ No es necesario realizar un bucle, solo usa las posiciones numéricas (índice/index) para acceder a la información. diff --git a/exercises/07-project-list-image/README.md b/exercises/07-project-list-image/README.md index 5b37214..94985d1 100644 --- a/exercises/07-project-list-image/README.md +++ b/exercises/07-project-list-image/README.md @@ -1,20 +1,21 @@ # `07` Project List Image -# 📝 Instructions +## 📝 Instructions: -Do a GET request to the same URL as in the previous exercise, print the `last` image URL in the `last` project. +1. Do a GET request to the same URL as in the previous exercise, print the **last** image URL in the **last** project. Example output: -```bash + +```text https://image.shutterstock.com/image-vector/trophy-cup-award-vector-icon-260nw-592525184.jpg ``` -## 💡Hint +## 💡 Hints: -1. Do a GET request to the endpoint. -2. Use the [.json() method](https://www.w3schools.com/python/ref_requests_response.asp) to get the response body as a dictionary. -3. Find the last project on the list. -4. Find the last image of that project. -5. Print the image URL on the console. -6. No need to loop, just use the numerical positions (index) to access the information ++ Do a GET request to the endpoint. ++ Use the [.json() method](https://www.w3schools.com/python/ref_requests_response.asp) to get the response body as a dictionary. ++ Find the last project on the list. ++ Find the last image of that project. ++ Print the image URL on the console. ++ No need to loop, just use the numerical positions (index) to access the information. diff --git a/exercises/07-project-list-image/app.py b/exercises/07-project-list-image/app.py index a471294..0ca5c86 100644 --- a/exercises/07-project-list-image/app.py +++ b/exercises/07-project-list-image/app.py @@ -1,3 +1,3 @@ import requests -# your code here \ No newline at end of file +# Your code here \ No newline at end of file diff --git a/exercises/07-project-list-image/solution.hide.py b/exercises/07-project-list-image/solution.hide.py new file mode 100644 index 0000000..b52a93f --- /dev/null +++ b/exercises/07-project-list-image/solution.hide.py @@ -0,0 +1,19 @@ +import requests + +# Your code here +response = requests.get("https://assets.breatheco.de/apis/fake/sample/project_list.php") + +if response.status_code == 200: + # Parsing JSON response + project_list = response.json() + + # Extracting the last project + last_project = project_list[-1] + + # Extracting the last image URL + last_image_url = last_project["images"][-1] + + # Printing the last image URL + print(last_image_url) +else: + print("Failed to fetch project list.") \ No newline at end of file diff --git a/exercises/07-project-list-image/test.py b/exercises/07-project-list-image/test.py index 3a733a7..b18b204 100644 --- a/exercises/07-project-list-image/test.py +++ b/exercises/07-project-list-image/test.py @@ -18,7 +18,7 @@ def json(self): { "name" : "Coursera eLearning", "thumb" : "https://unsplash.it/450/320?image=178", - "description" : "The coolest elarning site on the planet", + "description" : "The coolest eLearning site on the planet", "images" : [ "https://unsplash.it/450/320?image=178", "https://unsplash.it/450/320?image=179", @@ -29,7 +29,7 @@ def json(self): { "name" : "Company Website", "thumb" : "https://unsplash.it/450/320?image=278", - "description" : "Super boring company porfolio website with the tipical about us, home, contact us sections", + "description" : "Super boring company portfolio website with the typical about us, home, and contact us sections", "images" : [ "https://unsplash.it/450/320?image=278", "https://unsplash.it/450/320?image=280", @@ -38,7 +38,7 @@ def json(self): } ] -@pytest.mark.it("requests.get has to be called to the project url") +@pytest.mark.it("requests.get has to be called for the project_list.php url") def test_url_call(capsys, app): with patch('requests.get') as mock_request: app() diff --git a/exercises/08-blog-post-author/README.es.md b/exercises/08-blog-post-author/README.es.md index ba99543..46037b0 100644 --- a/exercises/08-blog-post-author/README.es.md +++ b/exercises/08-blog-post-author/README.es.md @@ -1,20 +1,22 @@ -# `08` Publicar autor de blog +# `08` Post blog author -Tómate un momento para comprender el body response al hacer una solicitud GET a este endpoint: +Tómate un momento para comprender el response body al hacer una solicitud GET a este endpoint: [https://assets.breatheco.de/apis/fake/sample/weird_portfolio.php](https://assets.breatheco.de/apis/fake/sample/weird_portfolio.php) -👉🏼 [Aquí hay una breve explicación en video.](https://www.youtube.com/watch?v=fwfBYVrvSk0) +> 👉🏼 [Aquí hay una breve explicación en video.](https://www.youtube.com/watch?v=fwfBYVrvSk0) -# 📝 Instrucciones +![explicación del json](https://github.com/4GeeksAcademy/python-http-requests-api-tutorial-exercises/blob/master/assets/traversion_json.png?raw=true) -Obtén el nombre del autor de la primera publicación. +## 📝 Instrucciones: -## 💡Pista +1. Obtén el nombre del autor de la primera publicación. -1. Haz una solicitud GET al endpoint. -2. Usa el [metodo .json()](https://www.w3schools.com/python/ref_requests_response.asp) para obtener el response body como un diccionario. -3. Encuentra la primera publicación -4. Obtén el autor del diccionario -5. Escribe el nombre del autor -6. No necesitas hacer un bucle (loop), solo usa las posiciones (índice/index) +## 💡 Pistas: + ++ Haz una solicitud GET al endpoint. ++ Usa el [metodo .json()](https://www.w3schools.com/python/ref_requests_response.asp) para obtener el response body como un diccionario. ++ Encuentra la primera publicación. ++ Obtén el diccionario `author`. ++ Imprime el nombre del autor. ++ No necesitas hacer un bucle, solo usa las posiciones (índice/index). diff --git a/exercises/08-blog-post-author/README.md b/exercises/08-blog-post-author/README.md index 17d8775..f31550a 100644 --- a/exercises/08-blog-post-author/README.md +++ b/exercises/08-blog-post-author/README.md @@ -3,20 +3,20 @@ Take a moment to understand the response body when doing a GET request to this endpoint: [https://assets.breatheco.de/apis/fake/sample/weird_portfolio.php](https://assets.breatheco.de/apis/fake/sample/weird_portfolio.php) -👉🏼 [Here is a brief video explanation.](https://www.youtube.com/watch?v=fwfBYVrvSk0) +> 👉🏼 [Here is a brief video explanation.](https://www.youtube.com/watch?v=fwfBYVrvSk0) ![json explanation](https://github.com/4GeeksAcademy/python-http-requests-api-tutorial-exercises/blob/master/assets/traversion_json.png?raw=true) -# 📝 Instructions +## 📝 Instructions: -Get the author name of the first post. +1. Get the author name of the first post. -## 💡Hint +## 💡 Hints: -1. Do a GET request to the endpoint. -2. Use the [.json() method](https://www.w3schools.com/python/ref_requests_response.asp) to get the response body as a dictionary. -3. Find the first post -4. Get the author dictionary -5. Print author name -6. You dont need to loop, jsut use the positions (index). ++ Do a GET request to the endpoint. ++ Use the [.json() method](https://www.w3schools.com/python/ref_requests_response.asp) to get the response body as a dictionary. ++ Find the first post. ++ Get the `author` dictionary. ++ Print the author name. ++ You don't need to loop, just use the positions (index). diff --git a/exercises/08-blog-post-author/app.py b/exercises/08-blog-post-author/app.py index a471294..0ca5c86 100644 --- a/exercises/08-blog-post-author/app.py +++ b/exercises/08-blog-post-author/app.py @@ -1,3 +1,3 @@ import requests -# your code here \ No newline at end of file +# Your code here \ No newline at end of file diff --git a/exercises/08-blog-post-author/solution.hide.py b/exercises/08-blog-post-author/solution.hide.py new file mode 100644 index 0000000..2d25260 --- /dev/null +++ b/exercises/08-blog-post-author/solution.hide.py @@ -0,0 +1,21 @@ +import requests + +# Your code here +response = requests.get("https://assets.breatheco.de/apis/fake/sample/weird_portfolio.php") + +if response.status_code == 200: + # Parsing JSON response + data = response.json() + + # Getting the first post + first_post = data["posts"][0] + + # Getting the author dictionary + author_dict = first_post["author"] + + # Getting the author name + author_name = author_dict["name"] + + print(author_name) +else: + print("Failed to fetch data from the endpoint.") \ No newline at end of file diff --git a/exercises/08-blog-post-author/test.py b/exercises/08-blog-post-author/test.py index 6bb9ed6..a69d0f4 100644 --- a/exercises/08-blog-post-author/test.py +++ b/exercises/08-blog-post-author/test.py @@ -11,7 +11,7 @@ def json(self): ] } -@pytest.mark.it("requests.get has to be called to the project url") +@pytest.mark.it("requests.get has to be called for the weird_portfolio.php url") def test_url_call(capsys, app): with patch('requests.get') as mock_request: app() diff --git a/exercises/09-array-of-blog-titles/README.es.md b/exercises/09-array-of-blog-titles/README.es.md deleted file mode 100644 index a341d3e..0000000 --- a/exercises/09-array-of-blog-titles/README.es.md +++ /dev/null @@ -1,20 +0,0 @@ -# `09` Arreglo con titulos de publicaciones - -# 📝 Instrucciones - -Usando el mismo endpoint del ejercicio anterior, crea una función `get_titles` que retorne los titulos de todos los post (publicaciones) encontradas en el response body. - -## 💡Pista - -1. Crea una función `get_titles`. -2. Declara un array vacío llamado `titles`. -3. Haz el request del API adentro de la función. -4. realiza un bucle (Loop) que itere para cada publicación. -5. Agregue cada título de publicación al nuevo arreglo. -6. Retorna el arreglo. - -La salida de la consola debería verse parecido a esto: - -```python -['title 1','title 2', 'title 3'] -``` \ No newline at end of file diff --git a/exercises/09-array-of-blog-titles/README.md b/exercises/09-array-of-blog-titles/README.md deleted file mode 100644 index 0c1a241..0000000 --- a/exercises/09-array-of-blog-titles/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# `09` Array of blog titles - -# 📝 Instructions - -Using the same endpoint from the previous exercise, create a function `get_titles` that returns the titles of all the posts found in the response body. - -## 💡Hint - -1. Create the function `get_titles`. -2. Declare a new empty array called `titles`. -3. Do the request to the endpoint inside of the function. -4. Loop each post from the list of posts. -5. Get the title of each post. -6. Add that title to the new array. -7. Return the titles array. - -The console output should be something similar to this: - -```python -['title 1','title 2', 'title 3'] -``` \ No newline at end of file diff --git a/exercises/09-list-of-blog-titles/README.es.md b/exercises/09-list-of-blog-titles/README.es.md new file mode 100644 index 0000000..496528f --- /dev/null +++ b/exercises/09-list-of-blog-titles/README.es.md @@ -0,0 +1,20 @@ +# `09` List of blog titles + +## 📝 Instrucciones: + +1. Usando el mismo endpoint del ejercicio anterior, crea una función `get_titles` que retorne los títulos de todas las publicaciones encontradas en el response body. + +## 💡 Pistas: + ++ Crea una función `get_titles`. ++ Declara una lista vacía llamada `titles`. ++ Haz el request del API adentro de la función. ++ realiza un bucle que itere para cada publicación. ++ Agregue cada título a la nueva lista. ++ Retorna la lista `titles`. + +La salida de la consola debería verse parecido a esto: + +```python +['title 1', 'title 2', 'title 3'] +``` \ No newline at end of file diff --git a/exercises/09-list-of-blog-titles/README.md b/exercises/09-list-of-blog-titles/README.md new file mode 100644 index 0000000..dd5b70f --- /dev/null +++ b/exercises/09-list-of-blog-titles/README.md @@ -0,0 +1,21 @@ +# `09` List of blog titles + +## 📝 Instructions: + +1. Using the same endpoint from the previous exercise, create a function `get_titles` that returns the titles of all the posts found in the response body. + +## 💡 Hints: + ++ Create the function `get_titles`. ++ Declare a new empty list called `titles`. ++ Do the request to the endpoint inside the function. ++ Loop each post from the list of posts. ++ Get the title of each post. ++ Add that title to the new list. ++ Return the `titles` list. + +The console output should be something similar to this: + +```python +['title 1', 'title 2', 'title 3'] +``` \ No newline at end of file diff --git a/exercises/09-array-of-blog-titles/app.py b/exercises/09-list-of-blog-titles/app.py similarity index 77% rename from exercises/09-array-of-blog-titles/app.py rename to exercises/09-list-of-blog-titles/app.py index e464bad..cc536a8 100644 --- a/exercises/09-array-of-blog-titles/app.py +++ b/exercises/09-list-of-blog-titles/app.py @@ -1,7 +1,7 @@ import requests def get_titles(): - # your code here + # Your code here return None diff --git a/exercises/09-list-of-blog-titles/solution.hide.py b/exercises/09-list-of-blog-titles/solution.hide.py new file mode 100644 index 0000000..090093b --- /dev/null +++ b/exercises/09-list-of-blog-titles/solution.hide.py @@ -0,0 +1,25 @@ +import requests + +def get_titles(): + # Your code here + url = "https://assets.breatheco.de/apis/fake/sample/weird_portfolio.php" + + titles = [] + + response = requests.get(url) + + if response.status_code == 200: + # Parsing JSON response + data = response.json() + + for post in data["posts"]: + title = post["title"] + if title: + titles.append(title) + else: + print("Failed to fetch data from the endpoint.") + + return titles + + +print(get_titles()) \ No newline at end of file diff --git a/exercises/09-array-of-blog-titles/test.py b/exercises/09-list-of-blog-titles/test.py similarity index 80% rename from exercises/09-array-of-blog-titles/test.py rename to exercises/09-list-of-blog-titles/test.py index 59965c8..e1b05b8 100644 --- a/exercises/09-array-of-blog-titles/test.py +++ b/exercises/09-list-of-blog-titles/test.py @@ -7,14 +7,14 @@ class FakeResponse(object): def json(self): return { "posts": [ - { "title": 'R.I.P. Ruby on Rails. Thanks for everything.' }, + {"title": 'R.I.P. Ruby on Rails. Thanks for everything.'}, {"title": 'The fraud behind the C.A. of digital certificates is over'}, {"title": 'Manteniendo las raices'}, - {"title":'DF Tech Meetup, ya es una realidad'} + {"title": 'DF Tech Meetup, ya es una realidad'} ] } -@pytest.mark.it("You seem to be returning None or not retuning anything") +@pytest.mark.it("You seem to be returning None or not returning anything") def test_for_null(app): with patch('requests.get') as mock_request: from app import get_titles @@ -30,7 +30,7 @@ def test_return_type(app): tags = get_titles() assert isinstance(tags, list) -@pytest.mark.it("Return a list of post titles like: ['title 1','title 2', 'title 3']") +@pytest.mark.it("Return a list of post titles like: ['title 1', 'title 2', 'title 3']") def test_array_content(app): with patch('requests.get') as mock_request: from app import get_titles diff --git a/exercises/10-get-post-tags/README.es.md b/exercises/10-get-post-tags/README.es.md new file mode 100644 index 0000000..cff0c68 --- /dev/null +++ b/exercises/10-get-post-tags/README.es.md @@ -0,0 +1,14 @@ +# `10` Get post tags + +## 📝 Instrucciones: + +1. Usando el mismo endpoint del ejercicio anterior, crea una función `get_post_tags` que retorne el arreglo de etiquetas (tags) de un `post_id` dado. + +## 💡 Pistas: + ++ Crea la función `get_post_tags`. ++ Obtén todas las publicaciones (post) haciendo la solicitud GET al endpoint. ++ Declare la variable para almacenar el body serializado. ++ Usando el parámetro `post_id`, recorre con un loop todas las publicaciones y compara sus ID para ver si coinciden con el `post_id`. ++ Cuando encuentres la publicación que deseas, devuelve una lista de etiquetas (tags). + diff --git a/exercises/10-get-post-tags/README.md b/exercises/10-get-post-tags/README.md new file mode 100644 index 0000000..6d974a7 --- /dev/null +++ b/exercises/10-get-post-tags/README.md @@ -0,0 +1,14 @@ +# `10` Get post tags + +## 📝 Instructions: + +1. Using the same endpoint from the previous exercise, create a function `get_post_tags` that returns the array of tags of a given `post_id` + +## 💡 Hints: + ++ Create the function `get_post_tags`. ++ GET all the posts by sending a GET request to the endpoint. ++ Declare the variable to store the serialized body ++ Using the `post_id` parameter, loop all the posts and compare their `id`s to see if they match the `post_id`. ++ When you find the post you want, return its list of tags. + diff --git a/exercises/10-get_post_tags/app.py b/exercises/10-get-post-tags/app.py similarity index 80% rename from exercises/10-get_post_tags/app.py rename to exercises/10-get-post-tags/app.py index 0889c24..ff6d142 100644 --- a/exercises/10-get_post_tags/app.py +++ b/exercises/10-get-post-tags/app.py @@ -1,7 +1,7 @@ import requests def get_post_tags(post_id): - # your code here + # Your code here return None diff --git a/exercises/10-get-post-tags/solution.hide.py b/exercises/10-get-post-tags/solution.hide.py new file mode 100644 index 0000000..f97c043 --- /dev/null +++ b/exercises/10-get-post-tags/solution.hide.py @@ -0,0 +1,23 @@ +import requests + +def get_post_tags(post_id): + # Your code here + url = "https://assets.breatheco.de/apis/fake/sample/weird_portfolio.php" + + response = requests.get(url) + + if response.status_code == 200: + # Parsing JSON response + data = response.json() + + # Loop through each post to find the one with matching post_id + for post in data["posts"]: + if post["id"] == post_id: + return post["tags"] + print("No post found") + + else: + print("Failed to fetch data from the endpoint.") + + +print(get_post_tags(146)) \ No newline at end of file diff --git a/exercises/10-get_post_tags/test.py b/exercises/10-get-post-tags/test.py similarity index 100% rename from exercises/10-get_post_tags/test.py rename to exercises/10-get-post-tags/test.py diff --git a/exercises/10-get_post_tags/README.es.md b/exercises/10-get_post_tags/README.es.md deleted file mode 100644 index 3293758..0000000 --- a/exercises/10-get_post_tags/README.es.md +++ /dev/null @@ -1,14 +0,0 @@ -# `10` Obtener etiqueta de publicación - -# 📝 Instrucciones - -Usando el mismo endpoint del ejercicio anterior, crea una función `get_post_tags` que retorne el arreglo de etiquetas (tags) de un `post id` dado. - -## 💡Pista - -1. Crea la función `get_post_tags`. -2. Obtén todas las publicaciones (post) haciendo la solicitud GET al endpoint. -3. Declare la variable para almacenar el body serializado -4. Usando el parámetro `post_id`, recorre con un loop todas las publicaciones y compara sus ID para ver si coinciden con el` post_id`. -3. Cuando encuentres la publicación que deseas, devuelve una lista de etiquetas (tags) - diff --git a/exercises/10-get_post_tags/README.md b/exercises/10-get_post_tags/README.md deleted file mode 100644 index 9529c07..0000000 --- a/exercises/10-get_post_tags/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# `10` Get post tags - -# 📝 Instructions - -Using the same endpoint from the previous exercise, create a function `get_post_tags` that returns the array of tags of a given `post id` - -## 💡Hint - -1. Create the function `get_post_tags`. -2. GET all the posts by doing the GET request to the endpoint. -3. declare the variable to store the serialized body -4. Using the `post_id` parameter loop all the posts and compare their id's to see if they match the `post_id`. -3. When you find the post you want, return it's list of tags - diff --git a/exercises/11-get-attachment-by-id/README.es.md b/exercises/11-get-attachment-by-id/README.es.md new file mode 100644 index 0000000..3b3ce59 --- /dev/null +++ b/exercises/11-get-attachment-by-id/README.es.md @@ -0,0 +1,13 @@ +# `11` Get attachment by id + +## 📝 Instrucciones: + +1. Usando el mismo endpoint del ejercicio anterior, crea una función `get_attachment_by_id` que retorne el título de los archivos adjuntos (attachments) que corresponden con el `id` dado. + +## 💡 Pistas: + ++ Crea la función `get_attachment_by_id` que reciba el `attachment_id` como un parámetro. ++ Recorre con un bucle todos los posts. ++ Recorre con un bucle todos los archivos adjuntos (attachments) de cada post. ++ Si el archivo adjunto (attachment) tiene el `attachment_id` dado en el parámetro de la función, devuélvelo. + diff --git a/exercises/11-get-attachment-by-id/README.md b/exercises/11-get-attachment-by-id/README.md new file mode 100644 index 0000000..5fb34df --- /dev/null +++ b/exercises/11-get-attachment-by-id/README.md @@ -0,0 +1,13 @@ +# `11` Get attachment by id + +## 📝 Instructions: + +1. Using the same endpoint from the previous exercise, create a function `get_attachment_by_id` that returns the title of the attachment that corresponds to the given `id`. + +## 💡 Hints: + ++ Create the function `get_attachment_by_id` that receives the `attachment_id` as a parameter. ++ Loop all the posts. ++ Loop all the `attachments` for each post. ++ If the attachment has the given `attachment_id` in the function parameter, return it. + diff --git a/exercises/11-get_attachment_by_id/app.py b/exercises/11-get-attachment-by-id/app.py similarity index 83% rename from exercises/11-get_attachment_by_id/app.py rename to exercises/11-get-attachment-by-id/app.py index 26274ff..3571d84 100644 --- a/exercises/11-get_attachment_by_id/app.py +++ b/exercises/11-get-attachment-by-id/app.py @@ -1,7 +1,7 @@ import requests def get_attachment_by_id(attachment_id): - # your code here + # Your code here return None print(get_attachment_by_id(137)) \ No newline at end of file diff --git a/exercises/11-get-attachment-by-id/solution.hide.py b/exercises/11-get-attachment-by-id/solution.hide.py new file mode 100644 index 0000000..d09dc7d --- /dev/null +++ b/exercises/11-get-attachment-by-id/solution.hide.py @@ -0,0 +1,25 @@ +import requests + +def get_attachment_by_id(attachment_id): + # Your code here + url = "https://assets.breatheco.de/apis/fake/sample/weird_portfolio.php" + + response = requests.get(url) + + if response.status_code == 200: + # Parsing JSON response + data = response.json() + + for post in data["posts"]: + # Check if the post has attachments + if "attachments" in post: + # Loop through each attachment + for attachment in post["attachments"]: + if attachment["id"] == attachment_id: + return attachment["title"] + + print("No attachment found") + else: + print("Failed to fetch data from the endpoint.") + +print(get_attachment_by_id(137)) \ No newline at end of file diff --git a/exercises/11-get_attachment_by_id/test.py b/exercises/11-get-attachment-by-id/test.py similarity index 63% rename from exercises/11-get_attachment_by_id/test.py rename to exercises/11-get-attachment-by-id/test.py index c413668..739579d 100644 --- a/exercises/11-get_attachment_by_id/test.py +++ b/exercises/11-get-attachment-by-id/test.py @@ -7,15 +7,15 @@ class FakeResponse(object): def json(self): return { "posts": [ - { "attachments": [{ "id": 22, "title": "asd" }] }, - { "attachments": [{ "id": 137, "title": "cert" }] }, - { "attachments": [{ "id": 11, "title": "asd" }] }, - { "attachments": [{ "id": 40, "title": "asd" }] }, - { "attachments": [{ "id": 314, "title": "asd" }] }, + { "attachments": [{ "id": 22, "title": "Invoice" }] }, + { "attachments": [{ "id": 137, "title": "Training Certificate" }] }, + { "attachments": [{ "id": 11, "title": "Presentation Slides" }] }, + { "attachments": [{ "id": 40, "title": "Meeting Agenda" }] }, + { "attachments": [{ "id": 314, "title": "Project Proposal" }] }, ] } -@pytest.mark.it("You seem to be returning None or not retuning anything on the function") +@pytest.mark.it("You seem to be returning None or not returning anything on the function") def test_for_null(app): with patch('requests.get') as mock_request: from app import get_attachment_by_id @@ -23,7 +23,7 @@ def test_for_null(app): att = get_attachment_by_id(137) assert att is not None -@pytest.mark.it("The function should have returned a string (the att title) but returnied something different") +@pytest.mark.it("The function should have returned a string (the attachment title) but returned something different") def test_return_type(app): with patch('requests.get') as mock_request: from app import get_attachment_by_id @@ -37,4 +37,4 @@ def test_array_content(app): from app import get_attachment_by_id mock_request.return_value = FakeResponse() title = get_attachment_by_id(137) - assert title == "cert" + assert title == "Training Certificate" diff --git a/exercises/11-get_attachment_by_id/README.es.md b/exercises/11-get_attachment_by_id/README.es.md deleted file mode 100644 index d7b82c2..0000000 --- a/exercises/11-get_attachment_by_id/README.es.md +++ /dev/null @@ -1,13 +0,0 @@ -# `11` Obtener un archivo adjunto (attachment) por id - -# 📝 Instrucciones - -Usando el mismo endpoint del ejercicio anterior, crea una función `get_attachment_by_id` que retornes el titulo de los adjuntos que correspondan con el id dado. - -## 💡Pista - -1. Crea la función `get_attachment_by_id` que reciba el `attachment_id` como un parametro. -2. Recorre (Loop) todos los posts. -3. Recorre (Loop) todos los attachments (adjuntos) de cada post. -4. Si el archivo adjunto (attachment) tiene el `attach_id` dado en el parámetro de la función, devuélvalo. - diff --git a/exercises/11-get_attachment_by_id/README.md b/exercises/11-get_attachment_by_id/README.md deleted file mode 100644 index 5f3864e..0000000 --- a/exercises/11-get_attachment_by_id/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# `11` Get attachment by id - -# 📝 Instructions - -Using the same endpoint from the previous exercise, create a function `get_attachment_by_id` that returns the title of the attachtment that corresponds to the given id. - -## 💡Hint - -1. Create the function `get_attachment_by_id` that recives the `attachment_id` as a parameter. -2. Loop all the posts. -3. Loop all the attachments for each post. -4. If the attachment has the given `attachment_id` in the function parameter, return it. - diff --git a/exercises/12-post-request/README.es.md b/exercises/12-post-request/README.es.md index fc7a1a7..13db050 100644 --- a/exercises/12-post-request/README.es.md +++ b/exercises/12-post-request/README.es.md @@ -1,8 +1,8 @@ -# `12` Solicitud POST +# `12` POST request -Las solicitudes POST están destinadas a la creación, por ejemplo, si tu negocio es un e-comerce de camisas , es probable que desee tener una forma de agregar nuevos clientes. +Las solicitudes POST están destinadas a la creación, por ejemplo, si tu negocio es un e-commerce de camisetas, es probable que desees tener una forma de agregar nuevos clientes. -Una solicitud de post generalmente tiene: +Una solicitud de POST (*POST request*) generalmente tiene: | | | | ---- | ---- | @@ -10,16 +10,15 @@ Una solicitud de post generalmente tiene: | Content-Type | application/json | | Body (payload) | JSON string | -# 📝 Instrucciones +## 📝 Instrucciones: -Envía una solitud POST al siguiente URL: +1. Envía una solitud POST al siguiente URL: POST: https://assets.breatheco.de/apis/fake/sample/post.php -E imprime la respuesta (text response) en la consolae +2. Imprime la respuesta (response text) en la consola. -## 💡Pista +## 💡 Pista: -Usa el paquete de solicitudes del metodo post: -https://www.w3schools.com/python/ref_requests_post.asp ++ Usa el método POST del paquete *requests*: https://www.w3schools.com/python/ref_requests_post.asp diff --git a/exercises/12-post-request/README.md b/exercises/12-post-request/README.md index fab7e53..7633825 100644 --- a/exercises/12-post-request/README.md +++ b/exercises/12-post-request/README.md @@ -1,8 +1,8 @@ # `12` POST request -POST requests are meant for creation, for example, if your business is an t-shirt e-commerce you probably want to have a way to add new clients. +POST requests are meant for creation, for example, if your business is a t-shirt e-commerce you probably want to have a way to add new clients. -A post request usually have: +A POST request usually has: | | | | ---- | ---- | @@ -10,16 +10,15 @@ A post request usually have: | Content-Type | application/json | | Body (payload) | JSON string | -# 📝 Instructions +## 📝 Instructions: -Send a POST request to the following URL: +1. Send a POST request to the following URL: POST: https://assets.breatheco.de/apis/fake/sample/post.php -And print the response text on the console +2. And print the response text on the console. -## 💡Hint +## 💡 Hint: -Use the requests package post method: -https://www.w3schools.com/python/ref_requests_post.asp ++ Use the requests package POST method: https://www.w3schools.com/python/ref_requests_post.asp diff --git a/exercises/12-post-request/app.py b/exercises/12-post-request/app.py index a471294..0ca5c86 100644 --- a/exercises/12-post-request/app.py +++ b/exercises/12-post-request/app.py @@ -1,3 +1,3 @@ import requests -# your code here \ No newline at end of file +# Your code here \ No newline at end of file diff --git a/exercises/12-post-request/solution.hide.py b/exercises/12-post-request/solution.hide.py new file mode 100644 index 0000000..631052e --- /dev/null +++ b/exercises/12-post-request/solution.hide.py @@ -0,0 +1,8 @@ +import requests + +# Your code here +url = "https://assets.breatheco.de/apis/fake/sample/post.php" + +response = requests.post(url) + +print(response.text) \ No newline at end of file diff --git a/exercises/12-post-request/test.py b/exercises/12-post-request/test.py index 7a5c98d..f49031f 100644 --- a/exercises/12-post-request/test.py +++ b/exercises/12-post-request/test.py @@ -1,7 +1,7 @@ import json, pytest from mock import patch -@pytest.mark.it("POST request to the specified endpoint") +@pytest.mark.it("Make a POST request to the specified endpoint") def test_url(app): with patch('requests.post') as mock_request: app() diff --git a/exercises/13-post-request-body/README.es.md b/exercises/13-post-request-body/README.es.md index bc8505b..4360e54 100644 --- a/exercises/13-post-request-body/README.es.md +++ b/exercises/13-post-request-body/README.es.md @@ -1,24 +1,25 @@ # `13` POST request body -# 📝 Instrucciones +## 📝 Instrucciones: -Envía una solitud POST al siguiente URL: +1. Envía una solitud POST al siguiente URL: + +```text https://assets.breatheco.de/apis/fake/sample/save-project-json.php +``` -Con `Content-Type: application/json` +2. Con `Content-Type: application/json` -Con el siguiente request body como texto JSON: +3. Con el siguiente request body como texto JSON: ```json { - "id":2323, + "id": 2323, "title": "Very big project" } - ``` -## 💡Pista +## 💡 Pista: -Usa el paquete de solicitudes del metodo post: -https://www.w3schools.com/python/ref_requests_post.asp ++ Usa el método POST del paquete *requests*: https://www.w3schools.com/python/ref_requests_post.asp diff --git a/exercises/13-post-request-body/README.md b/exercises/13-post-request-body/README.md index 87bd5c3..1cfa911 100644 --- a/exercises/13-post-request-body/README.md +++ b/exercises/13-post-request-body/README.md @@ -1,24 +1,25 @@ # `13` POST request body -# 📝 Instructions +## 📝 Instructions: -Send a POST request to the following URL: +1. Send a POST request to the following URL: + +```text https://assets.breatheco.de/apis/fake/sample/save-project-json.php +``` -With `Content-Type: application/json` +2. With `Content-Type: application/json` -With the following request body as JSON text: +3. With the following request body as JSON text: ```json { - "id":2323, + "id": 2323, "title": "Very big project" } - ``` -## 💡Hint +## 💡 Hint: -Use the requests package post method: -https://www.w3schools.com/python/ref_requests_post.asp ++ Use the requests package post method: https://www.w3schools.com/python/ref_requests_post.asp diff --git a/exercises/13-post-request-body/app.py b/exercises/13-post-request-body/app.py index 0edc6f1..df545c3 100644 --- a/exercises/13-post-request-body/app.py +++ b/exercises/13-post-request-body/app.py @@ -1,4 +1,4 @@ import requests -resp = requests.post("https://assets.breatheco.de/apis/fake/sample/save-project-json.php") -print(resp.text) \ No newline at end of file +response = requests.post("https://assets.breatheco.de/apis/fake/sample/save-project-json.php") +print(response.text) \ No newline at end of file diff --git a/exercises/13-post-request-body/solution.hide.py b/exercises/13-post-request-body/solution.hide.py new file mode 100644 index 0000000..97ca6d4 --- /dev/null +++ b/exercises/13-post-request-body/solution.hide.py @@ -0,0 +1,18 @@ +import requests + +url = "https://assets.breatheco.de/apis/fake/sample/save-project-json.php" + +data = { + "id": 2323, + "title": "Very big project" +} + +# Setting the headers +headers = { + "Content-Type": "application/json" +} + +# Sending POST request with dictionary data +response = requests.post(url, json=data, headers=headers) + +print(response.text) \ No newline at end of file diff --git a/exercises/13-post-request-body/test.py b/exercises/13-post-request-body/test.py index e296165..df557a9 100644 --- a/exercises/13-post-request-body/test.py +++ b/exercises/13-post-request-body/test.py @@ -1,7 +1,7 @@ import json, pytest from mock import patch -@pytest.mark.it("POST request to the specified endpoint") +@pytest.mark.it("Make a POST request to the specified endpoint") def test_url(app): with patch('requests.post') as mock_request: app() @@ -21,7 +21,7 @@ def test_headers(app): if "content-type" in headers: assert headers["content-type"].lower() == "application/json" -@pytest.mark.it("Request body must be a dictionary json with id and title") +@pytest.mark.it("Request body must be a json object with id and title") def test_body(app): with patch('requests.post') as mock_request: app()