SlideShare a Scribd company logo
Aplicaciones
RestFul con
Asp.net Core
Germán Küber
Software Architect
http://germankuber.com.ar
@germankuber
@netbaires
1. ¿Por qué la necesidad de RESTFull?
2. ¿Qué es RESTFull?
3. Los 6 conceptos de RESTFull
4. Como implementar RESTFull en Asp.net Core
5. Conclusión
¿Qué vamos a ver?
Las 8 Falacias de la Computación Distribuida
1. La red es confiable
2. La latencia es cero, la latencia no es problema
3. El ancho de banda es infinito
4. La red es segura
5. La topología no cambia
6. Hay uno y sólo un administrador
7. El coste de transporte es cero
8. La red es homogénea http://www.rgoarchitects.com/Files/fallacies.pdf
API
Application Programming Interface
REST
Representational State Transfer
¿Qué no es REST?
• RPC
• SOAP and WSDL
• HTTP
• URIs
¿Qué no es REST?
/getAllUsers
/getUserById?id=3
/getUserWithProfile?id=4&json=true
/updateProfile?name=harry
/deleteUserByName?name=jhon
¿Qué SI es REST?
/users
/users/3
/users/3/profiles
/users?email=example@mail.com
/users/3/profiles/permissions
Las 7 propiedades de RESTFull
1. Rendimiento
2. Escalabilidad
3. Simplicidad
4. Modificabilidad
5. Visibilidad
6. Portabilidad
7. Confiabilidad
https://en.wikipedia.org/wiki/Representational_state_transfer#Architectural_properties
6 constraints
1. Client – Server
2. Uniform Interface
3. Statelessness
4. Cacheable
5. Layered System
6. Code on Demand (opcional)
Client - Server
Cliente y servidor están separados
(Cliente y servidor pueden evolucionar por separado)
dotnet new webapi -n NetConf-Demo>
> dotnet run
dotnet add package Swashbuckle.AspNetCore
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});
}
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseMvc();
}
>
http://localhost:5000/swagger/
Uniform Interface
API y los consumidores comparten una sola interfaz,
técnica: URI, Method, Media Type
GET
/users
/users?name=test
/users/1
/users/4/comments
POST
/users
{…}
/comments
{…}
PUT
/users/3
{…}
DELETE
/users/3
/users/3/comments
/users/4/commetns/3
[HttpGet("{id}")]
public User Get(int id)
[HttpGet("{id}/comments")]
public User Get(int id)
[HttpGet("{id:int}/comments/{commentId:int}")]
public List<Comment> Get(int id,int commentId)
[HttpPost]
public void Post([FromBody]string value)
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
Microsoft.AspNetCore.Mvc
[HttpGet("")]
public IEnumerable<User> Get([FromQuery]int pageIndex = 1,
[FromQuery]int pageSize = 10)
/api/users?pageIndex=4&pageSize=5
{
"results": [ {author}, {author}, …],
"metadata": {
"previousPage": "/api/users?pageIndex=03&pageSize=45",
"nextPage": "/api/users?pageIndex=05&pageSize=45"
}
}
dotnet add package Microsoft.AspNetCore.Mvc.Versioning
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddApiVersioning(options =>
{
options.ReportApiVersions = true;
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
});
}
Startup.cs
>
ApiVersion("1.0")]
[Route("api/users")]
public class UsersController : Controller
[ApiVersion("2.0")]
[ApiVersion("3.0")]
[Route("api/v{ver:apiVersion}/users")]
public class UsersV2Controller : Controller
{
[HttpGet, MapToApiVersion("3.0")]
public IActionResult GetV3() => Content("Version 3");
[HttpGet, MapToApiVersion("2.0")]
public IActionResult GetV2() => Content("Version 2");
}
[ApiVersion("5.0", Deprecated = true)]
[Route("api/v{ver:apiVersion}/users")]
public class UsersV1Controller : Controller
Microsoft.AspNetCore.Mvc.Versioning
> dotnet add package Microsoft.AspNetCore.Mvc.Formatters.Xml
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.OutputFormatters.RemoveType<TextOutputFormatter>();
options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
});
}
Statelessness
Estado contenido dentro de la propia solicitud
> dotnet add package RiskFirst.Hateoas
services.AddLinks(config =>
{
config.AddPolicy<User>(policy =>
{
policy.RequireSelfLink()
.RequireRoutedLink("all", "GetAllModelsRoute")
.RequireRoutedLink("delete", "DeleteModelRoute",
x => new { id = x.Id });
});
});
public UsersController(ILinksService linksService)
Startup.cs
UsersController.cs
public UsersController(ILinksService linksService)
UsersController.cs
[HttpGet("{id}", Name = "GetModelRoute")]
public async Task<User> GetMyModel(int id)
{
var model = await userRepository.GetById(id);
await _linksService.AddLinksAsync(user);
return user;
}
RiskFirst.Hateoas
Startup.cs
UsersController.cs
{
"id": 1234,
"name": "Bob",
"userName": "SurT",
"_links": [
{ "rel": "self", "href": "/people/1234” },
{
"rel": "update-person",
"href": "/people/1234",
"method": "PUT"
},
{
"rel": "delete-person",
"href": "/people/1234",
"method": "DELETE"
}
]
}
Hateoas
Cacheable
Cada respuesta/mensaje debe indicar explícitamente
si se puede almacenar en caché o no.
> dotnet add package Marvin.Cache.Headers --version 1.0.0
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpCacheHeaders();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseHttpCacheHeaders();
app.UseMvc();
}
Startup.cs
dotnet add package --version 1.0.0
Response Header
{
"last-modified": "Sun, 08 Oct 2017 15:00:58 GMT",
"etag": "949E486E372B3C6BA94E7D80AA67E512",
"cache-control": "public,max-age=60",
"expires": "Sun, 08 Oct 2017 15:01:58 GMT"
}
Marvin.Cache.Headers
Request Header
Cliente 1 Cliente 2 API
G E T api/authors/{id}
G E T api/authors/{id}
PUT api/authors/{id}
Concurrencia
PUT api/authors/{id}
Cliente 1 Cliente 2 API
Concurrencia en RESTFull
G E T api/authors/{id}
PUT api/authors/{id}
If-Match: “123456789”
2 0 0 Ok, ETag: “123456789”
G E T api/authors/{id}
200/204, ETag: “987654321”
PUT api/authors/{id}
If-Match: “123456789”
412 Precondition failed
2 0 0 Ok, ETag: “123456789”
Layered System
El cliente no puede saber a qué capa está conectado
FIREWALL GATEWAY
LOAD
BALANCER
CLIENTE
Layered System
Code on Demand
(optional)
Servidor puede extender la funcionalidad del cliente
RESUMEN
• No toda api es una api RESTFull
• Debemos diseñar siempre pensando en nuestros clientes
• No debemos forzar la implementación de RESTFull
• RESTFull prepara nuestras API para el futuro
Recursos
Microsoft REST API Guidelines
https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md
Asp.net Core
https://docs.microsoft.com/en-us/aspnet/core/
Roy T. Fielding's dissertation
http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm
Gracias
Germán Küber
Software Architect
http://germankuber.com.ar
@germankuber

