You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

2 Días
18 Hrs
47 Min
7 Seg
Curso de Flask

Curso de Flask

Luis Martínez

Luis Martínez

Rutas y vistas en Flask

3/18
Resources

The @route decorator in Flask is a powerful tool that allows us to define how our web applications respond to different types of HTTP requests. Mastering this decorator is essential for creating robust APIs and interactive web applications that can process various types of user requests. In this article, we will explore how to extend our use of the @route decorator to handle different HTTP methods and return various types of data.

How to use the @route decorator with different HTTP methods?

The @route decorator in Flask not only allows us to define routes for GET requests, but we can also configure it to handle other HTTP methods such as POST, PUT or DELETE. This is essential for creating complete web applications that can receive and process different types of user interactions.

To specify which HTTP methods a particular route can handle, we use the methods parameter:

@app.route('/contact',  methods=['GET', 'POST'])def contact(): if request.method == 'POST': return "Form submitted successfully", 201 return "Contact page".

In this example, we have created a view that can respond to both GET and POST requests. It is important to note that if we do not specify the methods parameter, Flask will assume by default that the route only handles GET requests.

How to validate the type of method in a request?

To determine what type of HTTP method an incoming request is using, we can use Flask's request object:

from flask import request
 @app.route('/contact',  methods=['GET', 'POST'])def contact(): if request.method == 'POST': # Logic for handling POST requests return "Form submitted successfully", 201 # Logic for handling GET requests return "Contact page" .

The request object is imported directly from Flask and is automatically populated with the current request information. We do not need to pass it as a parameter to our view function.

How to customize HTTP responses in Flask?

Flask allows us not only to return content, but also to specify HTTP status codes and other metadata in our responses.

Returning HTTP status codes

To return a specific status code along with our response, we simply include it as the second element in a tuple:

@app.route('/contact',  methods=['GET', 'POST'])def contact(): if request.method == 'POST': # We return code 201 (Created) to indicate that something was successfully created return "Form submitted successfully", 201 return "Contact page" .

HTTP status codes are important to follow good web development practices:

  • 200: OK (overall success)
  • 201: Created (resource successfully created)
  • 404: Not Found (resource not found)
  • 500: Internal Server Error (server error)

How to return different data formats?

Flask makes it easy to return different data formats, such as JSON, which is especially useful for web APIs:

from flask import jsonify
 @app.route('/api/info')def api_info(): data = { " name": "notesApp", " version": "1.1.1" } return jsonify(data), 200

The jsonify() function automatically converts Python dictionaries into JSON responses with the appropriate MIME headers. This is critical when we are developing APIs that need to communicate with frontend or mobile applications.

How to customize the URLs of our routes?

An interesting feature of Flask is that we can define URLs that are different from the name of the function that handles that route:

@app.route('/about')def about(): return "This is a notes app."

In this example, the function is called about, but the URL that users will visit is /about-de. This flexibility allows us to create friendly and semantically meaningful URLs while keeping clear function names in our code.

Testing POST requests with curl

To test POST requests without having to create an HTML form, we can use tools such as curl from the command line:

curl -X POST http://localhost:5000/contacto

This command will send a POST request to our path /contact and show us the response, including the HTTP status code.

The use of tools like curl is invaluable during development to quickly test our endpoints without the need to create full user interfaces.

The @route decorator in Flask is a versatile tool that allows us to create robust web applications and flexible APIs. Mastering its use with different HTTP methods and response types is essential for any web developer working with Python. I encourage you to experiment with HTML returns and explore other HTTP methods such as PUT and PATCH to expand your web development skills with Flask.

Contributions 4

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Segunda Clase no Carga, por favor confirmar si a algúna otra persona le sucede los mismo
![](https://static.platzi.com/media/user_upload/image-fe57824a-4e37-4f38-b0f8-8a052ecf20c8.jpg) Para entender el uso de los métodos GET y POST hice este pequeño gráfico donde intento explicar kis siguientes puntos: 1. Que sucede cuando se crea una instancia de Flask() 2. Que sucede cuando se define un endpoint o ruta url. 3. El funcionamiento de los métodos GET y POST. Con respecto a esto último, dejo la explicación con más detalle obtenido gracias a ChatGPT. ### ✔ **Explicación de GET (en azul)** * **Elementos mostrados en azul representan datos obtenidos con GET.** * Se ve que el formulario tiene etiquetas como **"Nombre:"** y **"Género:"**, que son datos visibles sin enviar nada al servidor. * También se muestra la opción de género **"Masculino"** y **"Femenino"**, lo que indica que GET recupera y muestra información en la página. ### ✔ **Explicación de POST (en rojo)** * **Elementos en rojo representan datos enviados con POST.** * El usuario ha ingresado el nombre **"Neicer"** y seleccionado **"Masculino"**, y estos datos han sido enviados al servidor. * El endpoint `/datos` recibe esta información en formato JSON.
Con templates puedes mantener separada la lógica de Python del HTML, lo que hace tu código más organizado y fácil de mantener. `<html><head>    <title>Mi Barbería</title></head><body>   

{{ titulo }}

   

{{ contenido }}

</body></html>` `@app.route('/pagina')def pagina():    return render_template('pagina.html',                           titulo='Barbería',                           contenido='Bienvenidos a nuestra barbería')`
Para todos aquellos que no tengan linux o mac pueden usar el programa postman o insomnia, ponen la url e igual pueden verificar la respuesta del programa: ![](https://static.platzi.com/media/user_upload/upload-4f02034d-55d4-45de-9bf0-caddc274e7b4.png)