Building an API in Rust (Part 3)
Key Takeaways
Building a RESTful API in Rust using Rocket framework, handling CRUD operations, and integrating with a database, with a focus on error handling, API design, and JSON output formatting
Full Transcript
hey guys welcome back to the REST API tutorial my name is tensor in the last video we set up our database pool and we also set up some static routes today we're actually going to build the framework for our API to allow users to input and output Jason to perform crud activities on our data and we're also going to add a little bit of error handling and stuff like that alright so we've already seen how we can add some functions to the routes using rocket via this mount function and the routes macro so now we want to create a sub module called routes inside of this routes file I'm going to bring in DB connection as DB connection I'm gonna bring in rocket contribs an I'm also going to bring in super models Brooke and new burke and I'll bring in sir a Jason value and we'll talk about each of these items as we get to them the first feature that we want to implement for our API is the ability to pull all of our data out of our database and look at it so we're gonna put this on the route of backflash books and our format is going to be of course application JSON the actual function itself will take in our DB connection and it will output any jason with a value wrapped inside of it so this value is this serade Jason value and then the JSON type is the type that's coming from rakhi contribs and the reason why we're wrapping this value in this JSON value is so that we can serve this value from our handler directly if we were just using this array Jason value we wouldn't be able to serve it directly from our function and we'd have to write a bunch of other things to make it work we already have a method that's attached to our book model and there will allow us to query all of our books out of the database so we just say let books equal book Hall and then we pass in our connection and then we can actually build the jason by calling a jason function which is coming from rocket contribs and then a jason macro which is coming from sir ID jason and passing in the two fields that we want so we want status which will be 200 if this works and then we'll have a result which will come back with our books so this will come back with a huge vector filled with our books so basically we're calling a get request on books and then we get back our application JSON and it will be in a format that's very similar to what we've actually written because of this macro the next function that we want to write is a new function so this will allow us to create a new block which we can then insert into our database our declarative macro will be post and this will also be on the routes books our format will also be application JSON and we'll have a variable embedded inside of our macro called new underscore book in our function our new book is a JSON type wrapped around a new book type and of course we need to pass in our database connection and this will again pass out a jason wrapped around a value inside of our JSON function and our JSON macro our status could be book insert and we put our new book and we call this into inner function to actually force our new boss to unwrap itself from the JSON structure so it'll become a new book value and we also pass in the connection so this is actively inserting our book into the database then our result is calling book all with connection and then getting the first book out of our database that way every single time we put in our books we'll actually get back the book that we've put in if we look at our model we also have a method that allows us to query our books by ID let's make a part of the API that will let us do this so to query our books by ID we want to do a get method on the route books ID with the ID being the variable of our actual ID of the book and the format that gets returned will be application JSON and again for show this function we're gonna pass in our DB connection and then the idea of the book that we want to fetch out of the database and this will pass back Jason with a value wrapped inside of it this function is slightly more complicated than the other two above it we have to first get our result by calling book show with our ID and connection this will pull our book out by ID and then we want to check the status so we want to see if our result is empty or not if it is we'll make our status into 4 or 4 otherwise we'll make it into 200 then we'll take our status and we'll put it in the status field of our JSON and we'll put our result into the result field of our JSON and for a result we'll call get 0 so he gets the 0 index value just in case we have multiple books with this same ID for some reason we'll pull out just one of them we also have this by ID function so this allows us to update a book by ID in our database so we also want to create an API endpoint for this particular function we do this by creating a put request on books ID of course the format again is application JSON and our data so our variable will be this function will be called update will pass in our database connection our ID which comes from the route here and then our book which comes from the data that we're passing in to the JSON and this book will be a jason new book and of course we're going to be returning a value wrapped inside of json if you remember our book update by ID function gives back a boolean type so we want to say let's status equal if book update by and then we pass in our ID a reference to our connection and then book dot in to inner to unwrap it from the json and if the book exists in the database then we get back 200 otherwise we get back 4 or 4 and then our jason will just pass back the status with a result of null so in this case we don't actually need to pass back the book that we've altered we could but we don't actually need to so we're just going to pass back normal for a result and if the book was altered we'll get it 200 if it wasn't we'll get a 404 we have a delete by method inside of our models this allows us to delete by ID so we also want this function to be in our API in HTTP the delete is just a delete request and we'll just call it on books back slash ID so we'll get the idea of the book that we want to delete from the route and this delete function will take in our ID which is an i-32 and then the connection and output a JSON value and we want to check to see if this status again is a true or false value so we want to check to see if book delete by ID comes back with a deleted book and if it does then we've deleted it and we pass back 200 otherwise we pass back 4 or 4 again for our jason we don't really care about the result so we're just gonna pass back null and for the status we'll put in the one that comes back I'm running this method and I misspelled this method by calling it delete with ID it's actually delete by ID the last piece of functionality that we have for our database is the ability to query books by author this takes in our author string the connection and it outputs a vector book so it can output multiple books and of course we want to have this functionality on our API as well will create a get request on the route books authors with our author inside of it so this will pull our string directly from our route and then we'll have our format be application JSON and then the actual author function will take in that authors string from the route and then the database connection and pass back a JSON value and the astral jason for this function is fairly simple this is like our other get request we're just gonna pass back a status of 200 and then our resort will be all of the books that we pull out by author by calling the book by author method with our author in it and our reference to connection inside of it you might be thinking well what happens if for instance with our get request up here we passing something that doesn't exist in the database we're always passing back this 200 result here and we're doing the same for the get request down here and this shouldn't be a string by the way we're always passing back this status 200 and while we do have checks with this one this one we don't have checks with these other ones so this isn't a problem with rocket because we can actually generalize what our 404 error will look like we can do this again by using our declarative macro in this case we just call a catch and then we want to call it four or four so every single time a piece of jason comes back with a four or four then we'll run this function not found which will return a jason value and our error will just be jason jason status error and then reason resource was not found' and you can literally changes however you'd like now we have all of our routes we want to mount them onto our rocket function and we also want to make it so that it will actually catch our errors as well so for our API we want to mount this on a different route than our index route so we're serving static files through our index route our API will have its own route which will be back slash API back slash version one and then all of the other routes that we created inside of our routes module will be based off of that so this will be the index of all of those other routes so for instance if we want to call our index function we call API back slash version one back slash books and we do a get request on that now we also want to bring in all of our routes so we do a glob part of our routes and this will fix the error that we were seeing before so we're melting in Derek's new show delete author and update on this API backslash version one backslash and then four are not found are 404 not found function we can mount it by using this macro called catchers inside of this catch function and this will naturally set it up so that for both of our routes here and here when we get back a 404 error it will serve out that piece of data for us okay so now that we're done we can compile our project and run it with cargo run and of course compiling our project will come back with this configured for development message which shows where the actual app is located on localhost 8080 I version 1 books we have a post request on API version 1 books we have a get request on API version 1 books ID we have a delete request on that same route we have a get request on API version 1 books author and author and we have a put request on API version 1 books ID and it also shows you the names of the functions that are mounted on these different routes it also shows us our catcher's so it's catching the 404 error and then it says racket has launched from and it gives us our localhost 8080 called postman this allows us to do some jason queries and I've opened up postman and I put in localhost 8080 I version 1 books as a get request and if I hit Send you'll see here that we get back to 2 results that we had from before this has two books in it both of them are the same book because I guess they got copied no they have different IDs and you'll see that they're inside of our result field and they're listed as a list and then we also get our status with the 200 on it if we want to run a post request to add a book to our database we can click here go to post and then we can open up this body here and click on raw and then actually write in the JSON in this case I wrote in a title an author and a published value and if I click send you'll see that we get our result which gives us the result with the author the IDE published true and then it gives us our status which is true in this case which means that it got posted and we can see this by calling a request on our API version 1 books were out again having this copied book is kind of annoying me so now we can call a delete request on localhost:8080 i version 1 books number 2 so this will get rid of ID 2 I click send and it gives us back a result of null with the status of 200 which means that it actually should it work and I can go back to our get request and we can see that in fact it did work and it removes that copy so say we want to update one of our books we have to pass in the title author and the published say I just want to update the published maybe I'll make this false I'll just call this on API version 1 books number 3 so this is the third ID and if I hit Send it'll come back and say status 200 because it should have worked and it will give us a no result and we can get our book by ID and you can see here that the published field did change to false our last request is the get request on API version 1 books authors and then you put in the author name so you don't put in quotes or anything even though this is a string and I know this is a little bit messy but we just send it in and then we'll get back our results and inside of that result is a list with our adjacent book format though it has our author our ID our published in our title and if we had multiple books by the same author we would get those multiple books as well alright guys so that's it for our REST API tomorrow's tutorial we'll focus on building a front end using Elm so we're going to set up an elm environment that can query this API and it will be able to fetch all of the information from our database in a proper very Elm style way I hope you guys enjoyed this tutorial if you did feel free to like and subscribe if you have any questions or comments feel free to leave them in the box below and if you disliked it then by all means download it as much as you like have a good night
Original Description
This video is the final part in the Rust API tutorial series. We build out our Routes to allow us to pass JSON structures back and forth from our Database.
Source Code: https://github.com/tensor-programming/rust_api_part_3
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Tensor Programming · Tensor Programming · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
NodeJs, Text editors and IDEs
Tensor Programming
Vanilla JS todo App
Tensor Programming
Elm Tutorial part 1
Tensor Programming
Elm Lang Tutorial, Part 2
Tensor Programming
Elm Tutorial Part 3
Tensor Programming
Elm Tutorial Part 4 -- Analog Clock App
Tensor Programming
Elm Tutorial part 5 -- Snake Game
Tensor Programming
Elm Tutorial part 6 -- Calculator
Tensor Programming
Go Tutorial part 1 -- Hello World and Static File Server
Tensor Programming
Go Tutorial part 2 -- Web Crawler
Tensor Programming
Go Tutorial Part 3 (Web App part 1)
Tensor Programming
Go tutorial Part 4 (Web tutorial part 2) - Using templates
Tensor Programming
Go tutorial part 5 (web app part 3)
Tensor Programming
Go tutorial part 6 (webapp part 4)
Tensor Programming
Go tutorial part 7 (web app part 5)
Tensor Programming
Go tutorial part 8 (Web app part 6)
Tensor Programming
Go tutorial Part 9 (web tutorial part 7)
Tensor Programming
Go tutorial Part 10 (web app part 8)
Tensor Programming
Go tutorial Part 11 (Web app Part 9)
Tensor Programming
Go Tutorial Part 12 (Web app Part 10)
Tensor Programming
Go Tutorial Part 13 (Web app Part 11)
Tensor Programming
Looking at Elm 0.18
Tensor Programming
Go tutorial Part 14 (Web tutorial part 12)
Tensor Programming
Go tutorial Part 15 (Web tutorial part 13)
Tensor Programming
Go tutorial part 16 (web app part 14)
Tensor Programming
Elm Tutorial Part 7 (SPA part 1)
Tensor Programming
Elm Tutorial Part 8 (SPA Part 2)
Tensor Programming
Electron Elm Tutorial
Tensor Programming
Go tutorial part 17 (web app part 15)
Tensor Programming
Up and Coming Programming Languages and Technologies for 2017
Tensor Programming
elixir tutorial part 1
Tensor Programming
elixir tutorial part 2
Tensor Programming
Elixir tutorial Part 3 (GenServer and Supervisor)
Tensor Programming
Elixir Tutorial Part 4 (GenStage)
Tensor Programming
Elixir Tutorial Part 5 (Plug and Cowboy)
Tensor Programming
Phoenix Framework Tutorial Part 1 (elixir part 6)
Tensor Programming
Phoenix Framework Tutorial Part 2 (elixir part 7)
Tensor Programming
Phoenix Framework Tutorial Part 3 (elixir part 8)
Tensor Programming
A Intro to Clojure and Clojure Syntax
Tensor Programming
An Update about the channel
Tensor Programming
Intro to Rustlang (Setup and Primitives)
Tensor Programming
Intro to Rustlang (Strings, Tuples, Arrays, Slices and Pretty Printing)
Tensor Programming
Intro to Rustlang (Ownership and Borrowing)
Tensor Programming
Intro to Rustlang (Structs, Methods, Functions, Related Functions and the Display/Debug Traits)
Tensor Programming
Intro to Rustlang (Control Flow, Conditionals and Pattern Matching)
Tensor Programming
Intro to RustLang (Enums and Options)
Tensor Programming
Intro to Rustlang (Vectors, HashMaps, Casting, If-Let, While-Let, and the Result Enum)
Tensor Programming
Rustlang Project: Snake Game
Tensor Programming
Intro to Rustlang (Traits and Generic Types)
Tensor Programming
Intro to Rust-lang (Closures, the Box Pointer and Iterators)
Tensor Programming
Intro to Rust-lang (Modules and Lifetimes)
Tensor Programming
Intro to Rust-lang (Macros and Metaprogramming)
Tensor Programming
Intro to Rust-lang (Error Handling)
Tensor Programming
Intro to Rust-lang (Concurrency, Threads, Channels, Mutex and Arc)
Tensor Programming
Intro to Rust-lang (Tests, Attributes, Configuration and Conditional compilation)
Tensor Programming
Rustlang Project: Port Sniffer CLI
Tensor Programming
Rustlang Project: Chat Application
Tensor Programming
Rustlang Project: CLI Toy Blockchain
Tensor Programming
Intro to Rust-lang (Setting up a Development Environment)
Tensor Programming
Intro to Rust-lang (Building a Web API with Iron)
Tensor Programming
More on: Tool Use & Function Calling
View skill →Related Reads
📰
📰
📰
📰
The Silent Killer in Your Node.js APIs: Mass Assignment & How to Catch It Before Production
Medium · Programming
C# Async/Await Made Simple
Dev.to · Lou Creemers
The Backend Shortcut That Quietly Created Future Bugs
Medium · Programming
Java 21 void main() Explained: Where Did public static Go?
Medium · Programming
🎓
Tutor Explanation
DeepCamp AI