More Related Content

What's hot

Microservices: Lessons Learned
Microservices: Lessons LearnedMicroservices: Lessons Learned
Microservices: Lessons Learned
Weaveworks
 
OpenStack - Tzu-Mainn Chen, Marek Aufart, Petr Blaho - ManageIQ Design Summit...
OpenStack - Tzu-Mainn Chen, Marek Aufart, Petr Blaho - ManageIQ Design Summit...OpenStack - Tzu-Mainn Chen, Marek Aufart, Petr Blaho - ManageIQ Design Summit...
OpenStack - Tzu-Mainn Chen, Marek Aufart, Petr Blaho - ManageIQ Design Summit...
ManageIQ
 
Microservices with Netflix OSS and Spring Cloud
Microservices with Netflix OSS and Spring CloudMicroservices with Netflix OSS and Spring Cloud
Microservices with Netflix OSS and Spring Cloud
acogoluegnes
 
API Versioning in the Cloud
API Versioning in the CloudAPI Versioning in the Cloud
API Versioning in the Cloud
Cloud Elements
 
技术雷达——新技术的生产力
技术雷达——新技术的生产力技术雷达——新技术的生产力
技术雷达——新技术的生产力
Justina Chen
 
Container Management - Federico Simoncelli - ManageIQ Design Summit 2016
Container Management - Federico Simoncelli - ManageIQ Design Summit 2016Container Management - Federico Simoncelli - ManageIQ Design Summit 2016
Container Management - Federico Simoncelli - ManageIQ Design Summit 2016
ManageIQ
 
stackconf 2021 | How we finally migrated an eCommerce-Platform to GCP
stackconf 2021 | How we finally migrated an eCommerce-Platform to GCPstackconf 2021 | How we finally migrated an eCommerce-Platform to GCP
stackconf 2021 | How we finally migrated an eCommerce-Platform to GCP
NETWAYS
 
(PFC304) Effective Interprocess Communications in the Cloud: The Pros and Con...
(PFC304) Effective Interprocess Communications in the Cloud: The Pros and Con...(PFC304) Effective Interprocess Communications in the Cloud: The Pros and Con...
(PFC304) Effective Interprocess Communications in the Cloud: The Pros and Con...
Amazon Web Services
 
2019 Lightning Talk: Discovery, Consul and Inversion of Control for the infr...
2019  Lightning Talk: Discovery, Consul and Inversion of Control for the infr...2019  Lightning Talk: Discovery, Consul and Inversion of Control for the infr...
2019 Lightning Talk: Discovery, Consul and Inversion of Control for the infr...
Pierre Souchay
 
Kong API
Kong APIKong API
Kong API
Patrick Pierson
 
9 plugin Cloudstack Developer Day
9 plugin Cloudstack Developer Day9 plugin Cloudstack Developer Day
9 plugin Cloudstack Developer Day
Kimihiko Kitase
 
Monitoring Kubernetes with Prometheus
Monitoring Kubernetes with PrometheusMonitoring Kubernetes with Prometheus
Monitoring Kubernetes with Prometheus
Tobias Schmidt
 
APIdays Paris 2018 - Secure & Manage APIs with GraphQL, Ozair Sheikh, Directo...
APIdays Paris 2018 - Secure & Manage APIs with GraphQL, Ozair Sheikh, Directo...APIdays Paris 2018 - Secure & Manage APIs with GraphQL, Ozair Sheikh, Directo...
APIdays Paris 2018 - Secure & Manage APIs with GraphQL, Ozair Sheikh, Directo...
apidays
 
