owned this note
owned this note
Published
Linked with GitHub
---
slideOptions:
transition: slide
theme: white
---
# Diseño de un API RESTful
---
## ¿Qué es un API?
Application Program Interface
Una API es un conjunto de definiciones y protocolos que se utiliza para desarrollar e integrar distintas piezas de software.
---
## ¿Qué es un API REST?
REST, or REpresentational State Transfer, is an architectural style for providing standards between computer systems on the web, making it easier for systems to communicate with each other.
Es un estilo de arquitectura software, centrada en los recursos, que sirve para construir API sobre el protocolo HTTP.
---
## HTTP y REST
+ HTTP utiliza determinados verbos: GET, POST, PUT, PATCH, DELETE, etc.
+ Los recursos se identifican con una URI
`/preferencias`
+ Verbo HTTP + URI = endpoint
`GET /preferencias`
+ Un endpoint representa una acción sobre un recurso
+ Existe una correspondencia entre verbos y CRUD
---
```
GET /orders <---> orders (colección)
POST /orders <---> orders.push(data)
GET /orders/1 <---> orders[1]
PUT /orders/1 <---> orders[1] = data
GET /orders/1/lines <---> orders[1].lines
POST /orders/1/lines <---> orders[1].lines.push(data)
```
---
## Los recursos
+ Deben ser nombrados utilizando _nombres_
+ Las URI no deben contener acciones (verbos)
:no_entry_sign: `GET /crear_perfil`
:no_entry_sign: `GET /getAllUsers`
:white_check_mark: `POST /perfil`
+ Deben identificar a una entidad de negocio
---
## Las respuestas
+ Nunca debe responderse con texto plano
+ Utilizar `JSON` y por lo tanto:
`Content-Type: application/json`
+ Los códigos de la respuesta importan:
- `1xx` for information, `2xx` for success
- `3xx` for redirection, `4xx` for client errors
- `5xx` for server errors.
---
## Ejemplo de respuesta
```jsonld=
HTTP/1.1 201 Created
Content-Type: application/json
{
"order_id": "134234",
"customer": {
"client_id": 233231,
"name": "Óscar",
"surname": "García"
},
items:[ 1, 23, 123, 5, 52]
```
```jsonld=
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": "Expected at least two items in list."
}
```
---
## Colecciones: búsquedas, filtros, ordenación y paginación
Utiliza el campo `query` de la `URI`
+ `GET /client?sort=last_purchase`
+ `GET /client?company=3&zone=28`
+ `GET /client?search=garcia`
+ `GET /client?page=23`
---
## A jugar! :video_game:
- https://editor.swagger.io/
- [Ejemplo de definición OpenApi3](https://pastebin.com/3jKnTcyy)
Otros jugadores:
- Postman
- Stoplight.io
- Swagger.io