Examples

Crystal Web App

Building a Web App

Crystal web app uses Kemal for server-side rendering.

Introduction to Crystal and Kemal

Crystal is a programming language that combines the elegance of Ruby with the speed of C, making it an excellent choice for web applications. Kemal is a lightweight web framework for Crystal, inspired by Sinatra, designed for simplicity and speed. In this guide, we'll explore how to create a web app using Crystal and Kemal for server-side rendering.

Setting Up Your Development Environment

Before we begin, ensure you have Crystal installed on your machine. You can download it from the official Crystal website. Once Crystal is installed, use the following command to install Kemal:

Creating a Simple Kemal Web App

Let's create our first Kemal web app. First, create a new file called app.cr and add the following code:

This simple application will respond with "Hello, World!" when you access the root URL. To start the server, simply run:

Understanding Kemal's Routing

Kemal uses a routing system similar to Sinatra. You can define routes using HTTP methods like get, post, put, patch, and delete. Here's an example of how to create different routes:

In the example above, the /hello/:name route will greet a user with their name, and the /submit route handles POST requests.

Using Templates for Server-Side Rendering

Kemal supports server-side rendering with templates. You can use popular templating engines like ECR (Embedded Crystal). Let's see an example of how to use ECR to render an HTML page:

In this example, we define a template in views/index.ecr and render it using the render method. The template receives the name parameter, allowing dynamic content rendering.

Conclusion and Next Steps

You've now learned the basics of creating a web app using Crystal and Kemal. The flexibility and speed of Crystal combined with Kemal's simplicity make it a powerful choice for web development. In the next post, we'll explore API testing to ensure your web applications are robust and reliable.