OpenStack and Containers - Will they blend? A prequel. SF Bay OpenStack Meetup
OpenStack and Containers - Will they blend? A prequel. SF Bay OpenStack MeetupOpenStack and Containers - Will they blend? A prequel. SF Bay OpenStack Meetup
OpenStack and Containers - Will they blend? A prequel. SF Bay OpenStack Meetup
John Starmer
 
API Gateway study
API Gateway studyAPI Gateway study
API Gateway study
Rafael Gonzaga
 
5 lessons learned for Successful Migration to Confluent Cloud
5 lessons learned for  Successful Migration to Confluent Cloud5 lessons learned for  Successful Migration to Confluent Cloud
5 lessons learned for Successful Migration to Confluent Cloud
Natan Silnitsky
 
03 spring cloud eureka service discovery
03 spring cloud eureka   service discovery03 spring cloud eureka   service discovery
03 spring cloud eureka service discovery
Janani Velmurugan
 
Multi cloud Serverless platform using Kubernetes
Multi cloud Serverless platform using KubernetesMulti cloud Serverless platform using Kubernetes
Multi cloud Serverless platform using Kubernetes
Fahri Yardımcı
 
API Gateway report
API Gateway reportAPI Gateway report
API Gateway report
Gleicon Moraes
 
Introduction to Kong API Gateway
Introduction to Kong API GatewayIntroduction to Kong API Gateway
Introduction to Kong API Gateway
Yohann Ciurlik
 

What's hot (20)

Microservices: Lessons Learned
Microservices: Lessons LearnedMicroservices: Lessons Learned
Microservices: Lessons Learned
 
OpenStack - Tzu-Mainn Chen, Marek Aufart, Petr Blaho - ManageIQ Design Summit...
OpenStack - Tzu-Mainn Chen, Marek Aufart, Petr Blaho - ManageIQ Design Summit...OpenStack - Tzu-Mainn Chen, Marek Aufart, Petr Blaho - ManageIQ Design Summit...
OpenStack - Tzu-Mainn Chen, Marek Aufart, Petr Blaho - ManageIQ Design Summit...
 
Microservices with Netflix OSS and Spring Cloud
Microservices with Netflix OSS and Spring CloudMicroservices with Netflix OSS and Spring Cloud
Microservices with Netflix OSS and Spring Cloud
 
API Versioning in the Cloud
API Versioning in the CloudAPI Versioning in the Cloud
API Versioning in the Cloud
 
技术雷达——新技术的生产力
技术雷达——新技术的生产力技术雷达——新技术的生产力
技术雷达——新技术的生产力
 
Container Management - Federico Simoncelli - ManageIQ Design Summit 2016
Container Management - Federico Simoncelli - ManageIQ Design Summit 2016Container Management - Federico Simoncelli - ManageIQ Design Summit 2016
Container Management - Federico Simoncelli - ManageIQ Design Summit 2016
 
stackconf 2021 | How we finally migrated an eCommerce-Platform to GCP
stackconf 2021 | How we finally migrated an eCommerce-Platform to GCPstackconf 2021 | How we finally migrated an eCommerce-Platform to GCP
stackconf 2021 | How we finally migrated an eCommerce-Platform to GCP
 
(PFC304) Effective Interprocess Communications in the Cloud: The Pros and Con...
(PFC304) Effective Interprocess Communications in the Cloud: The Pros and Con...(PFC304) Effective Interprocess Communications in the Cloud: The Pros and Con...
(PFC304) Effective Interprocess Communications in the Cloud: The Pros and Con...
 
2019 Lightning Talk: Discovery, Consul and Inversion of Control for the infr...
2019  Lightning Talk: Discovery, Consul and Inversion of Control for the infr...2019  Lightning Talk: Discovery, Consul and Inversion of Control for the infr...
2019 Lightning Talk: Discovery, Consul and Inversion of Control for the infr...
 
Kong API
Kong APIKong API
Kong API
 
9 plugin Cloudstack Developer Day
9 plugin Cloudstack Developer Day9 plugin Cloudstack Developer Day
9 plugin Cloudstack Developer Day
 
Monitoring Kubernetes with Prometheus
Monitoring Kubernetes with PrometheusMonitoring Kubernetes with Prometheus
Monitoring Kubernetes with Prometheus
 
APIdays Paris 2018 - Secure & Manage APIs with GraphQL, Ozair Sheikh, Directo...
APIdays Paris 2018 - Secure & Manage APIs with GraphQL, Ozair Sheikh, Directo...APIdays Paris 2018 - Secure & Manage APIs with GraphQL, Ozair Sheikh, Directo...
APIdays Paris 2018 - Secure & Manage APIs with GraphQL, Ozair Sheikh, Directo...
 
OpenStack and Containers - Will they blend? A prequel. SF Bay OpenStack Meetup
OpenStack and Containers - Will they blend? A prequel. SF Bay OpenStack MeetupOpenStack and Containers - Will they blend? A prequel. SF Bay OpenStack Meetup
OpenStack and Containers - Will they blend? A prequel. SF Bay OpenStack Meetup
 
API Gateway study
API Gateway studyAPI Gateway study
API Gateway study
 
5 lessons learned for Successful Migration to Confluent Cloud
5 lessons learned for  Successful Migration to Confluent Cloud5 lessons learned for  Successful Migration to Confluent Cloud
5 lessons learned for Successful Migration to Confluent Cloud
 
03 spring cloud eureka service discovery
03 spring cloud eureka   service discovery03 spring cloud eureka   service discovery
03 spring cloud eureka service discovery
 
