DEV Community

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

Posted on • Edited on

3

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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay