Skip to content

Commit

Permalink
Merge pull request #24 from josemoracard/jose3-exercises
Browse files Browse the repository at this point in the history
todos los ejercicios, .gitignore, learn.json
  • Loading branch information
alesanchezr authored May 7, 2024
2 parents 1b12a8e + 0bb603d commit 1e0edda
Show file tree
Hide file tree
Showing 75 changed files with 599 additions and 354 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: 0 additions & 13 deletions exercises/00-hello-world/README.es.md

This file was deleted.

13 changes: 0 additions & 13 deletions exercises/00-hello-world/README.md

This file was deleted.

15 changes: 15 additions & 0 deletions exercises/00-welcome/README.es.md
Original file line number Diff line number Diff line change
@@ -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.
15 changes: 15 additions & 0 deletions exercises/00-welcome/README.md
Original file line number Diff line number Diff line change
@@ -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.
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.
20 changes: 0 additions & 20 deletions exercises/01-what-is-a-request/README.es.md

This file was deleted.

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`.

Loading

0 comments on commit 1e0edda

Please sign in to comment.