Build Blazing Fast Backends with Rust & Actix Web

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
milliseconds can make a big difference routine success and failure when it comes to backend development Additionally you do not only want to have performance but also safety that your code runs perfectly and your code does not crash because it sucks that's why I'm going to give you a stepbystep guide on how you can build a basic web server using rust and tic so let's go so first off I think it's pretty straightforward that we need to install actex web so that we can use actex additionally I've also installed which is basically used for serialization or deserialization when it comes to for instance using Json in your HTTP server so let's quickly jump into our main RS file and then let's just start with our main function here in that main function we are just going to use the port 8080 and then we are going to create a simple print line statement which just prints that our server is running on Port 8880 so this should be not really complex so far so let's just create create our HTTP server and we import that from actic SWAP after that we're going to call the new function and this new function returns some sort of factory of the HTTP server but also requires a closure in this closure we now configure our app so what we could use is just the app from actic SWAP then we say new and then we can declare for instance our services here now we can do this later after that we're going to make use of the bind function of the HTTP server and in this bind function we can Define the address which could be Local Host and we need to Define here our Port which basically is 880 after that we start the HTP server with run and then we make use of await now run await basically runs and waits until the HTTP server was terminated due to maybe some error or due to the fact that we manually terminate this server now this here here does not really work because we have some sort of mismatch type so first off we have the bind function the bind function returns a result and obviously we need to handle this result and we can do this for now by just using this question mark operator now this basically means that it catches kind of automatically the arror and then returns it to the function so I'm going to make one video specifically about this question mark operator but for now it means to you that it just Returns the error now because we now return the error and therefore the result to our main function we obviously need to declare the return type here to a result which comes from stdio so it's a standard Library import and then we Define here the void type in Rust additionally because we use a weight we need to make sure that this function is also marked as a synchronous now I'm going to also make a whole series about about the concurrency features of rustling but for now you can think of asyn like the typical thing in JavaScript of async await or promises in this case at the moment we have some weird error that basically says that the main function is not allowed to be async and to fix this we can make use of an actic macro so we can Define this macro here and can just say actic web and then Main and there we go we have our basic HTTP server and now we can obviously enhance this by for instance just using the workers method now this workers method needs one argument and here we can Define the threats that this HTTP server should run on now like I said before threats and async we and all that rust concurrency magic I'm going to explain this in a different series but for now this basically means that our HTTP server can receive multiple requests concurrently and con process them concurrently as well so now obviously we we have some sort of HTTP server but we do not have an endpoint yet so how we are going to Define our first endpoint we just declare a function which we can name greed now this basically means that our greed return value should implement the responder type from actic web we also need to make sure that this is an asynchronous method because obviously our function can be called asynchronously in two threats for instance and for now in here we just return the format of for instance hello world now format basically creates a suitable type for our return type we've used here now to make this really an actic web endpoint we obviously need to make sure that this is an endpoint right so we need to define the path of this endpoint for that we can make use of another macro of actic web and here we say get and we import get obviously from actic web again you can by the way also use just actic web and then get and now we can call this function and then then we Define the path in this function so for instance we can declare this endpoint as SLG greet so right now the greed function gets executed whenever a user visits the SLG greed endpoint and now we've defined our endpoint but now we also need to register that into our HTTP server and we can do this by making use of this service function and in this service function we Define now our greed function and that's basically it we've now declared our greed endpoint in our HTTP server now to run this we can simply hit cargo run and this just compiles and builds our server and now if we visit our local horse with 880 and obviously the greed end point we get the return value hello world now this is pretty cool but how about path parameters so for instance I want to greet a specific user in not just a simple hell world the only thing we need to manipulate here is the path obviously so we Define here in curly brackets the name of the path parameter which in this case is just ID and then we can make use of this path parameter in our greed function by just saying user ID and then defining the type as web and then path and then we Define the type of the path parameter now obviously we need to import web here from actic web and now we've defined our user ID and by the way the naming of this path parameter can be pretty much anything you want so you could also say instead of user ID ABC and then after that I'm just going to quickly say hello and then user ID in our format function here now if we restart our server and then call the endpoint with for instance my name we obviously get first the rust magic which basically means cannot pass floran to a u32 so obviously it cannot pass a string to an unsigned integer but it can obviously pass one 2 3 for instance and that works perfectly so we've now discussed path parameters but let's just make this whole example a bit more complex so let's say we want to declare some sort of rust struct and want to return this in Json format but we also want to insert some data through our post request for instance so let's just declare here a simple struct which we call user and this user struct contains a simple string now in here to really deserialize but also serialize this struct to adjacent format we can make use of this Sur a macro where we make use of the r and then we say serialize but we also say deserialize and now that basically means that it can serialize or transform our user struct to a suitable Json format but it can also deserialize some input to a US user struct so to simulate a database I'm just going to make use of a simple map so for that I'm going to declare a new type which we call user DB and this is now an arc mutex and now in here we declare our hashmap where the key is a u32 and the value is a user now what exactly does that line mean here it's pretty simple we just declare a new type which can be a hashmap however we also create through this Arc generic here some Atomic reference counting now I've already made some sort of similar video about Arc and mutex so I highly recommend watching this first but basically Ark is for moving ownership into closures and managing our references more easily through reference counting and mutex basically sets a mutually exclusive flag now that means that we cannot manipulate or insert new data into the user DB into concurrent threats now obviously this is not perfect here because the situation can come up that we need to manipulate the data in our DB into threats so for that I highly recommend using some sort of data structure that works perfectly concurrently or basically use some real database okay enough talking let's just declare our user Tob here by declaring a new variable which we just call user DB and the type is obviously user DB and the value is this here and this looks pretty complex but it basically suits the user DB type now it's necessary to declare this DP outside of our closure because multiple threats or multiple end points can make use of this DB but now obviously we need to make use of this DB inside our endpoints right so we can declare the move keyword here just FY also did a video about that so I highly recommend checking this one out as well and then we can declare our app data which basically will be some sort of web data that is provided through actic web so we can make use of web and then data and then new and then we are going to clone our user DB now it's important to note that clone comes here from our Arch type so this is needed for basic reference counting and then we are going to find our app data here through the app data function and now we've basically provided all our endpoints we've declared through this do service function with our app data which is a pretty basic DB now the order is not important here so we could also say that the app data is after the service actic web basically handles the order here for us so let's create a quick post endpoint now we're going to name this create user and obviously this also returns turns a implementation of the responder trait in here we basically Define our user data which comes from the request body of this specific endpoint so we need to say web Json and then we say user as the structure now because we use Sur here actic web natively supports this transformation to basically deserializing our request body to our user struct but then we also need to create or insert this data in into our local DB so we can just make use of the DB directly inside of our function argument so in here we just make use of the web data again which is really important and actic web basically handles the passing for us and here again the order of the arguments is not important now obviously before I forget that we obviously need to make sure that this is a real post endpoint and here we just say users so we want to make a post request towards WS the/ users endpoint now in here we basically lock first our mutex in our DB by just creating a new mutable variable DB and then we are locking the function parameter so our mutex in our DB and then we say just unwrap obviously it is recommended to handle this error but for now just for demonstration purposes I'm going to unwrap this directly then we need to create some sort of new ID because we obviously want to have this automatically and we say here db. keys to get all the keys then we make use of the max function then we say unwrap or and then we say reference to zero and then we say plus one now this reference to zero is necessary because the unrep or function needs some sort of reference to a value so we just say here reference zero after that we're going to insert our data into our hashmap so we now have here the hashmap and here we we basically use the new ID as a key and then we say user data into inner as the value now into inner is something similar to an unwrapping function which basically unwraps the Json request body retrieve through calling this API endpoint and then it just deserializes the Json data to our user struct and inserts it into our hashmap and by the way if we want to return the created data directly in this endpoint we can do this but first we have to make sure that we get the name of the user data here we just say user data then name and then we say clone in this case we clone it directly to create a new variable to create a new reference of this name and basically clone it into the memory so we can make use of it even after this into inner function and now in here we return an H shtp response which again comes from actic web and then we make use of the ad Json function now again this comes from Ser directly so actic web supports native le 30 and then we can create a new user for instance and just return here the name now obviously if you want to go beyond this we could also create a new struct and in here we also need to serialize this struct so that we basically can convert this struct into valid Json and in here we have an ID which is a u32 and a name which could be a string and after that we could basically say instead of user create user response and now obviously there is a missing field for instance ID so we can say ID and then new ID and then the name stays the same and then obviously we need to declare the service here with the function name that creates the user or has the post end point now that was a lot of code let's just quickly test if everything works fine so for that we're making use of Postman and obviously we declare a post method here then we Define the URL with the endpoint users and in the body which is of type Json we declare the name so for instance user XXXX so then we hit send and what we get back is a brand new ID with the correct name now if we do this multiple times we obviously get a new ID back now let's quickly transform our get method here so obviously our path has to be users so we want to retrieve a user by ID so we just say users ID then we have the user ID we're going to name this function get user for instance but then we also need the data so our database and now this function here returns a result of the implementation of the responder trade or an error so there obviously could be an error whenever the user ID was not found in our users d now let's just like I said before transform the user ID to into inner so user ID instead of being a web path type is now a u32 then again we can just use the DB where we are going to lock this DP first through the mutex and then we are just going to unwrap this and in here we are going to make use of the match keyword and here we're going to say DB get then we say user ID which we declare as a reference now obviously this could return some user data so the ID was found in our DB and if it was found we just return okay HTTP response and then okay as well and then Json and then user data and obviously if like there was no result in our database so the user ID was not found we just return the error with error not found and then we say user not found oh one more thing I forgot we OB obviously need to import the error from actic web here so we actually made use of the error in our generic result here so we obviously need to import it finally we obviously need to rename greet in our service declaration here to get user and now we have a fully functional HTTP server made with rust and actic web now let's just quickly test this obviously we need to create a new user because all our data gets lost whenever we basically restart our server we've declared a new user with the ID one and now if we want to get the user we just call our users endpoint with the path parameter one as an ID and now this returns our name and this works perfectly and obviously you can enhance the get method here by just returning the ID and the name for instance instead of just returning the name but that was basically it I hope it was not too confusing I know this rust concurrency magic and all this generic macro magic could be pretty confusing sometimes and obviously there's a lot more to know about actic web like middleware but the next step would be to just dockerize this rust application so that it can run everywhere and luckily there's one command that just dockerized your whole rust application so feel free to watch this video here anyway thank you so much for watching have a lovely day and bye-bye
Info
Channel: Flo Woelki
Views: 7,554
Rating: undefined out of 5
Keywords: rust, actix web, api development, backend development, async rust, rust actix web, rust actix, rust api, rust backend, rust backend frameworks, rust backend app, rust backend web development, rust backend web frameworks, rust frameworks, rust actix example, rust actix api, rust actix web example, rust actix web tutorial, rust actix tutorial
Id: 4Q7FAMydzOU
Channel Id: undefined
Length: 18min 28sec (1108 seconds)
Published: Sat Mar 16 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.