Write Simple RestAPI In Nim With Happyx #4

ethosa

Ethosa

Posted on June 24, 2023

Write Simple RestAPI In Nim With Happyx #4

Hi there! 👋

Previously we worked on posts 👨‍🔬

In this part we refactor our code and mount posts.

At first create /src/mounts/posts.nim and write

import happyx
Enter fullscreen mode Exit fullscreen mode

In main.nim delete all routes that provides work with posts.

import
  # This will import HappyX framework
  happyx


# Setting up our server at `127.0.0.1:5000`
serve("127.0.0.1", 5000):
  var posts = %*[
    {
      "title": "Hello",
      "text": "world"
    }, {
      "title": "Bye",
      "text": ":("
    }, {
      "title": "Perfect nim web framework?",
      "text": "it's HappyX 🍍"
    },
  ]

  # on GET HTTP method at 127.0.0.1:5000/hello-world
  get "/hello-world":
    # We'll see "Hello, world!"
    "Hello, world!"
Enter fullscreen mode Exit fullscreen mode

And import posts into main:

import
  # This will import HappyX framework
  happyx,
  ./mounts/[posts]
Enter fullscreen mode Exit fullscreen mode

Write in mounts/posts.nim:

# Request model AddPost
# with two string fields
model AddPost:
  title: string
  text: string


mount Posts:
  # on GET HTTP method at 127.0.0.1:5000/posts
  get "/":
    # will responds all posts
    return posts

  # on GET HTTP method at 127.0.0.1:5000/post
  get "/$index:int":  # index is post index
    if posts.len > index:
      # try open 127.0.0.1:5000/post0
      return posts[index]
    else:
      # try open 127.0.0.1:5000/post10
      return {
        "error": "post index is wrong"
      }

  # on POST HTTP method at 127.0.0.1:5000/post/
  post "/[postData:AddPost]":
    posts.add(%*{
      "title": postData.title,
      "text": postData.text
    })
    return {"response": {
      "index": posts.len - 1
    }}
Enter fullscreen mode Exit fullscreen mode

And mount it:

  ...

  mount "/posts" -> Posts

  # on GET HTTP method at 127.0.0.1:5000/hello-world
  get "/hello-world":
    # We'll see "Hello, world!"
    "Hello, world!"
Enter fullscreen mode Exit fullscreen mode

Now see
GET http://127.0.0.1:5000/posts/
GET http://127.0.0.1:5000/posts/1
POST http://127.0.0.1:5000/posts/

Source code

💖 💪 🙅 🚩
ethosa
Ethosa

Posted on June 24, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related