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/
Top comments (4)
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.
yeap, I found bug. Thanks for feedback.
See updated post π
I have send a fix por the get by id, but the post method isn't working
This bug was solved in HappyX 1.11.0