Maven is a build tool that can manage a project's build process, dependencies, documentation and reporting. It uses a Project Object Model (POM) file to store build configuration and metadata. Maven has advantages over Ant like built-in functionality for common tasks, cross-project reuse, and support for conditional logic. It works by defining the project with a POM file then running goals bound to default phases like compile, test, package to build the project.
Service workers allow you to control how network requests from web pages are handled. They run scripts in the background to intercept and handle fetch events, allowing web applications to work offline by responding with cached responses. Before service workers, AppCache was used but had limitations. The lifecycle of a service worker involves registration, installation, activation, and controlling pages. Common uses are caching assets, providing offline functionality, and handling network responses. Challenges include debugging failed installations and limitations on credentials and CORS requests. Service workers also enable push notifications and background sync functionality.
A REST API uses HTTP requests with verbs like GET, POST, PUT, and DELETE to perform CRUD (Create, Read, Update, Delete) operations on resources identified by URLs. It provides a lightweight alternative to SOAP that returns data in JSON format and HTTP response codes. Well-known codes include 200 for OK, 201 for Created, 400 for Bad Request, and 404 for Not Found. REST enables building applications and platforms that can easily integrate new interfaces over time.
Simple REST-API overview for developers. An newer version is here: https://www.slideshare.net/patricksavalle/super-simple-introduction-to-restapis-2nd-version-127968966
This document provides a summary of common Linux shell commands and shell scripting concepts. It begins with recapping common commands like ls, cat, grep etc. It then discusses what a shell script is, how to write basic scripts, and covers shell scripting fundamentals like variables, conditionals, loops, command line arguments and more. The document also provides examples of using sed, awk and regular expressions for text processing and manipulation.
The document provides an overview of important commands for the SQLMap tool. It describes commands for scanning GET and POST requests, crawling websites, bypassing web application firewalls, enumerating databases and tables, running system commands, and more. The document serves as a quick reference guide for common tasks performed using SQLMap for SQL injection testing and exploitation.
Swagger is a specification and complete framework implementation for describing, producing, consuming, and visualizing RESTful web services. The overarching goal of Swagger is to enable client and documentation systems to update at the same pace as the server. The documentation of methods, parameters, and models are tightly integrated into the server code, allowing APIs to always stay in sync. With Swagger, deploying managing, and using powerful APIs has never been easier.
Maven is a build tool that can manage a project's build process, dependencies, documentation and reporting. It uses a Project Object Model (POM) file to store build configuration and metadata. Maven has advantages over Ant like built-in functionality for common tasks, cross-project reuse, and support for conditional logic. It works by defining the project with a POM file then running goals bound to default phases like compile, test, package to build the project.
Service workers allow you to control how network requests from web pages are handled. They run scripts in the background to intercept and handle fetch events, allowing web applications to work offline by responding with cached responses. Before service workers, AppCache was used but had limitations. The lifecycle of a service worker involves registration, installation, activation, and controlling pages. Common uses are caching assets, providing offline functionality, and handling network responses. Challenges include debugging failed installations and limitations on credentials and CORS requests. Service workers also enable push notifications and background sync functionality.
A REST API uses HTTP requests with verbs like GET, POST, PUT, and DELETE to perform CRUD (Create, Read, Update, Delete) operations on resources identified by URLs. It provides a lightweight alternative to SOAP that returns data in JSON format and HTTP response codes. Well-known codes include 200 for OK, 201 for Created, 400 for Bad Request, and 404 for Not Found. REST enables building applications and platforms that can easily integrate new interfaces over time.
Simple REST-API overview for developers. An newer version is here: https://www.slideshare.net/patricksavalle/super-simple-introduction-to-restapis-2nd-version-127968966
This document provides a summary of common Linux shell commands and shell scripting concepts. It begins with recapping common commands like ls, cat, grep etc. It then discusses what a shell script is, how to write basic scripts, and covers shell scripting fundamentals like variables, conditionals, loops, command line arguments and more. The document also provides examples of using sed, awk and regular expressions for text processing and manipulation.
The document provides an overview of important commands for the SQLMap tool. It describes commands for scanning GET and POST requests, crawling websites, bypassing web application firewalls, enumerating databases and tables, running system commands, and more. The document serves as a quick reference guide for common tasks performed using SQLMap for SQL injection testing and exploitation.
Swagger is a specification and complete framework implementation for describing, producing, consuming, and visualizing RESTful web services. The overarching goal of Swagger is to enable client and documentation systems to update at the same pace as the server. The documentation of methods, parameters, and models are tightly integrated into the server code, allowing APIs to always stay in sync. With Swagger, deploying managing, and using powerful APIs has never been easier.
This presentation about Docker will help you learn what Docker and Docker compose is, benefits of Docker compose, differences between Docker compose and Docker swarm, basic commands of docker compose and finally, a demo on docker compose. Docker is a tool which runs containers, whereas Docker Compose is used for running multiple containers as a single service. With compose, containers run in isolation (but they interact with each other). After watching this video, you will able to create a YAML file of docker compose and run multiple containers at a time. Now, let us get started and understand how does a Docker compose work.
Below are the topics covered in this Docker compose presentation:
1. What is Docker?
2. What is a Docker Compose?
3. Benefits of Docker compose
4. Docker Compose vs Docker Swarm
5. Basic commands of Docker
6. Demo
Why learn DevOps?
Simplilearn’s DevOps training course is designed to help you become a DevOps practitioner and apply the latest in DevOps methodology to automate your software development lifecycle right out of the class. You will master configuration management; continuous integration deployment, delivery and monitoring using DevOps tools such as Git, Docker, Jenkins, Puppet and Nagios in a practical, hands on and interactive approach. The Devops training course focuses heavily on the use of Docker containers, a technology that is revolutionizing the way apps are deployed in the cloud today and is a critical skillset to master in the cloud age.
After completing the DevOps training course you will achieve hands on expertise in various aspects of the DevOps delivery model. The practical learning outcomes of this Devops training course are:
An understanding of DevOps and the modern DevOps toolsets
The ability to automate all aspects of a modern code delivery and deployment pipeline using:
1. Source code management tools
2. Build tools
3. Test automation tools
4. Containerization through Docker
5. Configuration management tools
6. Monitoring tools
Who should take this course?
DevOps career opportunities are thriving worldwide. DevOps was featured as one of the 11 best jobs in America for 2017, according to CBS News, and data from Payscale.com shows that DevOps Managers earn as much as $122,234 per year, with DevOps engineers making as much as $151,461. DevOps jobs are the third-highest tech role ranked by employer demand on Indeed.com but have the second-highest talent deficit.
1. This DevOps training course will be of benefit the following professional roles:
2. Software Developers
3. Technical Project Managers
4. Architects
5. Operations Support
6. Deployment engineers
7. IT managers
8. Development managers
Learn more at https://www.simplilearn.com/cloud-computing/devops-practitioner-certification-training
This document provides an overview of ASP.NET Web API, a framework for building HTTP-based services. It discusses key Web API concepts like REST, routing, actions, validation, OData, content negotiation, and the HttpClient. Web API allows building rich HTTP-based apps that can reach more clients by embracing HTTP standards and using HTTP as an application protocol. It focuses on HTTP rather than transport flexibility like WCF.
This document provides an introduction to REST APIs. It defines an API as a set of tools and protocols for building software. A REST API is an architectural style for web services that uses HTTP requests to GET, POST, PUT, and DELETE data. REST APIs have features like being simpler than SOAP, having documentation, and providing error messages. The core principles of REST are that it is stateless, uses a uniform interface, is layered, cacheable, and has code-on-demand. Common HTTP methods map to CRUD operations on resources. REST APIs offer advantages like scalability, flexibility, and independence.
Talk given at DevTeach Montreal on RxJS - The Basics & The Future.
Example repo: https://github.com/ladyleet/rxjs-test
Have questions? Find me on twitter http://twitter.com/ladyleet
Laravel is a popular PHP web framework created by Taylor Otwell in 2011. It follows the MVC pattern and simplifies development with modular structure, elegant syntax, and built-in features like routing, middleware, Blade templating, Eloquent ORM, and Artisan CLI. Laravel has a large community and is easy to learn and use due to its simplicity, modularity, and extensive built-in functionality that helps developers build cleaner code more efficiently.
This document provides an overview of web services. It defines a web service as a web page meant to be consumed programmatically rather than via a web browser. Examples given include e-commerce sites using shipping APIs and weather data being provided to news sites. Benefits outlined are simplicity, loose coupling, statelessness, and firewall friendliness. The document also discusses when to use and avoid web services and describes the main types - SOAP and REST. It provides details on RESTful services using JAX-RS annotations and extracting parameters. For SOAP, it explains the communication protocol and use of WSDL and UDDI.
Service discovery with Eureka and Spring CloudMarcelo Serpa
The document discusses service discovery with Eureka and Spring Cloud. It introduces traditional applications where services have fixed locations versus modern applications where services are dynamic. It explains that service discovery with a service registry like Eureka allows services to find each other and load balance requests. The rest of the document demonstrates configuring Eureka as a service registry and client applications that can discover and consume services registered with Eureka.
This document provides an overview of APIs and how they work. It begins with basic API concepts and definitions, then demonstrates how APIs are used by having programs interact with applications to access structured data without direct human interaction. It provides examples of common API uses for maps, login/authentication, payments, messaging and more. It also introduces the concept of webhooks which allow applications to "call" other services when data is available, rather than requiring the other service to periodically check via API calls. Overall it serves as a high-level introduction to APIs and webhooks for beginners.
Amongst all the big front end frameworks, Nuxt.js stands out as it has a lot of advantages over the other. This presentation covers an overview of Nuxt.js and how Server Side Rendering helps in improving the SEO of a site.
Swarm in a nutshell
• Exposes several Docker Engines as a single virtual Engine
• Serves the standard Docker API
• Extremely easy to get started
• Batteries included but swappable
Linux Crontab allows scheduling routine jobs to run automatically in the background at specific times or days. The document provides 15 examples of cron job configurations, including running jobs daily, weekly, monthly, at startup or reboot, and during specific time ranges. It also covers viewing, editing, and installing cron jobs, as well as redirecting output and specifying environment variables. Anacron is introduced as an alternative for machines that may not be running 24/7, to better ensure scheduled jobs run as expected.
Implement Authorization in your Apps with Microsoft identity platform-June 2020Microsoft 365 Developer
Kalyan Krishna from Microsoft hosted a community call on implementing authorization in applications using features of the Microsoft Identity Platform like app roles, security groups, scopes, and directory roles. The call covered:
- Defining and assigning app roles to users and other apps to control permissions.
- Using security groups assigned to users to manage access and optionally returning group details in tokens.
- Configuring application groups to filter tokens to only include groups relevant to an application.
- Providing scopes or delegated permissions for public client applications to request access to resources.
- Directories roles for administering access in Azure AD tenants.
- REST (Representational State Transfer) uses HTTP requests to transfer representations of resources between clients and servers. The format of the representation is determined by the content-type header and the interaction with the resource is determined by the HTTP verb used.
- The four main HTTP verbs are GET, PUT, DELETE, and POST. GET retrieves a representation of the resource and is safe, while PUT, DELETE, and POST can modify the resource's state in atomic operations.
- Resources are abstract concepts acted upon by HTTP requests, while representations are the actual data transmitted in responses. The representation may or may not accurately reflect the resource's current state.
This document provides an introduction and overview of Open Policy Agent (OPA). It discusses how OPA can be used to add fine-grained policy controls to other projects. Key points include:
- OPA allows integrating policy decisions from a project into OPA and offloading policy logic. Policies can be authored in OPA and decisions retrieved.
- Policies are invoked by sending decision requests to OPA APIs. The input is JSON and the response is also JSON.
- Simple policies involve looking up values, comparing values, assigning variables, and creating rules with heads and bodies. Rules with the same head are OR'd together.
- Policies can handle arrays and iteration by using an
Not so long ago Microsoft announced a new language trageting on front-end developers. Everybody's reaction was like: Why?!! Is it just Microsoft darting back to Google?!
So, why a new language? JavaScript has its bad parts. Mostly you can avoid them or workaraund. You can emulate class-based OOP style, modules, scoping and even run-time typing. But that is doomed to be clumsy. That's not in the language design. Google has pointed out these flaws, provided a new language and failed. Will the story of TypeScript be any different?
React Router is the most widely used router for React, in use by almost half of all React projects. This talk is about using React Router in your project. It will start with the basics and will go through all features React Router has to offer in the current version and the upcoming 1.0 release. I will also go through some common problems including data fetching and authentication.
Server-Side Request Forgery (SSRF) refers to an attack where an attacker is able to send a crafted request from a vulnerable web application to target internal systems normally inaccessible from outside. SSRF typically occurs when an attacker has partial or full control over a request being sent by the web application, such as controlling the URL a request is made to. To prevent SSRF, applications should whitelist allowed domains and protocols for requests, and avoid directly using untrusted user input in functions making external requests on the server's behalf.
ASP.NET is a web development platform that allows building dynamic web pages using programming languages like C# and VB.NET. It provides components, services and infrastructure for robust web applications. ASP.NET applications are compiled code that uses classes in the .NET framework. The document describes ASP.NET features, advantages, differences from ASP, the page and application lifecycles, and events in the page lifecycle.
Laravel, längst kein unbestriebenes Blatt mehr, gewinnt immer mehr an Popularität.
In diesem Vortrag wir Laravel kurz vorgestellt mit Themen wie:
- Was ist Laravel?
- Woher kommt Laravel?
- Was bietet Laravel?
- Laravel und sein Ecosystem.
und einiges mehr...
JavaScript is a scripting language used for client-side and server-side web development. It is a dynamically typed language that is easy to code in and supports features like DOM manipulation, events, functions, and objects. JavaScript can be added to HTML documents in internal <script> tags or externally linked .js files and is used for everything from simple form validation to complex single-page applications.
This document provides an overview and introduction to using the Sinatra web framework for building RESTful web applications in Ruby. It discusses Sinatra's philosophy of being simple and easy to use, introduces REST principles and how Sinatra supports them through HTTP verbs, routing, caching, authentication and more. Code examples are provided to demonstrate how a basic "Hello World" application is structured in Sinatra and how requests are routed and executed under the hood.
Based on original presentation by Dan Webb http://slidesha.re/dan_on_rack
Added some bits about Rails at the end, instead of other examples he had originally.
This presentation about Docker will help you learn what Docker and Docker compose is, benefits of Docker compose, differences between Docker compose and Docker swarm, basic commands of docker compose and finally, a demo on docker compose. Docker is a tool which runs containers, whereas Docker Compose is used for running multiple containers as a single service. With compose, containers run in isolation (but they interact with each other). After watching this video, you will able to create a YAML file of docker compose and run multiple containers at a time. Now, let us get started and understand how does a Docker compose work.
Below are the topics covered in this Docker compose presentation:
1. What is Docker?
2. What is a Docker Compose?
3. Benefits of Docker compose
4. Docker Compose vs Docker Swarm
5. Basic commands of Docker
6. Demo
Why learn DevOps?
Simplilearn’s DevOps training course is designed to help you become a DevOps practitioner and apply the latest in DevOps methodology to automate your software development lifecycle right out of the class. You will master configuration management; continuous integration deployment, delivery and monitoring using DevOps tools such as Git, Docker, Jenkins, Puppet and Nagios in a practical, hands on and interactive approach. The Devops training course focuses heavily on the use of Docker containers, a technology that is revolutionizing the way apps are deployed in the cloud today and is a critical skillset to master in the cloud age.
After completing the DevOps training course you will achieve hands on expertise in various aspects of the DevOps delivery model. The practical learning outcomes of this Devops training course are:
An understanding of DevOps and the modern DevOps toolsets
The ability to automate all aspects of a modern code delivery and deployment pipeline using:
1. Source code management tools
2. Build tools
3. Test automation tools
4. Containerization through Docker
5. Configuration management tools
6. Monitoring tools
Who should take this course?
DevOps career opportunities are thriving worldwide. DevOps was featured as one of the 11 best jobs in America for 2017, according to CBS News, and data from Payscale.com shows that DevOps Managers earn as much as $122,234 per year, with DevOps engineers making as much as $151,461. DevOps jobs are the third-highest tech role ranked by employer demand on Indeed.com but have the second-highest talent deficit.
1. This DevOps training course will be of benefit the following professional roles:
2. Software Developers
3. Technical Project Managers
4. Architects
5. Operations Support
6. Deployment engineers
7. IT managers
8. Development managers
Learn more at https://www.simplilearn.com/cloud-computing/devops-practitioner-certification-training
This document provides an overview of ASP.NET Web API, a framework for building HTTP-based services. It discusses key Web API concepts like REST, routing, actions, validation, OData, content negotiation, and the HttpClient. Web API allows building rich HTTP-based apps that can reach more clients by embracing HTTP standards and using HTTP as an application protocol. It focuses on HTTP rather than transport flexibility like WCF.
This document provides an introduction to REST APIs. It defines an API as a set of tools and protocols for building software. A REST API is an architectural style for web services that uses HTTP requests to GET, POST, PUT, and DELETE data. REST APIs have features like being simpler than SOAP, having documentation, and providing error messages. The core principles of REST are that it is stateless, uses a uniform interface, is layered, cacheable, and has code-on-demand. Common HTTP methods map to CRUD operations on resources. REST APIs offer advantages like scalability, flexibility, and independence.
Talk given at DevTeach Montreal on RxJS - The Basics & The Future.
Example repo: https://github.com/ladyleet/rxjs-test
Have questions? Find me on twitter http://twitter.com/ladyleet
Laravel is a popular PHP web framework created by Taylor Otwell in 2011. It follows the MVC pattern and simplifies development with modular structure, elegant syntax, and built-in features like routing, middleware, Blade templating, Eloquent ORM, and Artisan CLI. Laravel has a large community and is easy to learn and use due to its simplicity, modularity, and extensive built-in functionality that helps developers build cleaner code more efficiently.
This document provides an overview of web services. It defines a web service as a web page meant to be consumed programmatically rather than via a web browser. Examples given include e-commerce sites using shipping APIs and weather data being provided to news sites. Benefits outlined are simplicity, loose coupling, statelessness, and firewall friendliness. The document also discusses when to use and avoid web services and describes the main types - SOAP and REST. It provides details on RESTful services using JAX-RS annotations and extracting parameters. For SOAP, it explains the communication protocol and use of WSDL and UDDI.
Service discovery with Eureka and Spring CloudMarcelo Serpa
The document discusses service discovery with Eureka and Spring Cloud. It introduces traditional applications where services have fixed locations versus modern applications where services are dynamic. It explains that service discovery with a service registry like Eureka allows services to find each other and load balance requests. The rest of the document demonstrates configuring Eureka as a service registry and client applications that can discover and consume services registered with Eureka.
This document provides an overview of APIs and how they work. It begins with basic API concepts and definitions, then demonstrates how APIs are used by having programs interact with applications to access structured data without direct human interaction. It provides examples of common API uses for maps, login/authentication, payments, messaging and more. It also introduces the concept of webhooks which allow applications to "call" other services when data is available, rather than requiring the other service to periodically check via API calls. Overall it serves as a high-level introduction to APIs and webhooks for beginners.
Amongst all the big front end frameworks, Nuxt.js stands out as it has a lot of advantages over the other. This presentation covers an overview of Nuxt.js and how Server Side Rendering helps in improving the SEO of a site.
Swarm in a nutshell
• Exposes several Docker Engines as a single virtual Engine
• Serves the standard Docker API
• Extremely easy to get started
• Batteries included but swappable
Linux Crontab allows scheduling routine jobs to run automatically in the background at specific times or days. The document provides 15 examples of cron job configurations, including running jobs daily, weekly, monthly, at startup or reboot, and during specific time ranges. It also covers viewing, editing, and installing cron jobs, as well as redirecting output and specifying environment variables. Anacron is introduced as an alternative for machines that may not be running 24/7, to better ensure scheduled jobs run as expected.
Implement Authorization in your Apps with Microsoft identity platform-June 2020Microsoft 365 Developer
Kalyan Krishna from Microsoft hosted a community call on implementing authorization in applications using features of the Microsoft Identity Platform like app roles, security groups, scopes, and directory roles. The call covered:
- Defining and assigning app roles to users and other apps to control permissions.
- Using security groups assigned to users to manage access and optionally returning group details in tokens.
- Configuring application groups to filter tokens to only include groups relevant to an application.
- Providing scopes or delegated permissions for public client applications to request access to resources.
- Directories roles for administering access in Azure AD tenants.
- REST (Representational State Transfer) uses HTTP requests to transfer representations of resources between clients and servers. The format of the representation is determined by the content-type header and the interaction with the resource is determined by the HTTP verb used.
- The four main HTTP verbs are GET, PUT, DELETE, and POST. GET retrieves a representation of the resource and is safe, while PUT, DELETE, and POST can modify the resource's state in atomic operations.
- Resources are abstract concepts acted upon by HTTP requests, while representations are the actual data transmitted in responses. The representation may or may not accurately reflect the resource's current state.
This document provides an introduction and overview of Open Policy Agent (OPA). It discusses how OPA can be used to add fine-grained policy controls to other projects. Key points include:
- OPA allows integrating policy decisions from a project into OPA and offloading policy logic. Policies can be authored in OPA and decisions retrieved.
- Policies are invoked by sending decision requests to OPA APIs. The input is JSON and the response is also JSON.
- Simple policies involve looking up values, comparing values, assigning variables, and creating rules with heads and bodies. Rules with the same head are OR'd together.
- Policies can handle arrays and iteration by using an
Not so long ago Microsoft announced a new language trageting on front-end developers. Everybody's reaction was like: Why?!! Is it just Microsoft darting back to Google?!
So, why a new language? JavaScript has its bad parts. Mostly you can avoid them or workaraund. You can emulate class-based OOP style, modules, scoping and even run-time typing. But that is doomed to be clumsy. That's not in the language design. Google has pointed out these flaws, provided a new language and failed. Will the story of TypeScript be any different?
React Router is the most widely used router for React, in use by almost half of all React projects. This talk is about using React Router in your project. It will start with the basics and will go through all features React Router has to offer in the current version and the upcoming 1.0 release. I will also go through some common problems including data fetching and authentication.
Server-Side Request Forgery (SSRF) refers to an attack where an attacker is able to send a crafted request from a vulnerable web application to target internal systems normally inaccessible from outside. SSRF typically occurs when an attacker has partial or full control over a request being sent by the web application, such as controlling the URL a request is made to. To prevent SSRF, applications should whitelist allowed domains and protocols for requests, and avoid directly using untrusted user input in functions making external requests on the server's behalf.
ASP.NET is a web development platform that allows building dynamic web pages using programming languages like C# and VB.NET. It provides components, services and infrastructure for robust web applications. ASP.NET applications are compiled code that uses classes in the .NET framework. The document describes ASP.NET features, advantages, differences from ASP, the page and application lifecycles, and events in the page lifecycle.
Laravel, längst kein unbestriebenes Blatt mehr, gewinnt immer mehr an Popularität.
In diesem Vortrag wir Laravel kurz vorgestellt mit Themen wie:
- Was ist Laravel?
- Woher kommt Laravel?
- Was bietet Laravel?
- Laravel und sein Ecosystem.
und einiges mehr...
JavaScript is a scripting language used for client-side and server-side web development. It is a dynamically typed language that is easy to code in and supports features like DOM manipulation, events, functions, and objects. JavaScript can be added to HTML documents in internal <script> tags or externally linked .js files and is used for everything from simple form validation to complex single-page applications.
This document provides an overview and introduction to using the Sinatra web framework for building RESTful web applications in Ruby. It discusses Sinatra's philosophy of being simple and easy to use, introduces REST principles and how Sinatra supports them through HTTP verbs, routing, caching, authentication and more. Code examples are provided to demonstrate how a basic "Hello World" application is structured in Sinatra and how requests are routed and executed under the hood.
Based on original presentation by Dan Webb http://slidesha.re/dan_on_rack
Added some bits about Rails at the end, instead of other examples he had originally.
This document discusses using Sinatra to build a JSON query service with the following key points:
- It describes building a Sinatra app frontend to query portions of JSON documents stored in a Redis backend cache.
- The backend uses Redis as a fast key-value store to cache full JSON documents and return requested portions based on a JSON query syntax.
- Testing the Sinatra app is discussed as well as potential issues like query syntax, caching at scale, and performance under load.
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜崇之 清水
The document describes how to build serverless applications using the Chalice framework. It shows examples of defining routes, path parameters, HTTP methods, and response handling. It also demonstrates configuring features like CORS, API keys, and authorizers. The document explains how Chalice works behind the scenes by examining its core classes and how it matches incoming requests to route functions. It provides links to additional resources about serverless applications on AWS.
Sinatra is a lightweight web application framework for Ruby. It is a DSL for quickly building web apps that leverages the Ruby language. Some key points about Sinatra include that it is lightweight, pluggable as middleware in other apps like Rails, and uses convention over configuration. Hello world apps are simple Sinatra blocks that return strings. Views and templates use formats like HAML and are organized in standard directories. Sinatra apps can be deployed to Heroku with git pushes or run locally using the Thin web server.
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryTatsuhiko Miyagawa
Building a desktop app using HTTP::Engine as a micro web server, SQLite for data storage, and jQuery for the user interface. Comet and asynchronous workers are used to enable real-time features. JSON-RPC and routing are implemented to support AJAX actions. The combination provides a lightweight "desktop app" architecture that is cross-platform.
Rhebok, High Performance Rack Handler / Rubykaigi 2015Masahiro Nagano
This document discusses Rhebok, a high performance Rack handler written in Ruby. Rhebok uses a prefork architecture for concurrency and achieves 1.5-2x better performance than Unicorn. It implements efficient network I/O using techniques like IO timeouts, TCP_NODELAY, and writev(). Rhebok also uses the ultra-fast PicoHTTPParser for HTTP request parsing. The document provides an overview of Rhebok, benchmarks showing its performance, and details on its internals and architecture.
fog or: How I Learned to Stop Worrying and Love the CloudWesley Beary
Learn how to easily get started on cloud computing with fog. If you can control your infrastructure choices, you’ll make better choices in development and get what you need in production. You'll get an overview of fog and concrete examples to give you a head start on your provisioning workflow.
The document discusses socket applications and real-time communication. It describes common examples like chat, live feeds, and games. It then explains the typical solution of using AJAX requests and the problems with that approach. The proposed solution is to use a multi-threaded model with asynchronous I/O and the reactor pattern to process requests while waiting for network responses. Various tools for implementing this pattern in Ruby and JavaScript are also mentioned, including Pusher, Socket.IO, and SocketStream.
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)Wesley Beary
The document discusses how to use the Fog library to interact with cloud services. Fog allows interacting with multiple cloud providers like AWS, Rackspace, etc in a portable way. It provides models, collections, and methods to manage resources like servers, storage, DNS etc. in an abstracted way across providers. The document demonstrates how to boot a server, install SSH keys, run commands via SSH, and ping a target using the Fog and Ruby APIs in just a few lines of code.
The document discusses Rack, a Ruby web server interface. Rack provides a standard interface between web servers and Ruby frameworks/applications. If a Ruby object has a "call" method that takes an environment hash and returns a status, headers, and response body array, it can be run by any Rack-compatible web server. This allows Ruby web applications to be run using many different servers without code changes. The document provides examples of Rack applications and integrating them with servers like Thin and Mongrel.
Rack is a Ruby web server interface that provides a minimal interface between web servers and Ruby frameworks like Rails. It allows web applications to be written as Ruby objects that respond to the call method. Rack applications take a request environment hash and return a status, headers, and response body array. Rack allows modularity through middlewares that act as filters on requests. Rails itself is built with Rack and exposes its middleware stack.
Crossing the Bridge: Connecting Rails and your Front-end FrameworkDaniel Spector
1. The document discusses integrating front-end frameworks like Angular, Ember, and React with Rails by constructing JSON APIs, preloading data to avoid loading screens, and server-side rendering for SEO and performance.
2. It provides code examples for building a TODO application with each framework, including using ngResource and factories in Angular, Ember conventions like Ember Data, and building isolated React components.
3. Server-side rendering is highlighted as the future for isomorphic JavaScript, providing benefits like prerendering on initial page load.
This document discusses ways to create lightweight Ruby solutions by simplifying frameworks and components. It suggests replacing ActiveRecord with the simpler and faster Sequel ORM. It also recommends using Zepto.js instead of jQuery for mobile apps, and Rack and Sinatra to build lightweight web apps instead of full Rails applications. Benchmarks show these lightweight approaches can significantly improve performance compared to default Rails. Tools mentioned that aid lightweight development include Pow for local web serving and rbenv for Ruby version management. The document concludes by reminding developers not to see Ruby as the only solution and to consider other languages like Erlang, Scala and C++ for certain problems.
The document discusses Rack, a modular web server interface for Ruby that allows web applications and frameworks to be written as middleware stacks. It covers topics like Rack applications as middleware, common Rack middleware components, building applications with Rack and middleware, and integrating Rack middleware with frameworks like Rails.
This document discusses how Rails may not be the best tool for rapid prototyping and suggests alternatives that are more lightweight and collaborative. It introduces Serve, an alternative to Rails that uses a simple folder structure and views to quickly prototype ideas without models, controllers or routing. Serve works with popular front-end tools and libraries and can deploy to Heroku. The document argues that prototyping tools should empower all team members, including front-end developers, and that Rack middleware like Rack::Cascade allows reusing mockups and wireframes in a Rails app.
Sally and Leo use infrastructure as code practices like Cucumber, ServerSpec, Vagrant, and Ansible to automate the provisioning and configuration of a web server. They write behavior tests in Cucumber and infrastructure tests in ServerSpec. Vagrant is used to provision a virtual machine, and Ansible configures the server. By tying the tests to the provisioning code, they can now repeatedly build servers that are known to meet requirements.
Rack provides a simple interface for building web applications in Ruby. This document outlines how to build a basic web framework on top of Rack by leveraging existing Rack middleware and tools. It demonstrates how to add features like routing, controllers, views, ORM, authentication, testing, and a console using middleware like Usher, Tilt, DataMapper, Warden, rack-test, and racksh. The goal is to create a simple but full-featured framework with minimal code by combining existing Rack components.
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine YardSV Ruby on Rails Meetup
Wesley Beary: Cloud computing scared the crap out of me - the quirks and nightmares
of provisioning computing and storage on AWS, Terremark, Rackspace,
etc - until I took the bull by the horns. Let me now show you how I
tamed that bull.
Learn how to easily get started cloud computing with fog. It gives you
the reins within any Ruby application or script. If you can control
your infrastructure choices, you can make better choices in
development and get what you need in production.
You'll get an overview of fog and concrete examples to give you a head
start on your own provisioning workflow.
The document provides an overview of Node.js and the Express web framework. It discusses that Node.js is a platform for executing JavaScript files and includes utilities for network and file I/O. Express is a web application framework built on Node.js that uses middleware to handle requests. The document covers Express concepts like routing, middleware, templating, and popular middleware modules for tasks like compression, parsing request bodies, and sessions.
Similar to Using Sinatra to Build REST APIs in Ruby (20)
Refining Your API Design - Architecture and Modeling Learning EventLaunchAny
APIs are a conversation that involves everyone, from developers to end-users and even machine-to-machine. Yet, we can miss the mark when designing an API that delivers on the desired outcomes of the end user. In this talk, James discusses the factors that ensure an API delivers value to the end user. He will explore some techniques on refining your API design before it goes live. He will also explore the challenges of microservices and why they may not be what you think they are. Along the way, we will discuss techniques that can accelerate the API design and delivery process.
Event-based APIs are becoming more popular, enabling developers to craft new integrations and solutions that go beyond the original design of an API. Yet, there remains a challenge: how can teams design thoughtful event-based APIs that are long-lasting, evolvable, and discoverable? This talk will dive into the design practices of event-based APIs, including tips for determining which protocol(s) you should select, design patterns we should apply, and anti-patterns should we avoid. We will also look at how AI and tools such as ChatGPT are starting to shape the next generation of APIs.
Delivered on May 10, 2023 for the EDA Summit
Event-based API Patterns and Practices - AsyncAPI Online ConferenceLaunchAny
This document discusses API design patterns for event-based APIs. It begins with an introduction to the author and overview of popular API styles. It then covers several options for asynchronous API design like webhooks, server-sent events, websockets, and streaming protocols. The remainder discusses specific patterns for event payload design including thin notifications, hypermedia links, schema evolution, and separating internal and external events. It emphasizes putting careful design into event formats as they form a contract like an API.
GlueCon 2019: Beyond REST - Moving to Event-Based APIs and StreamingLaunchAny
For more than a decade, web APIs have replaced the previous generation of web services. Throughout this period of growth, most APIs have been restricted to request-response over HTTP. We are now seeing a move back to eventing with the popularity of webhooks. Additionally, streaming is becoming another option for connecting services, apps, and devices. In this talk, we will look at the opportunities that event-based APIs and streaming offer and how our software architecture is evolving to handle these new styles of API interaction.
Austin API Summit 2019 - APIs, Microservices, and Serverless: The Shape of Th...LaunchAny
A look at the growth of APIs, the influence of microservices and serverless, and the new enterprise API platform stack including API profiles, multiple API styles, and data management
APIStrat Keynote: Lessons in Transforming the Enterprise to an API PlatformLaunchAny
This document outlines lessons from transforming an enterprise to an API platform. It discusses 5 key lessons: 1) developing an API strategy, 2) implementing federated API governance, 3) modernizing architecture and delivery, 4) increasing API adoption, and 5) defining platform processes. The goal is to offer a platform that supports internal developers, public app developers, customers, and third-party approved apps through APIs, streams, and events.
Austin API Summit 2018: Are REST APIs Still Relevant Today?LaunchAny
A look at common API styles available today, a look back at historical API styles, and guidance for selecting the right API styles for your organization. Deep-dive of HTTP, mentioned in the presentation, can be found at: http://bit.ly/power-http
GlueCon 2018: Are REST APIs Still Relevant Today?LaunchAny
A look at common API styles available today, a look back at historical API styles, and guidance for selecting the right API styles for your organization. Deep-dive of HTTP, mentioned in the presentation, can be found at: http://bit.ly/power-http
Lessons in Transforming the Enterprise to an API PlatformLaunchAny
A look at lessons from our recent consulting engagements on why and how enterprises are moving from an API program to an API platform as part of their digital transformation. Includes 5 common practices we see across successful enterprises as they move to an API platform. Recording: https://www.youtube.com/watch?v=Km-mCx0Zbgo&feature=youtu.be
APIStrat 2017: API Design in the Age of Bots, IoT, and VoiceLaunchAny
Our API design should be user-first: a reflection of the kinds of capabilities and outcomes our users expect. New devices and software interaction will change the way we design web APIs. Presented at APIStrat 2017
API:World 2016 - Applying Domain Driven Design to APIs and MicroservicesLaunchAny
Presentation from API:World 2016 that answers the following questions:
How are APIs and microservices related?
How do I figure out how to find the right size for my microservices?
And how do I get there if I have a monolithic architecture?
Moving Toward a Modular Enterprise - All About the API Conference 2016LaunchAny
A look at how APIs and microservices are driving the enterprise toward a more modular, connected approach to software development. Also outlines the key transformation steps used by CIOs and CTOs to address digital transformation and achieve a more modular enterprise.
Designing APIs and Microservices Using Domain-Driven DesignLaunchAny
Presented at GlueCon 2016. Applying good software engineering practices, system design, and domain-driven design for your public APIs and microservices
Applying Domain-Driven Design to APIs and Microservices - Austin API MeetupLaunchAny
This document discusses applying domain-driven design principles to API and microservices architecture. It recommends using an outside-in design approach where the data model is separate from the object model and resource model. Domain-driven design helps identify context boundaries, and microservices require renewed focus on system and API design. Modeling the domain entities, relations, states and events defines the resources exposed by each API. This modular design increases composability and the ability to replace services over time.
APIs Are Forever - How to Design Long-Lasting APIsLaunchAny
Teams often struggle with balancing the complexity of legacy applications, limited time, and limited resources when designing APIs. The result is often the release of less-than-ideal API design that meets the immediate needs of the client but misses opportunities for longer-term value. This talk explores systems design and domain-driven design (DDD) for API design thinking and how to apply this technique to your design process to create a clear, well-designed, long-lasting API. Presented at API Strategy and Practice 2015
API Thinking - How to Design APIs Through Systems DesignLaunchAny
A 5 min discussion about how to improve API design by focusing on domain modeling (to identify entities, relationships, transitions, and events) and systems design (to find the context boundaries for our APIs).
OpenMetadata Community Meeting - 5th June 2024OpenMetadata
The OpenMetadata Community Meeting was held on June 5th, 2024. In this meeting, we discussed about the data quality capabilities that are integrated with the Incident Manager, providing a complete solution to handle your data observability needs. Watch the end-to-end demo of the data quality features.
* How to run your own data quality framework
* What is the performance impact of running data quality frameworks
* How to run the test cases in your own ETL pipelines
* How the Incident Manager is integrated
* Get notified with alerts when test cases fail
Watch the meeting recording here - https://www.youtube.com/watch?v=UbNOje0kf6E
Flutter is a popular open source, cross-platform framework developed by Google. In this webinar we'll explore Flutter and its architecture, delve into the Flutter Embedder and Flutter’s Dart language, discover how to leverage Flutter for embedded device development, learn about Automotive Grade Linux (AGL) and its consortium and understand the rationale behind AGL's choice of Flutter for next-gen IVI systems. Don’t miss this opportunity to discover whether Flutter is right for your project.
WhatsApp offers simple, reliable, and private messaging and calling services for free worldwide. With end-to-end encryption, your personal messages and calls are secure, ensuring only you and the recipient can access them. Enjoy voice and video calls to stay connected with loved ones or colleagues. Express yourself using stickers, GIFs, or by sharing moments on Status. WhatsApp Business enables global customer outreach, facilitating sales growth and relationship building through showcasing products and services. Stay connected effortlessly with group chats for planning outings with friends or staying updated on family conversations.
Utilocate offers a comprehensive solution for locate ticket management by automating and streamlining the entire process. By integrating with Geospatial Information Systems (GIS), it provides accurate mapping and visualization of utility locations, enhancing decision-making and reducing the risk of errors. The system's advanced data analytics tools help identify trends, predict potential issues, and optimize resource allocation, making the locate ticket management process smarter and more efficient. Additionally, automated ticket management ensures consistency and reduces human error, while real-time notifications keep all relevant personnel informed and ready to respond promptly.
The system's ability to streamline workflows and automate ticket routing significantly reduces the time taken to process each ticket, making the process faster and more efficient. Mobile access allows field technicians to update ticket information on the go, ensuring that the latest information is always available and accelerating the locate process. Overall, Utilocate not only enhances the efficiency and accuracy of locate ticket management but also improves safety by minimizing the risk of utility damage through precise and timely locates.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfUndress Baby
The quest for the best AI face swap solution is marked by an amalgamation of technological prowess and artistic finesse, where cutting-edge algorithms seamlessly replace faces in images or videos with striking realism. Leveraging advanced deep learning techniques, the best AI face swap tools meticulously analyze facial features, lighting conditions, and expressions to execute flawless transformations, ensuring natural-looking results that blur the line between reality and illusion, captivating users with their ingenuity and sophistication.
Web:- https://undressbaby.com/
E-commerce Development Services- Hornet DynamicsHornet Dynamics
For any business hoping to succeed in the digital age, having a strong online presence is crucial. We offer Ecommerce Development Services that are customized according to your business requirements and client preferences, enabling you to create a dynamic, safe, and user-friendly online store.
Transform Your Communication with Cloud-Based IVR SolutionsTheSMSPoint
Discover the power of Cloud-Based IVR Solutions to streamline communication processes. Embrace scalability and cost-efficiency while enhancing customer experiences with features like automated call routing and voice recognition. Accessible from anywhere, these solutions integrate seamlessly with existing systems, providing real-time analytics for continuous improvement. Revolutionize your communication strategy today with Cloud-Based IVR Solutions. Learn more at: https://thesmspoint.com/channel/cloud-telephony
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
Looking for a reliable mobile app development company in Noida? Look no further than Drona Infotech. We specialize in creating customized apps for your business needs.
Visit Us For : https://www.dronainfotech.com/mobile-application-development/
Hand Rolled Applicative User ValidationCode KataPhilip Schwarz
Could you use a simple piece of Scala validation code (granted, a very simplistic one too!) that you can rewrite, now and again, to refresh your basic understanding of Applicative operators <*>, <*, *>?
The goal is not to write perfect code showcasing validation, but rather, to provide a small, rough-and ready exercise to reinforce your muscle-memory.
Despite its grandiose-sounding title, this deck consists of just three slides showing the Scala 3 code to be rewritten whenever the details of the operators begin to fade away.
The code is my rough and ready translation of a Haskell user-validation program found in a book called Finding Success (and Failure) in Haskell - Fall in love with applicative functors.
Zoom is a comprehensive platform designed to connect individuals and teams efficiently. With its user-friendly interface and powerful features, Zoom has become a go-to solution for virtual communication and collaboration. It offers a range of tools, including virtual meetings, team chat, VoIP phone systems, online whiteboards, and AI companions, to streamline workflows and enhance productivity.
GraphSummit Paris - The art of the possible with Graph TechnologyNeo4j
Sudhir Hasbe, Chief Product Officer, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
4. Sinatra
is
a
DSL
for
quickly
crea<ng
web
applica<ons
in
Ruby
5. # hi.rb
require 'rubygems’
require 'sinatra'
get '/' do
'Hello world!’
end
$ gem install sinatra
$ ruby hi.rb
== Sinatra has taken the stage ...
>> Listening on 0.0.0.0:4567
$ curl http://0.0.0.0:4567
Hello World
9. Rou?ng:
Splat
Support
get '/say/*/to/*' do
# matches /say/hello/to/world
params['splat'] # => ["hello", "world"]
...
end
get '/download/*.*' do
# matches /download/path/to/file.xml
params['splat'] # => ["path/to/file", "xml"]
...
end
10. Rou?ng:
Regex
Support
get /A/hello/([w]+)z/ do
"Hello, #{params['captures'].first}!”
...
end
11. Rou?ng:
Op?onal
Parameters
get '/posts.?:format?' do
# matches "GET /posts" and
# any extension "GET /posts.rss", "GET /posts.xml" etc.
end
12. Rou?ng:
URL
Query
Parameters
get '/posts' do
# matches "GET /posts?title=foo&author=bar"
title = params['title']
author = params['author']
# uses title and author variables;
# query is optional to the /posts route
End
13. Rou?ng:
Condi?onal
Matching
get '/', :host_name => /^admin./ do
"Admin Area, Access denied!"
end
get '/', :provides => 'html' do
haml :index
end
get '/', :provides => ['rss', 'atom', 'xml'] do
builder :feed
end
14. Rou?ng:
Custom
Condi?ons
set(:probability) { |value| condition { rand <= value } }
get '/win_a_car', :probability => 0.1 do
"You won!"
end
get '/win_a_car' do
"Sorry, you lost."
End
15. Returning
Results
# 1. String containing the body and default code of 200
get '/' do
'Hello world!’
end
# 2. Response code + body
get '/' do
[200, 'Hello world!’]
end
# 3. Response code + headers + body
get '/' do
[200, {'Content-Type' => 'text/plain'}, 'Hello world!’]
end
17. Hello
World
with
Rack
# hello_world.rb
require 'rack'
require 'rack/server’
class HelloWorldApp
def self.call(env)
[200, {}, 'Hello World’]
end
end
Rack::Server.start :app => HelloWorldApp
18. Rack
env
# hello_world.rb
require 'rack'
require 'rack/server’
class HelloWorldApp
def self.call(env)
[200, {},
"Hello World. You said: #{env['QUERY_STRING']}"]
end
end
Rack::Server.start :app => HelloWorldApp
20. Typical
env
(con’t)
...
"HTTP_USER_AGENT"=>
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4)
AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47
Safari/536.11",
"HTTP_ACCEPT_ENCODING"=>"gzip,deflate,sdch",
"HTTP_ACCEPT_LANGUAGE"=>"en-US,en;q=0.8",
"HTTP_ACCEPT_CHARSET"=>"ISO-8859-1,utf-8;q=0.7,*;q=0.3",
"HTTP_COOKIE"=> "_gauges_unique_year=1;
_gauges_unique_month=1",
"GATEWAY_INTERFACE"=>"CGI/1.2",
"SERVER_PORT"=>"8080",
"QUERY_STRING"=>"",
"SERVER_PROTOCOL"=>"HTTP/1.1",
"rack.url_scheme"=>"http",
"SCRIPT_NAME"=>"",
"REMOTE_ADDR"=>"127.0.0.1",
...
}
21. The
Rack::Request
Wrapper
class HelloWorldApp
def self.call(env)
request = Rack::Request.new(env)
request.params # contains the union of GET and POST
params
request.xhr? # requested with AJAX
require.body # the incoming request IO stream
if request.params['message']
[200, {}, request.params['message']]
else
[200, {}, 'Say something to me!']
end
end
end
22. Rack
Middleware
u Rack
allows
for
chaining
mul?ple
call()
methods
u We
can
do
anything
we
want
within
each
call()
u This
includes
separa?ng
behavior
into
reusable
classes
(e.g.
across
Sinatra
and
Rails)
u SRP
(Single
Responsibility
Principle)
– Each
class
has
a
single
responsibility
– Our
app
is
composed
of
mul?ple
classes
that
each
do
one
thing
well
23. Rack::Builder
for
Middleware
# this returns an app that responds to call cascading down
# the list of middlewares.
app = Rack::Builder.new do
use Rack::Etag # Add an ETag
use Rack::ConditionalGet # Support Caching
use Rack::Deflator # GZip
run HelloWorldApp # Say Hello
end
Rack::Server.start :app => app
# Resulting call tree:
# Rack::Etag
# Rack::ConditionalGet
# Rack::Deflator
# HelloWorldApp
24. Using
the
Rackup
Command
u Combines
all
of
these
concepts
into
a
config
u Will
start
a
web
process
with
your
Rack
app
u Central
loca?on
for
requires,
bootstrapping
u Enables
middleware
to
be
configured
as
well
u Default
filename
is
config.ru
u Used
to
bootstrap
Rails
25. Using
Rackup
# config.ru
# HelloWorldApp defintion
# EnsureJsonResponse defintion
# Timer definition
use Timer
use EnsureJsonResponse
run HelloWorldApp
$ rackup –p 4567
26. Using
Mul?ple
Sinatra
Apps
u Rackup
allows
for
moun?ng
mul?ple
Sinatra
Apps
u This
allows
for
more
modular
APIs
u Recommend
one
Sinatra
app
per
top-‐level
resource
27. Moun?ng
Mul?ple
Sinatra
Apps
# config.ru
require 'sinatra'
require 'app/auth_api'
require 'app/users_api'
require 'app/organizations_api'
map "/auth" do
run AuthApi
end
map "/users" do
run UsersApi
end
map "/organizations" do
run OrganizationsApi
end
28. Important:
Require
!=
Automa?c
u Must
manage
your
own
requires
u No
free
ride
(like
with
Rails)
u This
means
order
of
requires
is
important!
30. Mul?ple
API
Design
Choices
u RPC-‐based
– Uses
HTTP
for
transport
only
– Endpoints
are
not
unique,
only
the
payload
– No
HTTP
caching
available
– e.g.
POST
/getUserDetails,
POST
/createUser
u Resource-‐based
– Unique
URLs
for
resources
and
collec?ons
– HTTP
caching
available
– e.g.
GET
/users/{userId}
and
GET
/users
31. Hypermedia
REST
u An
architectural
style,
with
constraints
u A
set
of
constraints,
usually
on
top
of
HTTP
u Not
a
standard;
builds
on
the
standard
of
HTTP
u Mul?ple
content
types
(e.g.
JSON,
XML,
CSV)
u The
response
is
a
representa?on
of
the
resource
state
(data)
plus
server-‐side
state
in
the
form
of
ac<ons/transi<ons
(links)
33. Resource
Lifecycle
using
Sinatra
get '/users' do
.. list a resource collection (and search) ..
end
get '/users/:id' do
.. resource instance details ..
end
post '/users' do
.. create new resource ..
end
put '/users/:id' do
.. replace resource ..
End
delete ’/users/:id' do
.. annihilate resource ..
end
34. List
Resources
Example
get '/users' do
# 1. capture any search filters using params[]
email_filter = params[:email]
# 2. build query and fetch results from database
if email_filter
users = User.where( email: email_filter ).all
else
users = User.all
# 3. marshal results to proper content type (e.g. JSON)
[200, users.to_json]
end
35. List
Resources
Example
get '/users' do
# 1. capture any search filters using params[]
email_filter = params[:email]
# 2. build query and fetch results from database
if email_filter
users = User.where( email: email_filter ).all
else
users = User.all
# 3. marshal results to proper content type (e.g. JSON)
[200, users.to_json]
# Q: Which ORM should we use with Sinatra?
# Q: Can we customize the results format easily?
end
37. Selec?ng
an
ORM
u Ac?veRecord
u DataMapper
u Sequel
(my
favorite)
– Flexible
as
it
supports
Datasets
and
Models
38. Sequel
Datasets
Example
require 'sequel'
DB = Sequel.sqlite # memory database
DB.create_table :items do
primary_key :id
String :name
Float :price
end
items = DB[:items] # Create a dataset
items.insert(:name => 'abc', :price => rand * 100)
items.insert(:name => 'def', :price => rand * 100)
items.insert(:name => 'ghi', :price => rand * 100)
puts "Item count: #{items.count}"
puts "The average price is: #{items.avg(:price)}”
39. Sequel
Model
Example
require 'sequel'
DB = Sequel.sqlite # memory database
class Post < Sequel::Model
end
post = Post[123]
post = Post.new
post.title = 'hello world'
post.save
40. Select
a
Marshaling
Library
u Ac?veModel::Serializers
(AMS)
– Works
with
Kaminari
and
WillPaginate
– Supported
by
Rails
core
team
– One-‐way
JSON
genera?on
only
u Roar+Representable
(my
favorite)
– Works
with
and
without
Rails
– Bi-‐direc?onal
marshaling
– Supports
JSON,
XML,
YAML,
hash
41. Representable
module SongRepresenter
include Representable::JSON
property :title
property :track
collection :composers
end
class Song < OpenStruct
end
song = Song.new(title: "Fallout", track: 1)
song.extend(SongRepresenter).to_json
> {"title":"Fallout","track":1}
song = Song.new.extend(SongRepresenter).from_json(%
{ {"title":"Roxanne"} })
> #<Song title="Roxanne">
42. Roar
+
Representable
module SongRepresenter
include Roar::JSON
include Roar::Hypermedia
property :title
property :track
collection :composers
link :self do
"/songs/#{title}"
end
end
song = Song.new(title: "Fallout", track: 1)
song.extend(SongRepresenter).to_json
> {"title":"Fallout","track":1,"links":
[{"rel":"self","href":"/songs/Fallout"}]}"
43. Tools
for
Tes?ng
Your
API
u Unit
–
RSpec
– Models,
helpers
u Integra?on
–
RSpec
– Make
HTTP
calls
to
a
running
Sinatra
process
– Controller-‐focused
u Acceptance/BDD
–
RSpec,
Cucumber
– Make
HTTP
calls
to
a
running
Sinatra
process
– Use-‐case/story
focused
45. Addi?onal
Gems
u faraday
–
HTTP
client
with
middleware
for
tes?ng
and
3rd
party
API
integra?on
u xml-‐simple
–
Easy
XML
parsing
and
genera?on
u faker
–
Generates
fake
names,
addresses,
etc.
u uuidtools
–
uuid
generator
when
incremen?ng
integers
aren’t
good
enough
u bcrypt
–
Ruby
binding
for
OpenBSD
hashing
algorithm,
to
secure
data
at
rest
46. Addi?onal
Gems
(part
2)
u rack-‐conneg
–
Content
nego?a?on
support
get '/hello' do
response = { :message => 'Hello, World!' }
respond_to do |wants|
wants.json { response.to_json }
wants.xml { response.to_xml }
wants.other {
content_type 'text/plain'
error 406, "Not Acceptable"
}
end
end
curl -H "Accept: application/json" http://localhost:4567/
hello
47. Addi?onal
Gems
(part
3)
u hirb
–
Console
formaing
of
data
from
CLI,
Rake
tasks
irb>> Tag.last
+-----+-------------------------+-------------+
| id | created_at | description |
+-----+-------------------------+-------------+
| 907 | 2009-03-06 21:10:41 UTC | blah |
+-----+-------------------------+-------------+
1 row in set
48. Reloading
with
Shotgun
Gem
u No
automa?c
reload
of
classes
with
Sinatra
u Instead,
use
the
shotgun
gem:
u Note:
Only
works
with
Ruby
MRI
where
fork()
is
available
(POSIX)
$ gem install shotgun
$ shotgun config.ru
49. Puma
+
JRuby
u Ruby
MRI
is
geing
beCer
u JVM
is
faster
(2-‐5x),
very
mature
(since
1997)
u High
performance
garbage
collectors,
na?ve
threading,
JMX
management
extensions
u JDBC
libraries
very
mature
and
performant
for
SQL-‐based
access
u Puma
is
recommended
over
unicorn
for
JRuby
50. From
Sinatra
to
Padrino
u Padrino
provides
Rails-‐like
environment
for
Sinatra
u Build
in
Sinatra,
move
to
Padrino
when
needed
u Generators,
pluggable
modules,
admin
generator