Multi cloud Serverless platform using Kubernetes
Multi cloud Serverless platform using KubernetesMulti cloud Serverless platform using Kubernetes
Multi cloud Serverless platform using Kubernetes
 
API Gateway report
API Gateway reportAPI Gateway report
API Gateway report
 
Introduction to Kong API Gateway
Introduction to Kong API GatewayIntroduction to Kong API Gateway
Introduction to Kong API Gateway
 

Similar to Api RESTFull

C#on linux
C#on linuxC#on linux
C#on linux
AvarinTalks
 
.NET Core Apps: Design & Development
.NET Core Apps: Design & Development.NET Core Apps: Design & Development
.NET Core Apps: Design & Development
GlobalLogic Ukraine
 
ASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline Internals
Lukasz Lysik
 
Asp Net Architecture
Asp Net ArchitectureAsp Net Architecture
Asp Net Architecture
Juan Jose Gonzalez Faundez
 
Challenges in a Microservices Age: Monitoring, Logging and Tracing on Red Hat...
Challenges in a Microservices Age: Monitoring, Logging and Tracing on Red Hat...Challenges in a Microservices Age: Monitoring, Logging and Tracing on Red Hat...
Challenges in a Microservices Age: Monitoring, Logging and Tracing on Red Hat...
Martin Etmajer
 
Stephane Lapointe, Frank Boucher & Alexandre Brisebois: Les micro-services et...
Stephane Lapointe, Frank Boucher & Alexandre Brisebois: Les micro-services et...Stephane Lapointe, Frank Boucher & Alexandre Brisebois: Les micro-services et...
Stephane Lapointe, Frank Boucher & Alexandre Brisebois: Les micro-services et...
MSDEVMTL
 
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexus
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexusMicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexus
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexus
Emily Jiang
 
Marata
MarataMarata
NuGet 3.0 - Transitioning from OData to JSON-LD
NuGet 3.0 - Transitioning from OData to JSON-LDNuGet 3.0 - Transitioning from OData to JSON-LD
NuGet 3.0 - Transitioning from OData to JSON-LD
Jeff Handley
 
Devfest 2023 - Service Weaver Introduction - Taipei.pdf
Devfest 2023 - Service Weaver Introduction - Taipei.pdfDevfest 2023 - Service Weaver Introduction - Taipei.pdf
Devfest 2023 - Service Weaver Introduction - Taipei.pdf
KAI CHU CHUNG
 
Spring boot microservice metrics monitoring
Spring boot   microservice metrics monitoringSpring boot   microservice metrics monitoring
Spring boot microservice metrics monitoring
Oracle Korea
 
Spring Boot - Microservice Metrics Monitoring
Spring Boot - Microservice Metrics MonitoringSpring Boot - Microservice Metrics Monitoring
Spring Boot - Microservice Metrics Monitoring
DonghuKIM2
 
Getting Started with API Management
Getting Started with API ManagementGetting Started with API Management
Getting Started with API Management
Revelation Technologies
 
Vijay Oscon
Vijay OsconVijay Oscon
Vijay Oscon
vijayrvr
 
Scale and Load Testing of Micro-Service
Scale and Load Testing of Micro-ServiceScale and Load Testing of Micro-Service
Scale and Load Testing of Micro-Service
IRJET Journal
 
Cloud nativemicroservices jax-london2020
Cloud nativemicroservices   jax-london2020Cloud nativemicroservices   jax-london2020
Cloud nativemicroservices jax-london2020
Emily Jiang
 
Cloud nativemicroservices jax-london2020
Cloud nativemicroservices   jax-london2020Cloud nativemicroservices   jax-london2020
Cloud nativemicroservices jax-london2020
Emily Jiang
 
New and smart way to develop microservice for istio with micro profile
New and smart way to develop microservice for istio with micro profileNew and smart way to develop microservice for istio with micro profile
New and smart way to develop microservice for istio with micro profile
Emily Jiang
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
Lokesh Singrol
 
All About Microservices and OpenSource Microservice Frameworks
All About Microservices and OpenSource Microservice FrameworksAll About Microservices and OpenSource Microservice Frameworks
All About Microservices and OpenSource Microservice Frameworks
Mohammad Asif Siddiqui
 

Similar to Api RESTFull (20)

C#on linux
C#on linuxC#on linux
C#on linux
 
.NET Core Apps: Design & Development
.NET Core Apps: Design & Development.NET Core Apps: Design & Development
.NET Core Apps: Design & Development
 
ASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline Internals
 
Asp Net Architecture
Asp Net ArchitectureAsp Net Architecture
Asp Net Architecture
 
Challenges in a Microservices Age: Monitoring, Logging and Tracing on Red Hat...
Challenges in a Microservices Age: Monitoring, Logging and Tracing on Red Hat...Challenges in a Microservices Age: Monitoring, Logging and Tracing on Red Hat...
Challenges in a Microservices Age: Monitoring, Logging and Tracing on Red Hat...
 
Stephane Lapointe, Frank Boucher & Alexandre Brisebois: Les micro-services et...
Stephane Lapointe, Frank Boucher & Alexandre Brisebois: Les micro-services et...Stephane Lapointe, Frank Boucher & Alexandre Brisebois: Les micro-services et...
Stephane Lapointe, Frank Boucher & Alexandre Brisebois: Les micro-services et...
 
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexus
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexusMicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexus
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexus
 
