Write Simple RestAPI In Nim With Happyx #4
Ethosa
Posted on June 24, 2023
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
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!"
And import posts
into main
:
import
# This will import HappyX framework
happyx,
./mounts/[posts]
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
}}
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!"
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/
💖 💪 🙅 🚩
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
watercooler Why does a reboot make your PC run SO much faster than running all the cleaning tools you can possibly imagine?
November 30, 2024