DEV Community

Ethosa
Ethosa

Posted on • Updated on

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

Top comments (4)

Collapse
 
alfonsodg profile image
Alfonso de la Guarda Reyes

Hi... I am tryting to follow your steps, but i only receive this message: [2023-07-24 at 09:52:56]:INFO Server started at 127.0.0.1:5000
[2023-07-24 at 09:53:00]:INFO GET::/
[2023-07-24 at 09:53:00]:WARN / is not found.
[2023-07-24 at 09:53:08]:INFO GET::/posts
[2023-07-24 at 09:53:08]:WARN /posts is not found.
[2023-07-24 at 09:53:11]:INFO GET::/posts/
[2023-07-24 at 09:53:11]:WARN /posts/ is not found.

Collapse
 
ethosa profile image
Ethosa

yeap, I found bug. Thanks for feedback.

See updated post 🙂

Collapse
 
alfonsodg profile image
Alfonso de la Guarda Reyes

I have send a fix por the get by id, but the post method isn't working

Thread Thread
 
ethosa profile image
Ethosa

This bug was solved in HappyX 1.11.0