Marata
MarataMarata
Marata
 
NuGet 3.0 - Transitioning from OData to JSON-LD
NuGet 3.0 - Transitioning from OData to JSON-LDNuGet 3.0 - Transitioning from OData to JSON-LD
NuGet 3.0 - Transitioning from OData to JSON-LD
 
Devfest 2023 - Service Weaver Introduction - Taipei.pdf
Devfest 2023 - Service Weaver Introduction - Taipei.pdfDevfest 2023 - Service Weaver Introduction - Taipei.pdf
Devfest 2023 - Service Weaver Introduction - Taipei.pdf
 
Spring boot microservice metrics monitoring
Spring boot   microservice metrics monitoringSpring boot   microservice metrics monitoring
Spring boot microservice metrics monitoring
 
Spring Boot - Microservice Metrics Monitoring
Spring Boot - Microservice Metrics MonitoringSpring Boot - Microservice Metrics Monitoring
Spring Boot - Microservice Metrics Monitoring
 
Getting Started with API Management
Getting Started with API ManagementGetting Started with API Management
Getting Started with API Management
 
Vijay Oscon
Vijay OsconVijay Oscon
Vijay Oscon
 
Scale and Load Testing of Micro-Service
Scale and Load Testing of Micro-ServiceScale and Load Testing of Micro-Service
Scale and Load Testing of Micro-Service
 
Cloud nativemicroservices jax-london2020
Cloud nativemicroservices   jax-london2020Cloud nativemicroservices   jax-london2020
Cloud nativemicroservices jax-london2020
 
Cloud nativemicroservices jax-london2020
Cloud nativemicroservices   jax-london2020Cloud nativemicroservices   jax-london2020
Cloud nativemicroservices jax-london2020
 
New and smart way to develop microservice for istio with micro profile
New and smart way to develop microservice for istio with micro profileNew and smart way to develop microservice for istio with micro profile
New and smart way to develop microservice for istio with micro profile
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
 
All About Microservices and OpenSource Microservice Frameworks
All About Microservices and OpenSource Microservice FrameworksAll About Microservices and OpenSource Microservice Frameworks
All About Microservices and OpenSource Microservice Frameworks
 

More from Germán Küber

Explorando el Diseño de la Memoria en Rust
Explorando el Diseño de la Memoria en RustExplorando el Diseño de la Memoria en Rust
Explorando el Diseño de la Memoria en Rust
Germán Küber
 
De Código a Ejecución: El Papel Fundamental del MSIL en .NET
De Código a Ejecución: El Papel Fundamental del MSIL en .NETDe Código a Ejecución: El Papel Fundamental del MSIL en .NET
De Código a Ejecución: El Papel Fundamental del MSIL en .NET
Germán Küber
 
Mev Rapido.pptx
Mev Rapido.pptxMev Rapido.pptx
Mev Rapido.pptx
Germán Küber
 
Que son los smart contracts.pptx
Que son los smart contracts.pptxQue son los smart contracts.pptx
Que son los smart contracts.pptx
Germán Küber
 
De 0 a blockchain developer en 3 meses
De 0 a blockchain developer en 3 mesesDe 0 a blockchain developer en 3 meses
De 0 a blockchain developer en 3 meses
Germán Küber
 
Patrones funcionales
Patrones funcionalesPatrones funcionales
Patrones funcionales
Germán Küber
 
Patrones de diseño en solidity
Patrones de diseño en solidityPatrones de diseño en solidity
Patrones de diseño en solidity
Germán Küber
 
Vertical slice architecture
Vertical slice architectureVertical slice architecture
Vertical slice architecture
Germán Küber
 
De 0 a blockchain developer en 3 meses
De 0 a blockchain developer en 3 mesesDe 0 a blockchain developer en 3 meses
De 0 a blockchain developer en 3 meses
Germán Küber
 
Diamon pattern presentation
Diamon pattern presentationDiamon pattern presentation
Diamon pattern presentation
Germán Küber
 
Patrones funcionales
Patrones funcionalesPatrones funcionales
Patrones funcionales
Germán Küber
 
Defensive code
Defensive codeDefensive code
Defensive code
Germán Küber
 
Programación Funcional C#
Programación Funcional C#Programación Funcional C#
Programación Funcional C#
Germán Küber
 
Unit testing consejos
Unit testing   consejosUnit testing   consejos
Unit testing consejos
Germán Küber
 
Defensive code C#
Defensive code C#Defensive code C#
Defensive code C#
Germán Küber
 
Event sourcing
Event sourcingEvent sourcing
Event sourcing
Germán Küber
 
C sharp 8
C sharp 8C sharp 8
C sharp 8
Germán Küber
 
Arquitectura en aplicaciones Angular y buenas practicas.
Arquitectura en aplicaciones Angular y buenas practicas.Arquitectura en aplicaciones Angular y buenas practicas.
Arquitectura en aplicaciones Angular y buenas practicas.
Germán Küber
 
Un mundo sin if. generics al rescate
Un mundo sin if. generics al rescateUn mundo sin if. generics al rescate
Un mundo sin if. generics al rescate
Germán Küber
 
Azure 360º para Desarrolaldores
Azure 360º para DesarrolaldoresAzure 360º para Desarrolaldores
Azure 360º para Desarrolaldores
Germán Küber
 

More from Germán Küber (20)

Explorando el Diseño de la Memoria en Rust
Explorando el Diseño de la Memoria en RustExplorando el Diseño de la Memoria en Rust
Explorando el Diseño de la Memoria en Rust
 
