Skip to content

Commit

Permalink
todos los ejercicios
Browse files Browse the repository at this point in the history
  • Loading branch information
josemoracard committed Apr 5, 2024
2 parents 855aa82 + 8e299a4 commit 81e9aeb
Show file tree
Hide file tree
Showing 72 changed files with 595 additions and 308 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

!/exercises
!/exercises/*
exercises/*/__pycache__/

!/.learn
/.learn/**
Expand Down
13 changes: 13 additions & 0 deletions exercises/00-welcome/README.es.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# `00` Welcome to Python API Requests!

Python Requests es el paquete más popular para consumir APIs y hacer solicitudes HTTP.

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.
13 changes: 13 additions & 0 deletions exercises/00-welcome/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# `00` Welcome to Python API Requests!

Python Requests is the most popular package for consuming APIs and doing HTTP requests.

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.
20 changes: 20 additions & 0 deletions exercises/01-creating-a-request/README.es.md
Original file line number Diff line number Diff line change
@@ -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('<destination url>')
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.
Original file line number Diff line number Diff line change
@@ -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.

Expand All @@ -9,12 +9,12 @@ response = requests.get('<destination url>')
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.
> Note: The console should print a 200 status code.
File renamed without changes.
6 changes: 6 additions & 0 deletions exercises/01-creating-a-request/solution.hide.py
Original file line number Diff line number Diff line change
@@ -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))
File renamed without changes.
11 changes: 6 additions & 5 deletions exercises/02-random-status/README.es.md
Original file line number Diff line number Diff line change
@@ -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 |
| 400 | Something is wrong with the request params |
| Otro código de status | Unknown status code |
12 changes: 6 additions & 6 deletions exercises/02-random-status/README.md
Original file line number Diff line number Diff line change
@@ -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 |
| 400 | Something is wrong with the request params |
| Any other code | Unknown status code |
14 changes: 14 additions & 0 deletions exercises/02-random-status/solution.hide.py
Original file line number Diff line number Diff line change
@@ -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")
16 changes: 12 additions & 4 deletions exercises/02-random-status/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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
14 changes: 9 additions & 5 deletions exercises/03-response-body/README.es.md
Original file line number Diff line number Diff line change
@@ -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".
```text
"Something went wrong"
```
12 changes: 8 additions & 4 deletions exercises/03-response-body/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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".
```text
"Something went wrong"
```
2 changes: 1 addition & 1 deletion exercises/03-response-body/app.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import requests

url = "https://assets.breatheco.de/apis/fake/sample/random-status.php"
url = "https://assets.breatheco.de/apis/fake/sample/random-status.php"
10 changes: 10 additions & 0 deletions exercises/03-response-body/solution.hide.py
Original file line number Diff line number Diff line change
@@ -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")
4 changes: 2 additions & 2 deletions exercises/03-response-body/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
14 changes: 7 additions & 7 deletions exercises/04-response-body-json/README.es.md
Original file line number Diff line number Diff line change
@@ -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.

Expand All @@ -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`.

16 changes: 8 additions & 8 deletions exercises/04-response-body-json/README.md
Original file line number Diff line number Diff line change
@@ -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.

Expand All @@ -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`.

16 changes: 16 additions & 0 deletions exercises/04-response-body-json/solution.hide.py
Original file line number Diff line number Diff line change
@@ -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.")
2 changes: 1 addition & 1 deletion exercises/04-response-body-json/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading

0 comments on commit 81e9aeb

Please sign in to comment.