DEV Community

Cover image for Writing Simple RestAPI in Nim With HappyX #2
Ethosa
Ethosa

Posted on • Updated on

Writing Simple RestAPI in Nim With HappyX #2

Previously we added /hello-world method that responds "Hello, world!"

In this series, we'll attempt to write methods for working with simple posts (without connecting to a database for now). 🙂

Let's open /tutorial/src/main.nim 🍍

Rewrite this

# Setting up our server at `127.0.0.1:5000`
serve("127.0.0.1", 5000):
Enter fullscreen mode Exit fullscreen mode

to this

# 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 🍍"
    },
  ]
Enter fullscreen mode Exit fullscreen mode

After this we add a new method that responds all posts 🔨
Try recompile /src/main.nim and open ✌http://localhost:5000/posts

  # on GET HTTP method at 127.0.0.1:5000/posts
  get "/posts":
    # will responds all posts
    return posts
Enter fullscreen mode Exit fullscreen mode

Add method that responds only one post also 🛠

  # on GET HTTP method at 127.0.0.1:5000/post
  get "/post$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"
      }
Enter fullscreen mode Exit fullscreen mode

And open http://localhost:5000/post1 as example 🙂

That's all, good luck ✨

Source code

Top comments (0)