De Código a Ejecución: El Papel Fundamental del MSIL en .NET
De Código a Ejecución: El Papel Fundamental del MSIL en .NETDe Código a Ejecución: El Papel Fundamental del MSIL en .NET
De Código a Ejecución: El Papel Fundamental del MSIL en .NET
 
Mev Rapido.pptx
Mev Rapido.pptxMev Rapido.pptx
Mev Rapido.pptx
 
Que son los smart contracts.pptx
Que son los smart contracts.pptxQue son los smart contracts.pptx
Que son los smart contracts.pptx
 
De 0 a blockchain developer en 3 meses
De 0 a blockchain developer en 3 mesesDe 0 a blockchain developer en 3 meses
De 0 a blockchain developer en 3 meses
 
Patrones funcionales
Patrones funcionalesPatrones funcionales
Patrones funcionales
 
Patrones de diseño en solidity
Patrones de diseño en solidityPatrones de diseño en solidity
Patrones de diseño en solidity
 
Vertical slice architecture
Vertical slice architectureVertical slice architecture
Vertical slice architecture
 
De 0 a blockchain developer en 3 meses
De 0 a blockchain developer en 3 mesesDe 0 a blockchain developer en 3 meses
De 0 a blockchain developer en 3 meses
 
Diamon pattern presentation
Diamon pattern presentationDiamon pattern presentation
Diamon pattern presentation
 
Patrones funcionales
Patrones funcionalesPatrones funcionales
Patrones funcionales
 
Defensive code
Defensive codeDefensive code
Defensive code
 
Programación Funcional C#
Programación Funcional C#Programación Funcional C#
Programación Funcional C#
 
Unit testing consejos
Unit testing   consejosUnit testing   consejos
Unit testing consejos
 
Defensive code C#
Defensive code C#Defensive code C#
Defensive code C#
 
Event sourcing
Event sourcingEvent sourcing
Event sourcing
 
C sharp 8
C sharp 8C sharp 8
C sharp 8
 
Arquitectura en aplicaciones Angular y buenas practicas.
Arquitectura en aplicaciones Angular y buenas practicas.Arquitectura en aplicaciones Angular y buenas practicas.
Arquitectura en aplicaciones Angular y buenas practicas.
 
Un mundo sin if. generics al rescate
Un mundo sin if. generics al rescateUn mundo sin if. generics al rescate
Un mundo sin if. generics al rescate
 
Azure 360º para Desarrolaldores
Azure 360º para DesarrolaldoresAzure 360º para Desarrolaldores
Azure 360º para Desarrolaldores
 

Recently uploaded

"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
Fwdays
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
Edge AI and Vision Alliance
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
Pablo Gómez Abajo
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
Neo4j
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 

Recently uploaded (20)

"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 

