mirror of https://github.com/tiangolo/fastapi.git
🌐 Translate index to Spanish (#1201)
This commit is contained in:
parent
3b7e4e0544
commit
3a0c22ce7d
|
|
@ -2,7 +2,7 @@
|
||||||
<a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a>
|
<a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a>
|
||||||
</p>
|
</p>
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<em>FastAPI framework, high performance, easy to learn, fast to code, ready for production</em>
|
<em>FastAPI framework, alto desempeño, fácil de aprender, rápido de programar, listo para producción</em>
|
||||||
</p>
|
</p>
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://travis-ci.com/tiangolo/fastapi" target="_blank">
|
<a href="https://travis-ci.com/tiangolo/fastapi" target="_blank">
|
||||||
|
|
@ -21,29 +21,28 @@
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Documentation**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a>
|
**Documentación**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a>
|
||||||
|
|
||||||
**Source Code**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a>
|
**Código Fuente**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a>
|
||||||
|
|
||||||
---
|
---
|
||||||
|
FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python 3.6+ basado en las anotaciones de tipos estándar de Python.
|
||||||
|
|
||||||
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
|
Sus características principales son:
|
||||||
|
|
||||||
The key features are:
|
* **Rapidez**: Alto rendimiento, a la par con **NodeJS** y **Go** (gracias a Starlette y Pydantic). [Uno de los frameworks de Python más rápidos](#rendimiento).
|
||||||
|
|
||||||
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
|
* **Rápido de programar**: Incrementa la velocidad de desarrollo entre 200% y 300% *.
|
||||||
|
* **Menos errores**: Reduce los errores humanos (de programador) aproximadamente un 40% *.
|
||||||
|
* **Intuitivo**: Gran soporte en los editores con <abbr title="conocido en inglés como auto-complete, autocompletion, IntelliSense, completion">auto completado</abbr> en todas partes. Gasta menos tiempo <abbr title="buscando y corrigiendo errores">debugging</abbr>.
|
||||||
|
* **Fácil**: Está diseñado para ser fácil de usar y aprender. Gastando menos tiempo leyendo documentación.
|
||||||
|
* **Corto**: Minimiza la duplicación de código. Múltiples funcionalidades con cada declaración de parámetros. Menos errores.
|
||||||
|
* **Robusto**: Crea código listo para producción con documentación automática interactiva.
|
||||||
|
* **Basado en estándares**: Basado y totalmente compatible con los estándares abiertos para APIs: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> (conocido previamente como Swagger) y <a href="http://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>.
|
||||||
|
|
||||||
* **Fast to code**: Increase the speed to develop features by about 200% to 300% *.
|
<small>* Esta estimación está basada en pruebas con un equipo de desarrollo interno contruyendo aplicaciones listas para producción.</small>
|
||||||
* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *
|
|
||||||
* **Intuitive**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging.
|
|
||||||
* **Easy**: Designed to be easy to use and learn. Less time reading docs.
|
|
||||||
* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
|
|
||||||
* **Robust**: Get production-ready code. With automatic interactive documentation.
|
|
||||||
* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> (previously known as Swagger) and <a href="http://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>.
|
|
||||||
|
|
||||||
<small>* estimation based on tests on an internal development team, building production applications.</small>
|
## Opiniones
|
||||||
|
|
||||||
## Opinions
|
|
||||||
|
|
||||||
"*[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products.*"
|
"*[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products.*"
|
||||||
|
|
||||||
|
|
@ -77,24 +76,24 @@ The key features are:
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## **Typer**, the FastAPI of CLIs
|
## **Typer**, el FastAPI de las CLIs
|
||||||
|
|
||||||
<a href="https://typer.tiangolo.com" target="_blank"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style="width: 20%;"></a>
|
<a href="https://typer.tiangolo.com" target="_blank"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style="width: 20%;"></a>
|
||||||
|
|
||||||
If you are building a <abbr title="Command Line Interface">CLI</abbr> app to be used in the terminal instead of a web API, check out <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">**Typer**</a>.
|
Si estás construyendo un app de <abbr title="Interfaz de línea de comandos en español">CLI</abbr> para ser usada en la terminal en vez de una API web, fíjate en <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">**Typer**</a>.
|
||||||
|
|
||||||
**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀
|
**Typer** es el hermano menor de FastAPI. La intención es que sea el **FastAPI de las CLIs**. ⌨️ 🚀
|
||||||
|
|
||||||
## Requirements
|
## Requisitos
|
||||||
|
|
||||||
Python 3.6+
|
Python 3.6+
|
||||||
|
|
||||||
FastAPI stands on the shoulders of giants:
|
FastAPI está sobre los hombros de gigantes:
|
||||||
|
|
||||||
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> for the web parts.
|
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> para las partes web.
|
||||||
* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> for the data parts.
|
* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> para las partes de datos.
|
||||||
|
|
||||||
## Installation
|
## Instalación
|
||||||
|
|
||||||
<div class="termy">
|
<div class="termy">
|
||||||
|
|
||||||
|
|
@ -106,7 +105,7 @@ $ pip install fastapi
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
You will also need an ASGI server, for production such as <a href="http://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> or <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
También vas a necesitar un servidor ASGI para producción cómo <a href="http://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> o <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||||
|
|
||||||
<div class="termy">
|
<div class="termy">
|
||||||
|
|
||||||
|
|
@ -118,11 +117,11 @@ $ pip install uvicorn
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
## Example
|
## Ejemplo
|
||||||
|
|
||||||
### Create it
|
### Créalo
|
||||||
|
|
||||||
* Create a file `main.py` with:
|
* Crea un archivo `main.py` con:
|
||||||
|
|
||||||
```Python
|
```Python
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
|
@ -141,9 +140,9 @@ def read_item(item_id: int, q: str = None):
|
||||||
```
|
```
|
||||||
|
|
||||||
<details markdown="1">
|
<details markdown="1">
|
||||||
<summary>Or use <code>async def</code>...</summary>
|
<summary>O usa <code>async def</code>...</summary>
|
||||||
|
|
||||||
If your code uses `async` / `await`, use `async def`:
|
Si tu código usa `async` / `await`, usa `async def`:
|
||||||
|
|
||||||
```Python hl_lines="7 12"
|
```Python hl_lines="7 12"
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
|
@ -161,15 +160,15 @@ async def read_item(item_id: int, q: str = None):
|
||||||
return {"item_id": item_id, "q": q}
|
return {"item_id": item_id, "q": q}
|
||||||
```
|
```
|
||||||
|
|
||||||
**Note**:
|
**Nota**:
|
||||||
|
|
||||||
If you don't know, check the _"In a hurry?"_ section about <a href="https://fastapi.tiangolo.com/async/#in-a-hurry" target="_blank">`async` and `await` in the docs</a>.
|
Si no lo sabes, revisa la sección _"¿Con prisa?"_ sobre <a href="https://fastapi.tiangolo.com/es/async/#con-prisa" target="_blank">`async` y `await` en la documentación</a>.
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
### Run it
|
### Córrelo
|
||||||
|
|
||||||
Run the server with:
|
Corre el servidor con:
|
||||||
|
|
||||||
<div class="termy">
|
<div class="termy">
|
||||||
|
|
||||||
|
|
@ -186,54 +185,54 @@ $ uvicorn main:app --reload
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<details markdown="1">
|
<details markdown="1">
|
||||||
<summary>About the command <code>uvicorn main:app --reload</code>...</summary>
|
<summary>Sobre el comando <code>uvicorn main:app --reload</code>...</summary>
|
||||||
|
|
||||||
The command `uvicorn main:app` refers to:
|
El comando `uvicorn main:app` se refiere a:
|
||||||
|
|
||||||
* `main`: the file `main.py` (the Python "module").
|
* `main`: el archivo `main.py` (el"modulo" de Python).
|
||||||
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
|
* `app`: el objeto creado dentro de `main.py` con la línea `app = FastAPI()`.
|
||||||
* `--reload`: make the server restart after code changes. Only do this for development.
|
* `--reload`: hace que el servidor se reinicie después de cambios en el código. Esta opción solo debe ser usada en desarrollo.
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
### Check it
|
### Revísalo
|
||||||
|
|
||||||
Open your browser at <a href="http://127.0.0.1:8000/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>.
|
Abre tu navegador en <a href="http://127.0.0.1:8000/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>.
|
||||||
|
|
||||||
You will see the JSON response as:
|
Verás la respuesta de JSON cómo:
|
||||||
|
|
||||||
```JSON
|
```JSON
|
||||||
{"item_id": 5, "q": "somequery"}
|
{"item_id": 5, "q": "somequery"}
|
||||||
```
|
```
|
||||||
|
|
||||||
You already created an API that:
|
Ya creaste una API que:
|
||||||
|
|
||||||
* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`.
|
* Recibe HTTP requests en los _paths_ `/` y `/items/{item_id}`.
|
||||||
* Both _paths_ take `GET` <em>operations</em> (also known as HTTP _methods_).
|
* Ambos _paths_ toman <em>operaciones</em> `GET` (también conocido como HTTP _methods_).
|
||||||
* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`.
|
* El _path_ `/items/{item_id}` tiene un _path parameter_ `item_id` que debería ser un `int`.
|
||||||
* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`.
|
* El _path_ `/items/{item_id}` tiene un `str` _query parameter_ `q` opcional.
|
||||||
|
|
||||||
### Interactive API docs
|
### Documentación interactiva de APIs
|
||||||
|
|
||||||
Now go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
Ahora ve a <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||||
|
|
||||||
You will see the automatic interactive API documentation (provided by <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>):
|
Verás la documentación automática e interactiva de la API (proveída por <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>):
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
### Alternative API docs
|
### Documentación alternativa de la API
|
||||||
|
|
||||||
And now, go to <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
|
Ahora, ve a <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
|
||||||
|
|
||||||
You will see the alternative automatic documentation (provided by <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>):
|
Ahora verás la documentación automática alternativa (proveída por <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>):
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
## Example upgrade
|
## Mejora al ejemplo
|
||||||
|
|
||||||
Now modify the file `main.py` to receive a body from a `PUT` request.
|
Ahora modifica el archivo `main.py` para recibir un <abbr title="cuerpo del mensaje HTTP">body</abbr> del `PUT` request.
|
||||||
|
|
||||||
Declare the body using standard Python types, thanks to Pydantic.
|
Declara el body usando las declaraciones de tipo estándares de Python gracias a Pydantic.
|
||||||
|
|
||||||
```Python hl_lines="2 7 8 9 10 23 24 25"
|
```Python hl_lines="2 7 8 9 10 23 24 25"
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
|
@ -263,175 +262,175 @@ def update_item(item_id: int, item: Item):
|
||||||
return {"item_name": item.name, "item_id": item_id}
|
return {"item_name": item.name, "item_id": item_id}
|
||||||
```
|
```
|
||||||
|
|
||||||
The server should reload automatically (because you added `--reload` to the `uvicorn` command above).
|
El servidor debería recargar automáticamente (porque añadiste `--reload` al comando `uvicorn` que está más arriba).
|
||||||
|
|
||||||
### Interactive API docs upgrade
|
### Mejora a la documentación interactiva de APIs
|
||||||
|
|
||||||
Now go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
Ahora ve a <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||||
|
|
||||||
* The interactive API documentation will be automatically updated, including the new body:
|
* La documentación interactiva de la API se actualizará automáticamente, incluyendo el nuevo body:
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API:
|
* Haz clíck en el botón de "Try it out" que te permite llenar los parámetros e interactuar directamente con la API:
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
* Then click on the "Execute" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen:
|
* Luego haz clíck en el botón de "Execute". La interfaz de usuario se comunicará con tu API, enviará los parámetros y recibirá los resultados para mostrarlos en pantalla:
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
### Alternative API docs upgrade
|
### Mejora a la documentación alternativa de la API
|
||||||
|
|
||||||
And now, go to <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
|
Ahora, ve a <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
|
||||||
|
|
||||||
* The alternative documentation will also reflect the new query parameter and body:
|
* La documentación alternativa también reflejará el nuevo parámetro de query y el body:
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
### Recap
|
### Resumen
|
||||||
|
|
||||||
In summary, you declare **once** the types of parameters, body, etc. as function parameters.
|
En resumen, declaras los tipos de parámetros, body, etc. **una vez** como parámetros de la función.
|
||||||
|
|
||||||
You do that with standard modern Python types.
|
Lo haces con tipos modernos estándar de Python.
|
||||||
|
|
||||||
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
|
No tienes que aprender una sintáxis nueva, los métodos o clases de una library específica, etc.
|
||||||
|
|
||||||
Just standard **Python 3.6+**.
|
Solo **Python 3.6+** estándar.
|
||||||
|
|
||||||
For example, for an `int`:
|
Por ejemplo, para un `int`:
|
||||||
|
|
||||||
```Python
|
```Python
|
||||||
item_id: int
|
item_id: int
|
||||||
```
|
```
|
||||||
|
|
||||||
or for a more complex `Item` model:
|
o para un modelo más complejo de `Item`:
|
||||||
|
|
||||||
```Python
|
```Python
|
||||||
item: Item
|
item: Item
|
||||||
```
|
```
|
||||||
|
|
||||||
...and with that single declaration you get:
|
...y con esa única declaración obtienes:
|
||||||
|
|
||||||
* Editor support, including:
|
* Soporte del editor incluyendo:
|
||||||
* Completion.
|
* Auto completado.
|
||||||
* Type checks.
|
* Anotaciones de tipos.
|
||||||
* Validation of data:
|
* Validación de datos:
|
||||||
* Automatic and clear errors when the data is invalid.
|
* Errores automáticos y claros cuándo los datos son inválidos.
|
||||||
* Validation even for deeply nested JSON objects.
|
* Validación, incluso para objetos JSON profundamente anidados.
|
||||||
* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> of input data: coming from the network to Python data and types. Reading from:
|
* <abbr title="en inglés: serialization, parsing, marshalling">Conversión</abbr> de datos de input: viniendo de la red a datos y tipos de Python. Leyendo desde:
|
||||||
* JSON.
|
* JSON.
|
||||||
* Path parameters.
|
* Path parameters.
|
||||||
* Query parameters.
|
* Query parameters.
|
||||||
* Cookies.
|
* Cookies.
|
||||||
* Headers.
|
* Headers.
|
||||||
* Forms.
|
* Formularios.
|
||||||
* Files.
|
* Archivos.
|
||||||
* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> of output data: converting from Python data and types to network data (as JSON):
|
* <abbr title="en inglés: serialization, parsing, marshalling">Conversión</abbr> de datos de output: convirtiendo de datos y tipos de Python a datos para la red (como JSON):
|
||||||
* Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc).
|
* Convertir tipos de Python (`str`, `int`, `float`, `bool`, `list`, etc).
|
||||||
* `datetime` objects.
|
* Objetos `datetime`.
|
||||||
* `UUID` objects.
|
* Objetos `UUID`.
|
||||||
* Database models.
|
* Modelos de bases de datos.
|
||||||
* ...and many more.
|
* ...y muchos más.
|
||||||
* Automatic interactive API documentation, including 2 alternative user interfaces:
|
* Documentación automática e interactiva incluyendo 2 interfaces de usuario alternativas:
|
||||||
* Swagger UI.
|
* Swagger UI.
|
||||||
* ReDoc.
|
* ReDoc.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
Coming back to the previous code example, **FastAPI** will:
|
Volviendo al ejemplo de código anterior, **FastAPI** va a:
|
||||||
|
|
||||||
* Validate that there is an `item_id` in the path for `GET` and `PUT` requests.
|
* Validar que existe un `item_id` en el path para requests usando `GET` y `PUT`.
|
||||||
* Validate that the `item_id` is of type `int` for `GET` and `PUT` requests.
|
* Validar que el `item_id` es del tipo `int` para requests de tipo `GET` y `PUT`.
|
||||||
* If it is not, the client will see a useful, clear error.
|
* Si no lo es, el cliente verá un mensaje de error útil y claro.
|
||||||
* Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests.
|
* Revisar si existe un query parameter opcional llamado `q` (cómo en `http://127.0.0.1:8000/items/foo?q=somequery`) para requests de tipo `GET`.
|
||||||
* As the `q` parameter is declared with `= None`, it is optional.
|
* Como el parámetro `q` fue declarado con `= None` es opcional.
|
||||||
* Without the `None` it would be required (as is the body in the case with `PUT`).
|
* Sin el `None` sería obligatorio (cómo lo es el body en el caso con `PUT`).
|
||||||
* For `PUT` requests to `/items/{item_id}`, Read the body as JSON:
|
* Para requests de tipo `PUT` a `/items/{item_id}` leer el body como JSON:
|
||||||
* Check that it has a required attribute `name` that should be a `str`.
|
* Revisar si tiene un atributo requerido `name` que debe ser un `str`.
|
||||||
* Check that it has a required attribute `price` that has to be a `float`.
|
* Revisar si tiene un atributo requerido `price` que debe ser un `float`.
|
||||||
* Check that it has an optional attribute `is_offer`, that should be a `bool`, if present.
|
* Revisar si tiene un atributo opcional `is_offer`, que debe ser un `bool`si está presente.
|
||||||
* All this would also work for deeply nested JSON objects.
|
* Todo esto funcionaría para objetos JSON profundamente anidados.
|
||||||
* Convert from and to JSON automatically.
|
* Convertir de y a JSON automáticamente.
|
||||||
* Document everything with OpenAPI, that can be used by:
|
* Documentar todo con OpenAPI que puede ser usado por:
|
||||||
* Interactive documentation systems.
|
* Sistemas de documentación interactiva.
|
||||||
* Automatic client code generation systems, for many languages.
|
* Sistemas de generación automática de código de cliente para muchos lenguajes.
|
||||||
* Provide 2 interactive documentation web interfaces directly.
|
* Proveer directamente 2 interfaces de documentación web interactivas.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
We just scratched the surface, but you already get the idea of how it all works.
|
Hasta ahora, escasamente vimos lo básico pero ya tienes una idea de cómo funciona.
|
||||||
|
|
||||||
Try changing the line with:
|
Intenta cambiando la línea a:
|
||||||
|
|
||||||
```Python
|
```Python
|
||||||
return {"item_name": item.name, "item_id": item_id}
|
return {"item_name": item.name, "item_id": item_id}
|
||||||
```
|
```
|
||||||
|
|
||||||
...from:
|
...de:
|
||||||
|
|
||||||
```Python
|
```Python
|
||||||
... "item_name": item.name ...
|
... "item_name": item.name ...
|
||||||
```
|
```
|
||||||
|
|
||||||
...to:
|
...a:
|
||||||
|
|
||||||
```Python
|
```Python
|
||||||
... "item_price": item.price ...
|
... "item_price": item.price ...
|
||||||
```
|
```
|
||||||
|
|
||||||
...and see how your editor will auto-complete the attributes and know their types:
|
... y mira como el editor va a auto-completar los atributos y sabrá sus tipos:
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
For a more complete example including more features, see the <a href="https://fastapi.tiangolo.com/tutorial/">Tutorial - User Guide</a>.
|
Para un ejemplo más completo que incluye más características ve el <a href="https://fastapi.tiangolo.com/tutorial/">Tutorial - Guía de Usuario</a>.
|
||||||
|
|
||||||
**Spoiler alert**: the tutorial - user guide includes:
|
**Spoiler alert**: el Tutorial - Guía de Usuario incluye:
|
||||||
|
|
||||||
* Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**.
|
* Declaración de **parámetros** en otros lugares diferentes cómo los: **headers**, **cookies**, **formularios** y **archivos**.
|
||||||
* How to set **validation constraints** as `maximum_length` or `regex`.
|
* Cómo agregar **requisitos de validación** cómo `maximum_length` o `regex`.
|
||||||
* A very powerful and easy to use **<abbr title="also known as components, resources, providers, services, injectables">Dependency Injection</abbr>** system.
|
* Un sistema de **<abbr title="también conocido en inglés cómo: components, resources, providers, services, injectables">Dependency Injection</abbr>** poderoso y fácil de usar.
|
||||||
* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth.
|
* Seguridad y autenticación incluyendo soporte para **OAuth2** con **JWT tokens** y **HTTP Basic** auth.
|
||||||
* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic).
|
* Técnicas más avanzadas, pero igual de fáciles, para declarar **modelos de JSON profundamente anidados** (gracias a Pydantic).
|
||||||
* Many extra features (thanks to Starlette) as:
|
* Muchas características extra (gracias a Starlette) como:
|
||||||
* **WebSockets**
|
* **WebSockets**
|
||||||
* **GraphQL**
|
* **GraphQL**
|
||||||
* extremely easy tests based on `requests` and `pytest`
|
* pruebas extremadamente fáciles con `requests` y `pytest`
|
||||||
* **CORS**
|
* **CORS**
|
||||||
* **Cookie Sessions**
|
* **Cookie Sessions**
|
||||||
* ...and more.
|
* ...y mucho más.
|
||||||
|
|
||||||
## Performance
|
## Rendimiento
|
||||||
|
|
||||||
Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">one of the fastest Python frameworks available</a>, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)
|
Benchmarks independientes de TechEmpower muestran que aplicaciones de **FastAPI** corriendo con Uvicorn cómo <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">uno de los frameworks de Python más rápidos</a>, únicamente debajo de Starlette y Uvicorn (usados internamente por FastAPI). (*)
|
||||||
|
|
||||||
To understand more about it, see the section <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a>.
|
Para entender más al respecto revisa la sección <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a>.
|
||||||
|
|
||||||
## Optional Dependencies
|
## Dependencias Opcionales
|
||||||
|
|
||||||
Used by Pydantic:
|
Usadas por Pydantic:
|
||||||
|
|
||||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - for faster JSON <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>.
|
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - para <abbr title="convertir el string que viene de un HTTP request a datos de Python">"parsing"</abbr> de JSON más rápido.
|
||||||
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - for email validation.
|
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - para validación de emails.
|
||||||
|
|
||||||
Used by Starlette:
|
Usados por Starlette:
|
||||||
|
|
||||||
* <a href="http://docs.python-requests.org" target="_blank"><code>requests</code></a> - Required if you want to use the `TestClient`.
|
* <a href="http://docs.python-requests.org" target="_blank"><code>requests</code></a> - Requerido si quieres usar el `TestClient`.
|
||||||
* <a href="https://github.com/Tinche/aiofiles" target="_blank"><code>aiofiles</code></a> - Required if you want to use `FileResponse` or `StaticFiles`.
|
* <a href="https://github.com/Tinche/aiofiles" target="_blank"><code>aiofiles</code></a> - Requerido si quieres usar `FileResponse` o `StaticFiles`.
|
||||||
* <a href="http://jinja.pocoo.org" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration.
|
* <a href="http://jinja.pocoo.org" target="_blank"><code>jinja2</code></a> - Requerido si quieres usar la configuración por defecto de templates.
|
||||||
* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`.
|
* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Requerido si quieres dar soporte a <abbr title="convertir el string que viene de un HTTP request a datos de Python">"parsing"</abbr> de formularios, con `request.form()`.
|
||||||
* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support.
|
* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Requerido para dar soporte a `SessionMiddleware`.
|
||||||
* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
|
* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Requerido para dar soporte al `SchemaGenerator` de Starlette (probablemente no lo necesites con FastAPI).
|
||||||
* <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Required for `GraphQLApp` support.
|
* <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Requerido para dar soporte a `GraphQLApp`.
|
||||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`.
|
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Requerido si quieres usar `UJSONResponse`.
|
||||||
|
|
||||||
Used by FastAPI / Starlette:
|
Usado por FastAPI / Starlette:
|
||||||
|
|
||||||
* <a href="http://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application.
|
* <a href="http://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - para el servidor que carga y sirve tu aplicación.
|
||||||
* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`.
|
* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Requerido si quieres usar `ORJSONResponse`.
|
||||||
|
|
||||||
You can install all of these with `pip install fastapi[all]`.
|
Puedes instalarlos con `pip install fastapi[all]`.
|
||||||
|
|
||||||
## License
|
## Licencia
|
||||||
|
|
||||||
This project is licensed under the terms of the MIT license.
|
Este proyecto está licenciado bajo los términos de la licencia del MIT.
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue