Web Development

Elixir REST APIs

Building REST APIs

Elixir REST APIs use Phoenix with JSON responses.

Introduction to Phoenix Framework

The Phoenix Framework is the go-to choice for building web applications in Elixir. It is known for its high performance and scalability, making it an excellent choice for creating REST APIs. In this post, we'll cover how to create a simple REST API using Phoenix with JSON responses.

Setting Up a New Phoenix Project

To start creating your REST API, you'll first need to set up a new Phoenix project. Ensure you have Elixir and Phoenix installed on your machine. You can create a new Phoenix project by running the following command:

This command creates a new Phoenix project without HTML and Webpack, which are not needed for an API-only application.

Creating a Simple Resource

Next, let's create a simple resource. We will define a model for a 'Post' resource and expose it through our API. First, generate a context and a schema for the Post resource:

This command generates a context module for the Blog and a Post schema with title and body fields.

Adding a Controller for JSON Responses

Next, you need to create a controller that will handle HTTP requests and return JSON responses. Use the Phoenix generator to create a new controller:

This command will create a JSON controller, views, and routes for the Post resource, enabling CRUD operations with JSON responses.

Configuring Routes

Ensure your routes are correctly configured to handle the API requests. Open the lib/my_api_web/router.ex file and confirm the following setup:

This configuration sets up the routes for the Post resource under the /api scope, using the PostController to manage requests.

Testing Your API

With your routes and controllers set up, you can now start your Phoenix server and test your API endpoints. Run the following command to start the server:

Visit http://localhost:4000/api/posts to interact with your API. You can use tools like Postman or curl to send requests and verify the responses.

Previous
Plug