Api RESTFull

  • 1. Aplicaciones RestFul con Asp.net Core Germán Küber Software Architect http://germankuber.com.ar @germankuber @netbaires
  • 2. 1. ¿Por qué la necesidad de RESTFull? 2. ¿Qué es RESTFull? 3. Los 6 conceptos de RESTFull 4. Como implementar RESTFull en Asp.net Core 5. Conclusión ¿Qué vamos a ver?
  • 3. Las 8 Falacias de la Computación Distribuida 1. La red es confiable 2. La latencia es cero, la latencia no es problema 3. El ancho de banda es infinito 4. La red es segura 5. La topología no cambia 6. Hay uno y sólo un administrador 7. El coste de transporte es cero 8. La red es homogénea http://www.rgoarchitects.com/Files/fallacies.pdf
  • 6. ¿Qué no es REST? • RPC • SOAP and WSDL • HTTP • URIs
  • 7. ¿Qué no es REST? /getAllUsers /getUserById?id=3 /getUserWithProfile?id=4&json=true /updateProfile?name=harry /deleteUserByName?name=jhon
  • 8. ¿Qué SI es REST? /users /users/3 /users/3/profiles /users?email=example@mail.com /users/3/profiles/permissions
  • 9. Las 7 propiedades de RESTFull 1. Rendimiento 2. Escalabilidad 3. Simplicidad 4. Modificabilidad 5. Visibilidad 6. Portabilidad 7. Confiabilidad https://en.wikipedia.org/wiki/Representational_state_transfer#Architectural_properties
  • 10. 6 constraints 1. Client – Server 2. Uniform Interface 3. Statelessness 4. Cacheable 5. Layered System 6. Code on Demand (opcional)
  • 11. Client - Server Cliente y servidor están separados (Cliente y servidor pueden evolucionar por separado)
  • 12. dotnet new webapi -n NetConf-Demo> > dotnet run
  • 13. dotnet add package Swashbuckle.AspNetCore public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); } Startup.cs public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); app.UseMvc(); } >
  • 15. Uniform Interface API y los consumidores comparten una sola interfaz, técnica: URI, Method, Media Type
  • 17. [HttpGet("{id}")] public User Get(int id) [HttpGet("{id}/comments")] public User Get(int id) [HttpGet("{id:int}/comments/{commentId:int}")] public List<Comment> Get(int id,int commentId) [HttpPost] public void Post([FromBody]string value) [HttpPut("{id}")] public void Put(int id, [FromBody]string value) Microsoft.AspNetCore.Mvc
  • 18. [HttpGet("")] public IEnumerable<User> Get([FromQuery]int pageIndex = 1, [FromQuery]int pageSize = 10) /api/users?pageIndex=4&pageSize=5 { "results": [ {author}, {author}, …], "metadata": { "previousPage": "/api/users?pageIndex=03&pageSize=45", "nextPage": "/api/users?pageIndex=05&pageSize=45" } }
  • 19. dotnet add package Microsoft.AspNetCore.Mvc.Versioning public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddApiVersioning(options => { options.ReportApiVersions = true; options.AssumeDefaultVersionWhenUnspecified = true; options.DefaultApiVersion = new ApiVersion(1, 0); }); } Startup.cs >
  • 20. ApiVersion("1.0")] [Route("api/users")] public class UsersController : Controller [ApiVersion("2.0")] [ApiVersion("3.0")] [Route("api/v{ver:apiVersion}/users")] public class UsersV2Controller : Controller { [HttpGet, MapToApiVersion("3.0")] public IActionResult GetV3() => Content("Version 3"); [HttpGet, MapToApiVersion("2.0")] public IActionResult GetV2() => Content("Version 2"); } [ApiVersion("5.0", Deprecated = true)] [Route("api/v{ver:apiVersion}/users")] public class UsersV1Controller : Controller Microsoft.AspNetCore.Mvc.Versioning
  • 21. > dotnet add package Microsoft.AspNetCore.Mvc.Formatters.Xml Startup.cs public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.OutputFormatters.Add(new XmlSerializerOutputFormatter()); }); } public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.OutputFormatters.RemoveType<TextOutputFormatter>(); options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>(); }); }
  • 22. Statelessness Estado contenido dentro de la propia solicitud
  • 23. > dotnet add package RiskFirst.Hateoas services.AddLinks(config => { config.AddPolicy<User>(policy => { policy.RequireSelfLink() .RequireRoutedLink("all", "GetAllModelsRoute") .RequireRoutedLink("delete", "DeleteModelRoute", x => new { id = x.Id }); }); }); public UsersController(ILinksService linksService) Startup.cs UsersController.cs
  • 24. public UsersController(ILinksService linksService) UsersController.cs [HttpGet("{id}", Name = "GetModelRoute")] public async Task<User> GetMyModel(int id) { var model = await userRepository.GetById(id); await _linksService.AddLinksAsync(user); return user; } RiskFirst.Hateoas
  • 25. Startup.cs UsersController.cs { "id": 1234, "name": "Bob", "userName": "SurT", "_links": [ { "rel": "self", "href": "/people/1234” }, { "rel": "update-person", "href": "/people/1234", "method": "PUT" }, { "rel": "delete-person", "href": "/people/1234", "method": "DELETE" } ] } Hateoas
  • 26. Cacheable Cada respuesta/mensaje debe indicar explícitamente si se puede almacenar en caché o no.
  • 27. > dotnet add package Marvin.Cache.Headers --version 1.0.0 public void ConfigureServices(IServiceCollection services) { services.AddHttpCacheHeaders(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseHttpCacheHeaders(); app.UseMvc(); } Startup.cs
  • 28. dotnet add package --version 1.0.0 Response Header { "last-modified": "Sun, 08 Oct 2017 15:00:58 GMT", "etag": "949E486E372B3C6BA94E7D80AA67E512", "cache-control": "public,max-age=60", "expires": "Sun, 08 Oct 2017 15:01:58 GMT" } Marvin.Cache.Headers Request Header
  • 29. Cliente 1 Cliente 2 API G E T api/authors/{id} G E T api/authors/{id} PUT api/authors/{id} Concurrencia PUT api/authors/{id}
  • 30. Cliente 1 Cliente 2 API Concurrencia en RESTFull G E T api/authors/{id} PUT api/authors/{id} If-Match: “123456789” 2 0 0 Ok, ETag: “123456789” G E T api/authors/{id} 200/204, ETag: “987654321” PUT api/authors/{id} If-Match: “123456789” 412 Precondition failed 2 0 0 Ok, ETag: “123456789”
  • 31. Layered System El cliente no puede saber a qué capa está conectado
  • 33. Code on Demand (optional) Servidor puede extender la funcionalidad del cliente
  • 34. RESUMEN • No toda api es una api RESTFull • Debemos diseñar siempre pensando en nuestros clientes • No debemos forzar la implementación de RESTFull • RESTFull prepara nuestras API para el futuro
  • 35. Recursos Microsoft REST API Guidelines https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md Asp.net Core https://docs.microsoft.com/en-us/aspnet/core/ Roy T. Fielding's dissertation http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm

Editor's Notes

  1. Buenas para integracion de aplicaciones
  2. Como armar el Etag no es parte de la norma si no que lo decide el servidor.
  3.  En 1994 L. Peter Deutsch fundador de Aladdin Enterprises y más conocido como el creador de Ghostscript, afirmó que todo programador que empieza en el mundo de las aplicaciones distribuidas comete una serie de presunciones erróneas cuyo resultado se traduce en errores o reducciones substanciales del alcance del sistema. Estas presunciones, que inicialmente fueron 7, se conocen como las Falacias de la Computación Distribuida.
  4. Intenta definir y mostrar como una web bien diseñada se comporta por detrás.
  5. Se diseña pensando en el modelo no en los requisitos de sismtea Esto permite crecer y extender nuestro sistema
  6. Se diseña pensando en el modelo no en los requisitos de sismtea Esto permite crecer y extender nuestro sistema
  7. Es una forma de pensar nuestras aplicaciones Es un modelo de arquitectura Solo se implementa sobre HTTP Un concepto que intenta describir como se comporta la web por detrás, o como deberia comportarse por completo
  8.  En 1994 L. Peter Deutsch fundador de Aladdin Enterprises y más conocido como el creador de Ghostscript, afirmó que todo programador que empieza en el mundo de las aplicaciones distribuidas comete una serie de presunciones erróneas cuyo resultado se traduce en errores o reducciones substanciales del alcance del sistema. Estas presunciones, que inicialmente fueron 7, se conocen como las Falacias de la Computación Distribuida.
  9. Clava diferenciadora Aplicar patrones de diseño general, donde la Interface de nuestra api sea lo mas natural Definir una comunicación estándar, donde todos los clientes puedan comunicarse. No se trabaja con el recurso directamente si no con una reprensetacion de el: json, xml Mensajes deben tener la capacidad de auto describir, los puntos de actualizacion y hasta como eliminar a este recurso (HATEOAS) Beneficios: Todos entienden el mismos lenguaje, y pueden reaccionar antes errores de red, o de otro tipo Reconoce que todo se escribe en lenguajes distintos Asegura que no se necesita que los componentes conozcan el lenguaje del otro componente, si no que entiendan un lenguaje comun independiente a su implementación Visibilidad, el mismos mensaje significa lo mismo en todos los componentes Estabilidad : puedo evolucionar componentes independientes sin que el sistema se vuelva inestable
  10. Define toda la comunicación entre servidores como la de un cliente con un servidor Separacion de responsabilidades entre cliente y servidor Evolucion independiente Los clientes solo conocen a los SERVIDORES y no los servidores a los CLIENTES Portabilidad de clientes Evolucion independiente
  11. Clava diferenciadora Aplicar patrones de diseño general, donde la Interface de nuestra api sea lo mas natural Definir una comunicación estándar, donde todos los clientes puedan comunicarse. No se trabaja con el recurso directamente si no con una reprensetacion de el: json, xml Mensajes deben tener la capacidad de auto describir, los puntos de actualizacion y hasta como eliminar a este recurso (HATEOAS) Beneficios: Todos entienden el mismos lenguaje, y pueden reaccionar antes errores de red, o de otro tipo Reconoce que todo se escribe en lenguajes distintos Asegura que no se necesita que los componentes conozcan el lenguaje del otro componente, si no que entiendan un lenguaje comun independiente a su implementación Visibilidad, el mismos mensaje significa lo mismo en todos los componentes Estabilidad : puedo evolucionar componentes independientes sin que el sistema se vuelva inestable
  12. No construimos una app sin estados Todo estado del cliente se mantiene en el cliente y se envia en la solicitud Evita sincronizacion entre servidores, y evita flujos complejos Si la conexión se cae , no pierdo el estado ya que le estado viaja en el request Pueden vivir app intermedias que sean capaz de aplica capas de seguridad Visibilidad Relaibility > si cae un servidor reinicio el workflow Escalabilidad
  13. Hypermedia as the Engine of Application State
  14. La respuesta debe estar etiquetada como cacheable o no cacheable Benefiicios de cache: Cliente Servidor Intermedio Dado que la latencia nunca es cero, evita esperar respuesta no necesarias al cliente Ancho de banda, evita hacer pedidos no necesarios , reduce el ancho de banda.. Reconoce el tema de que no hay costos en las llamadas Por ejemplo un mobile El servidor puede mantener una cantidad X de cache, hasta evolucionar a un sistema mucho mas caro Beneficios Eficiencia Escalabilidad: se peude escalar dado que no se consume toda la red Performance.
  15. Como armar el Etag no es parte de la norma si no que lo decide el servidor.
  16. Como armar el Etag no es parte de la norma si no que lo decide el servidor.
  17. Como armar el Etag no es parte de la norma si no que lo decide el servidor.
  18. Como armar el Etag no es parte de la norma si no que lo decide el servidor.
  19. El componente solo puede conocer las capas del sistema en el que vive Esto permite agregar caches,. Proxys. Balanceadores de carga Entiende que los servidores estan en constante cambio Entiende que la red no es segura por lo que limita los contextos. Puede administrarse mejor dado que cada persona puede administrar su propio contexto. Escalabilidad Manajabilidad Cliente > proovedor > empresa > base de datos
  20. Mas ignorada por falta de tecnología que pudiera implementarlo de una manera adecuada. Jj, html5 y ajax lo hacen posible. El servidor puede proveedor de código ejecutable al cliente. Evita que el cliente tenga que escribir lógica redundante. Problemas de seguridad, estamos descargando algo que no controlamos Menos gente utilice la api. Se debe aseguridad de que devolvemos valor al cliente que lo precisa pero no rompemos al cliente que no lo quiere. Autenticación federada, me quiero loguear con facebook y el me devuelva html y js para que me redirija.
  21. Rest no es una implementación. Rest es un concepto. No todas las api rest son api rest, y aun menos todas las api RESTFull no son restfull. Debemos tener en cuenta este concepto a la hora de diseñar nuestros sistemas, y debemos tener en cuenta siempre que nuestras aplicaciones son para nuestros clientes Por lo que la implementación y la cantidad de conceptos que implementemos siempre deben ayudar a los clientes. Asp.net Core, es un framework pensado para la nube, por lo que si queresmo aprobecharlo realmente debemos diseñar.