Creating JSON-API in Elixir-Phoenix with ease using ja_serializer.

Search for a command to run...

No comments yet. Be the first to comment.
Motivation Recently, I tried to learn some low-level system programming stuff. I am a Mac user, and I thought that everything that works on Linux should also work on Mac. After all, Mac is a Unix-based system 😊. I guess we all heard this. Oh boy! I ...

Problem Statement While working on a Nestjs project, I encountered a weird problem related to the database column. I was trying to insert a record into a MySQL table using TypeORM. The error I was experiencing stated that a specific column “cannot be...

Recently, I was exploring design patterns courses on my LinkedIn Learning subscription. I came across a course, Node.js: Design Patterns by Alex Banks. It is a wonderful, easy-to-understand course. I started with the Builder Pattern, and the explanat...

Suppose you are working on a table in a LiveView project. This table has limited static data of not more than one page (you can avoid questions about pagination in the comment section 😊). From a user's point of view, it becomes hard to look into the...

Recently, while working on one of my personal Elixir projects. I came across a scenario where I needed to make some changes to the database schema.The changes mainly revolve around adding and removing indexes due to changes in the business requiremen...

Today, most of the Web application uses Modern Frontend frameworks like React, Angular, Ember, etc. These frameworks use the JSON API to interact with some back-end. JSON-API is the preferred specification for building APIs. This post will help you in creating JSON-API using ja_serializer(an Elixir library) for an Elixir-Phoenix app. We are going to create a simple Blog(everyone's favorite example 😉 ) application. This application will generate JSON-API, which will be accessible for SPA's to use.
I'll divide this post into 3 parts for the sake of simplicity:
ja_serializer(Here we will configure ja_serializer).ja_serializer into action).mix phx.new --no-webpack --no-html my_blog_api
cd my_blog_api.mix ecto.create. This will generate database along with Repo.Post model along with Blog context. This can be achieved by following command.mix phx.gen.context Blog Post posts title:string body:text
//This will create `Post` model along with `Blog` context and 5 main `CRUD` operations methods.
iex -S mix phx.server and run MyBlogApi.Blog.list_posts. This is going to return all Posts. In our case its a fresh app. So, try creating few records and test this function later :) .ja_serializer:{:ja_serializer, "~> 0.12.0"} in mix.exs and run mix deps.get.ja_serializer. We need to add configuration in our app to make it use json-api specification headers.poison to encode requests for our new json-api mime type. (To install poison add poison in mix.exs and run mix deps.get).config in config/config.exs.config :mime, :types, %{
"application/vnd.api+json" => ["json-api"]
}
config :phoenix, :format_encoders, "json-api": Poison
Also update the error type in ErrorView in the same file. It has an array with only json type. Add json-api as well in it. Update the line as below
render_errors: [view: MyBlogApiWeb.ErrorView, accepts: ~w(json json-api)],
Now we need to rebuild the plugin dependency by running the following command.
mix deps.clean mime --build
Next, we have to do some setup to make our router to use ja_serializer:
plug JaSerializer.ContentTypeNegotiationjaserilaizer deserializer to convert bobcase property to underscore property.
plug JaSerializer.Deserializerpipeline :api do
plug :accepts, ["json", "json-api"]
plug JaSerializer.ContentTypeNegotiation
plug JaSerializer.Deserializer
end
ja_serializer, we will now create a Post#index endpoint to see json-api response.router.ex add resources /posts, PostController, only: [:index]my_blog_api_web/controllers/post_controller.ex.Add an index action.
defmodule MyBlogApiWeb.PostController do
use MyBlogApiWeb, :controller
alias MyBlogApi.Blog
def index(conn, _params) do
posts = Blog.list_posts()
render(conn, "index.json-api", data: posts)
end
end
Create a my_blog_api_web/views/post_view.ex file for post to render json and add the following code.
defmodule MyBlogApiWeb.PostView do
use MyBlogApiWeb, :view
use JaSerializer.PhoenixView
attributes [:title, :body]
end
attributes macro, we can specify the fields we want to send in response.postman and hit posts endpoint i.e localhost:4000/posts you can see the response in json-api format.I hope you like this post. If you any questions please add the comment below.👇
Note:
If you face an error related to CORS while integrating this API into the frontend- framework follow this blog👇