Microservices with FastAPI – Full Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this course antonio papa will teach you how to create a microservices project using fast api react and redis antonio has a bunch of experience with a lot of different tech stacks in this video we will build a simple micro services app using python fast api the front end of this app will be in react and we will have two main micro services one is the inventory microservice and the other one is the payment microservice the inventory microservice will store products and the payment microservice will purchase those products the data will be stored in redis so we will use the redis json database which is a database similar to mongodb and we will send events uh from one microservice to another using redis streams so that is another functionality of redis i choose this architecture because we will not use any other database or rabbitmq or kafka we can use redis for all the needs that we have now let's see the app that we are going to build also make sure to check my channel scalable scripts where here i have a lot of projects and more microservices tutorials if you are interested now let's move to the app this is the app that we will build so it is very simple we can create products here which i will create one right now so i'll call it product i'll set up price and the quantity when i create we will have a product created with this id here and we have the option to delete this product so this is the first microservice and the other microservice is purchasing that product here we need to copy this id and when i paste this id we can see that your product price is 24 now you may be confused because the price here is 20 and here is 24. the reason that i increase the price here is uh think of it as another app that buys the products from this uh warehouse you can think of it and on top of that it will add 20 fee so it is 24 because it is 20 more so that's it when the user buys this product this app will gain profits and also the warehouse also i will buy a quantity of three i'll buy and here it says thank you for your order and if we refresh we won't see it immediately because it needs five seconds to update and now the quantity is 97 so the app will seem very easy but there is lot of asynchronous stuff going in the background and also redis stream events so we will see it now when we build the backend now let's create the projects go to fastapi.tagolo.com and here we will see the instructions to install fast api and uv corn after you install these two packages click tutorial first steps and i'll copy this code here now i will open my ide and i have two projects here so the first one is inventory where here we will store products and also their quantities and the payment project where we will purchase those products so these are the two microservices that we will work in the this tutorial we have a main.pi file which currently it is empty and the requirements.txt where we have all the packages that we need like fast api and redis om we will use redis as a database we will store our products there but also we will use redis as event sourcing software like rabbitmq and kafka so we will use it for multiple cases now let's go to main.pipe and i will paste the code that i just copied and to run this code now simply run the command which is showed here uvicorn main up reload so this is a command and it will run this app on port 8000 now let's test that end point and to test that endpoint i will use a tool called postman so this tool helps us to test api endpoints i will open the tool now it is free i will open a new tab and i will send a get request to http localhost port 8000 and if i send the request we will see hello world here so we created our first endpoint and now we want to create a database where we want to store products here for that i will use redis so go to redis.com and we need to try the redis cloud for free now i'm logged in to redis cloud and here we need to create a new subscription so there is a free plan available i'm located in europe and i will select this free plan 30 megabytes the subscription name i'll call it microservices and that's it we created this plan and now we need to create a new database i'll call it this database redis db and for the models i will select ready search and reduce json so already json is a database just like mongodb energy search adds some functionality to search that database like it is similar to elasticsearch and i will activate this database so the database was created successfully and as you can see here we have a public endpoint which we will use it uh right now and we need also the default user password which we will copy as well so that's it now in this invertory app i will connect with redis and we need to use this package called redis om i will copy it and i will install install it via pip so pip install redis om and let's uh import it here so from redis om we need to import get redis connection and with this we will connect to redis i'll do it here so red is uh it is equal to get redisconnection inside we need to pass the host which in our case is this public endpoint i will copy the public endpoint and i will paste it here but we don't need the port so i'll cut the port here because the port will be another variable so port here is equal to this value and then we need the password which it is this user password value here which i will copy and i'll paste it here so this is my password don't use my credentials because i will remove this connection once this tutorial is over so you have to create your own credentials and then the code responses it is equal to true so that should be it we created the connection via redis and now we want to create a model that will be converted to a table in the redis database so for that i'll create a class here product and from redis om we need to import also hash model and this product will extend from hash model and let's add all the values that the product has so the product has a name which should be a string then it has a price which it is an integer and a quantity which it is an integer actually i will change the price i will make it a float better and that's it so this product will have just a name a price and this quantity is the quantity available i will keep it short so it could be quantity available but i will just keep it quantity so i will keep it short and to make this product connect with our redis database we need to add another class here meta and inside we'll say that the database will be equal to redis and that should be it so with this uh every time we query and we create products they will it will be stored in our redis connection and let's do that i will remove this end point here and i'll create a function products or all doesn't matter uh let's return an empty list for the moment this will be a get request to slash products and that's it so let's test this endpoint on postman if we send a get request to localhost port 8000 slash products so we have an error is your corn running it seems it's not and we can see an empty array right now so it is uh this simple now we need to return the products from redis and to do that we have to return products that all underscore primary keys so this is the function that will return all the products i will save it and for the moment we don't have any but this will return only the primary keys and this will not return the products for the moment we cannot see it but we need to create another endpoint to create a product to see what this returns we will do that but first we need to create also a middleware here so we need to add a middleware called course let's import it here so from fast api middleware course we need to import the course middleware and we need to add it here so what is course so course is a problem that when we run our front end it will run on port 3000 and the uv cord here is running on port 8000 so it's not running for the moment i will fix that but there are different ports and the browser will prevent that in order to prevent that problem we need to add the middleware also we need to specify the allowed origins so allow origins here will be http localhost for 3000 so this is our frontend we need to allow the frontend to request our apis we need the the methods so i'll copy this paste it here so this is allow methods i'll put the star here so all the methods and we need to allow headers so that should be it this won't change anything until now so the app will work the same but the changes will be reflected on the front end so we won't have problems in the front end if we add this middleware and now let's create the other end point where we create products so i'll create a function here create and uh fast api makes it really simple for us first i will add here the method so up post method to slash products and to create a product we need to pass in the parameters here the product itself as a product and we need to return product save it is this simple so the parameters that we need to send in the request are the name of the price and the quantity and the rest will be taken care from fast api so let's see if this works i'll copy this open a new tab i'll send a post request and in the body i'll send a json i'll send a name product i'll send the price 20 and a quantity available i'll say 100 so if we send this request we can see that we get a primary key a name the price and the quantity so the product was created successfully and if we try this request again we can see that we are returning a primary key but i don't want to return just a primary key i want to return all the objects and we need to create another function for me for it so i'll create a function here format and in this function we need to pass a primary key as a string so we will pass the all the primary keys to this function we need to get the product which is equal to product that get with this primary key so this will query that product from the database and we want to return the response of this so i want to display the primary key i will display directly the id which is product dot primary key we need the name which is product dot name we need the price which is product that price and we need the quantity which is product that quantity and for this function now we need to return an array now that we'll do something here for primary key in product all primary keys and this something will be calling this format function that we just created and i will pass the primary key there so that's it uh with this change now so it seems uv corn stopped again we can see now the response is what i wanted so we have an array of products with the id name price and quantity so that's it we need also one last method which is deleting this product actually we need two so i'll add the first one so def get with a primary key as a string so this will get a single product from an id and this will be a get request get to products slash the primary key here and we will return product that get with the primary key let's see if uvicorn is running it is so if i copy this id and i will put it here we can see that we are returning not an array now but directly the object so this is working fine and now let's add the last one which is deleting this product so delete here and we need to pass again the primary key as a string i'll copy this part i'll paste it here and this is a delete method and we will get the product like this so product is equal to product get with this primary key and we will return product that delete if we try this method now this will be a delete request so we have a problem what is the problem now it seems that uh we need a primary key here so maybe i made a mistake we should do it like this then so now it should work so my bet there and now it is working not sure why it returns one but it means uh it probably means that it is successful now if we get all the products we don't have any so we created a simple crowd for the products and now let's move to the payment microservice let's go to the main.pi file and let's add all these parts and i'll paste it here so we still need the course middleware we need to create a fast api project and we need to connect to a database i'll copy this again and i'll paste it here a lot of comments here and i will say this should be a different database so the point of microservices is that each microservice needs their own database i will keep the same database because if we go to the redis cloud if we add a new subscription let me open it here not sure it is here we need to pay still i have 200 dollars in three credits but in this case it won't make a difference since it will be another database i will use the same database but keep in mind that this could be not a radius database but a mongodb or a mysql database so this is not a problem in what i'm trying to teach you and now let's create the class for this microservice what we need to create and it will be an order so this will extend from the hash model and what does the order table has as a column so it has a product id as a string so when we create an order we need to know which product id we are buying and that product id has a price which is a float and this microservice will buy that product with that price but it will also add a so think of it as you are getting items from a warehouse but you also need your own revenue so you add the fee on top of the price that you buy on that warehouse and also price plus fee it mean it needs a total here which is also a float the total price that the user pays the quantity is an integer so this is a quantity that the user buys and the status so this is important so the status is pending i will add a comment here so pending completed and refunded so we will handle all these cases in this tutorial pending is when we create this record in our database but the payment processor hasn't completed yet this status is when the payment processor approves our request and refunded is when an error happens which i will show you later when that error happens and how we will handle it so we need the meta here and we need to connect with the database which is redis so that's it we created also another model and here let's add the method so we need to create a function create this will be a post request to orders and we will pass a request here so we need to import a request i will import it directly so i have a lot of imports there from starlet requests import request so this is what we want and then what do we want to do right now first we know that fast api supports asynchronous requests and asynchronous functions and i will get the body of that request by awaiting requests that json so this is one way of getting all the data in the request but i will show you later a better way of handling asynchronous tasks but for the moment let's get just the body and here we will send just an id and a quantity and from that id we want to get the products and all the information regarding that product so now comes the first problem of microservices how do we get that information that information we will get it if we request directly the inverter in microservice so we request this endpoint here and we retrieve that information and to do that we need to install another package pip install requests so it is installed and we need to import it here so import requests so let's send now a get request to the inventory microservice so the request will be equal to requests we'll send a get request to http localhost port 8000 slash products slash percentage s so this is a string so we need to pass the id of the product which we get it from the body and that will be converted like this with a percentage body id so this value will be converted to this value and in the end let's see what this returns i will return request dot json and let's see what this returns so first we don't have any products so send again the request here to create another product which we created so we can see it we have a product in the other microservice we need also to run this microservice but we won't use the command so i'll copy it here directly i'll copy it i'll run it here i'll paste it here but here we need also to change the port because the port 8000 is already occupied so add port here 8001 and this will run this up on port 8001 and now let's send this request so we'll send a request to http localhost port 8001 this time slash orders we'll send a post request and we will send as we said an id which in our case it is this id here that we just created and the quantity and we will buy two products let's say let's send this request and indeed we got that product so we are not querying this product in this microservice instead we are sending an http request to the other microservice and we are retrieving the products from here so this is one way of microservices communicating with each other and now we successfully got the product i will cut this the product will be equal to request.json here and we want to create this order so to create that order the order will be equal to an order and let's add all the values that we need like the product id will be equal to body id we need the price which is equal to this product here because we don't send it in the request so this is product price the fee this fee will be 20 of the products price so this will be 0.2 times the product price and the total will be the price plus the fee total here so this means is 1.2 times the product price so that's it so this is a price the fee is a total we need also the quantity which we get it from the request body and that's it we need also the status which the first case is pending in the end we will save it so order dot save so we successfully created an order here in the end we will return the order and the only problem is this status pending which means that we are waiting for a payment processor to finish in order to change this status and for that i'll create here another function i'll call it order completed we'll pass the order here as an order and what we want to do here is simply say that the order that [Music] status is equal to completed for the moment we will do it like this order dot save and we will call it here order completed with an order so you may ask yourself why i did it this way so we will make make this more complicated so don't worry first let's test if this is working i will send an order here let's send this request and indeed it works so we see we have a primary key here so a new primary key which means it's a primary key of the order this has this product id this has this price fee total quantity and in the end it is completed so this means that it went also to this function change it to completed and it is working fine but let's say that the payment processor needs five seconds to confirm our order so i will add here time sleep for 5 seconds usually the payment processor needs their time to confirm and so this is a good estimation what happens if we add this delay here if we send another request right now we will wait for five seconds till we get the response but this should not be the case because we want to return the pro the order with the status pending and later on when it is completed we want to change the status how can we do that so fast api supports asynchronous requests like we did here and for that we need to create a background task so we need to import i will import it here from fast api background import background tasks i will also cut time here and add it here so we have more space and let's uh use now the background task and when we call the function here i will add background tasks is a type of background tasks i have also a typo here and we have this variable right now and the way that we will use the background tasks is like this so we will use background tasks other tasks and our task will be this function here so i'll cut this name and i'll put it here if this function does not have parameters the background task will be simply like this but this has an order as a parameter so all the other parameters should be passed after the name of the function and that should be it with this fast api will execute this function on the background and let's see it [Music] before we test it i will add also another endpoint here i'll add it here on top this will be a get request because we need to see if the order has changed so orders with the primary key here def get primary key as a string and we will return order get with that primary theme so we created this just to test it and now let's test it on the postman now let's send this request the status is pending as we can see but now let's open another tab and let's paste this id now the status it is completed so i used five seconds to request this so if i do it uh faster this time so let's send this this request i'll copy the primary key paste it here is still pending let's wait two more seconds and now it is completed so as you can see this is indeed executing in the background this is how we execute functions in the background in fast api and now let's go to the other problem which it is that every time we buy a product the the quantity should be subtracted from the inverter so the quantity here is 100 and we should decrease this value how do we do that we will do this by sending events through redis streams so what are ready streams ready stream is a messaging event pass just like rabbit mq and kafka so you can read the documentation here how it works so it has a lot of functionalities i will use just the basic ones and it will simply let us communicate via different microservices by sending events and they won't know about each other how do we do it we will do it like this the first step is sending the event to the uh ready streams and we already have a redis connection here and when the order is completed we change the status of the order and we will send an event to redis and the command is x add so this is a command in reddit streams we need a key and the key will be order completed and we need a value which in our case i will send directly the order as it is so this should be a dictionary as well but fast api makes it uh easier for us so i will send directly the order as a dictionary like this so the order is sent and the other parameter is a star so this last parameter is the id of this event we can put it ourselves as we want but i want to have an auto generated id so if you want uh now to generate id just put a star here and that should be it so this is the event that we will send and in our inventory here we need to create a consumer so this will wait for these events for that i will create a new python file i'll call it consumer here and in this file first we need to add the imports so from the main app we need to import the redis connection import redis and we will import the product and what do we want to add here first i'll create a variable key which is equal to order completed and we need also a group which i'll call this inventory group and let's create a redis consumer group so i'll use a try accept here and we will try to create x group create with the key and the group so we will create a consumer group with this key and this name if it fails then we will print group already exists so we need a consumer group in order to consume and now we need to consume and to do that we need to add the infinite loop here so while true i'll use a try accept here as well for the exception i want to print the exception so exception as e here and we will print the exception as a string so like this and inside the try we will consume and the way to consume is like this we'll get the results redis x read group and the parameters here first we need the group second we need the key so it is the opposite as creating the group so we need the key here and the group but here we need the group and the key we need also two more parameters uh the second one is a dictionary that the key will be our key so it is order completed and we need to add this symbol which means that we want to get all the events here and the second parameter the the last one is none and this is how we consume i will print the results here so to see what is the type of content that we are reading and we need to add a timer so while we have an infinite loop here i'll import time here and we will wait sleep for one second so every second we will consume messages and that should be it so now what is left is to run this consumer i will open a new tab and run python consumer dot pi and as you can see it is running uh nostalgia key order completed so it is running and this is waiting for the event in the payment part which we will do it right now we will send an event when we create an order let's send this event and we should be able to see something here in five seconds because we need to wait that much and uh not sure if it is working i will interrupt it and run it again so we see an empty array actually [Music] so the message is different so this means that the key was created let's send another event then we should probably wait uh five seconds till we get the response and indeed we got so i will stop it here and as you can see we got an asynchronous event from redis streams so this is the order itself this is a key order completed this is the key of the ready streams event and this is the order that we just created and with this information we will decrease the quantity by 2 in the inventory microservice so let's do that and the way that i will do it right now is uh first i'll make the condition if results is not an empty array i will not print more empty arrays here and then for each result in results so we can have multiple events because they are returned as a list and the object itself so this is what we want we don't need the key we don't need the event id here we just need this object and that object will be equal to result we need the second value of that list then the first one then the second one so this is the way how we get it and then we will get the product which will be equal to product get with the object product underscore id so this is the id of the product that we use in the order and if the product is set or i will print it directly so i will do it like this so print product then i will decrease the quantity so product that quantity is equal to product that quantity again minus this object quantity and i will convert this to an integer because it will throw an error if we don't do it and we will save it so product that save and that should be it so we get the event through ready streams we loop the results we get the order from that order we get the product we decrease the quantity and we save that product let's see if this works i will save it and i will run it again and this time we get the group already exist but we are not getting empty arrays because i added the if condition here and we are waiting to send this event i send this event so we need to wait five seconds and as we can see we got a product print here so it got the product that we want with the quantity of 100 and now if we query again all the products we can see that the quantity now is 98 so we decreased the quantity asynchronously so this is how it works we make a payment for a product and we send events to ready streams to that microservice this microservice doesn't know what happens in the other microservice it just get events to decrease the quantity of the products so that's it our app it seems that is uh almost completed uh if you look at this app uh with the functionalities it seems that everything is handled but there is a small a rare problem that may happen which is in between this time period of five seconds so in between this time period we may have a problem that if we don't handle it we will charge customers for nothing basically and that is the time when for example i will copy this endpoint i will create a new one and this will be delete now we want to delete this product with this id before i delete the id uh i will create an order for that product and if everything is successful within five seconds i will delete that product so let's do it now let's send the request for the orders it is pending let's delete the product if we wait i will copy the id of this order this means that the order was successful because now the status is completed the customer was charged the order was completed but the product was removed uh one or two seconds after the order was completed this means that the customer was charged and the product does not exist how do we handle this case so these are rare problems but if you are building event driven systems you need to handle these problems in this case in our app what we will do is we will refund our customers so we will change the status of the order to refund it and we will send to the email to the customers that an error happens and your payment has been refunded and to do that we need to send an event here to the other microservice so we will send an event here to the inventory and now we will send it from the inventory back and we will do it the same so i'll copy this code and i will make an if condition here for the product so i'll do it like this if the product is set then we will decrease the quantity of that product else if the product does not exist so else here we will call redis we need to add the so we need to send another event which i'll call it refund order and the order in our case is this object here which is already a dictionary so i'll do it like this so this is the event in this part this microservice has totally finished now let's add the consumer which i will copy again the consumer here and i'll paste it here to this microservice of course we need to make changes here we need to get the order this is not order completed this is refund order the group is a payment group so we need to create the group here and we need to make an infinite loop here we get the order actually the order will be here or the object i'll do it like this object then this is the order itself we will get the order from that primary key order here and we will change the status of the order status to refunded and we will save the order and that should be it so this microservice now needs uh to call the consumer so python consumer.pi it is running let's do the same for this other microservice let's run the consumer here as well and let's uh simulate that problem now so first we will create a product which was created we can see this is a product i'll copy the id i'll paste it here just to be ready to be deleted when we create an order and let's create an order now i'll change the id send this and delete immediately the product so i think the problem now is that the first time the key won't be created that's why i'm getting this message let me stop it now and run it again so i will try to do it like this then so in the payment uh when we get the order i'll copy this and i'll paste it here i'll just say send an empty list here just to create the key and if i get this order so let's send a get request so we have a problem it seems must be an empty dictionary so then i will get the order and i'll pass the order to dictionary here and i'll return the order i'll run it again and i will stop this now it is working and if i run the consumer i won't have this problem that the consumer is was not created so as we see it is empty here and now we can simulate that the product deletion again so let's create a product it is appearing here i'll copy the id be ready to be deleted and let's create another order which we have a mistake so what is the mistake right now so the mistake is because i forgot to change the id here and now let's send the request it is spending delete the product and now let's see the consumer do we print something here i don't think so so we don't print anything but for the order that we just created let's see it here and this time i won't send a random event here so i'll remove this part i'll just return the order as it was before i'll save it and we are still getting completed so i figured out what is the reason the reason is this if condition here is not working because when it doesn't find the product currently it throws an error so i have to do a try accept here also and we have multiple try catch statements here but let's hope if this works then i will immediately create a product now i will save this delete request to do it immediately now when we create an order and let's delete it immediately and let's see if we get a deletion here so actually here we don't have any print statements because i removed it so i added a print statement here on top and as you can see i retried again with a new order and we actually get an event and uh for this order that i created i will copy this paste it here let's see if the status now it is refunded so that's it how it works this is a rare case but anyway we need to handle also the rare cases in an event-driven architecture so that's it this were the microservices that i wanted to build now let's build the front end so now it's time to create the front end and i'm in a in the folder now with where i have the inventory and the payment microservice and now i will use the command mpx create react up i'll call it front end or i'll call it inventory front-end and let's wait till it's completed right now so it is completed i open it with my ide so this is the front end now and i have the back ends running in other tabs but we won't change those let's work with the front end i will remove the test file and this up css we need to adjust our app.js and our index.css so for the app.js i will change the html here i'll go to boots gets bootstrap.com click get started and let's copy the bootstrap css i'll paste it here on the index.html and for the html here go to examples and go to dashboard here let's view the page source and i'll copy the code from the container fluid or from the header i guess until the end and i will replace this html here with the one that i just copied but we need to make a lot of changes here for example this table we need just a table row we don't need all the other table rows so from the end until here i will remove everything so we need just one table row we don't need the section title neither the canvas i will remove also this div here we don't need it for the menu we have two kinds of menu so this ul here i will remove it along with this h6 here and we need this ul but we need only one list item so i will keep the dashboard and and for the header we don't need this button this input we don't need it and what is left here so something is wrong i guess or not so let me format it i'll save it run npm start and let's see how it looks like so if we open it on the browser it will look like this still we need some css because this dashboard has this dashboard css here so in the in the paste source click dashboard css select all the css there and add it to the index css here i'll save it if we see now our react app it will look better now let's make other changes for example the dashboard here i'll rename it to products i'll remove this spawn and it will look like this and here we need to render our products but i will create components i want to do it directly so first i will create a new directory components and inside i will create a products component so this will be a javascript file products and i will export a constant here products this will be equal to a function that we will return here an html and that html will be this table here so i will cut the code and i will return it here so this is the products component for the moment and for the other html that is left i will create another component i'll call it wrapper because we will reuse this wrapper to another component so that's why i split that html into two different components so i'll export a constant wrapper that this will contain all this html in the wrapper i will return the html so i will remove this class name up and also the div in the beginning so i'll keep it like this and here we want to display our products.js we can do it like this so i'll add here the props and inside our main div here i'll add props that children and this wrapper will be used in our products.js because we will wrap this html with the wrapper i'll cut it i'll put it here and that's it so this is our products is rapid is wrapped with this wrapper component and here we can simply return our products like this and if we save if we go back nothing will change but our code will look much better now let's add the the router so we need to install a package npm install react router dom so this will let us map the routes so we will have more components we don't we won't have just the products here and first we need to import from react router dom we need to import browser router routes and route so now this will change this return statement to this first i will use the browser router inside this will have the routes and for all the routes we need the specific routes so we have only one route for the moment which is the path is just the main path and the element is our products components like this so if we go to the main path we will render our products component i will save this and nothing will change again now we are finished with app.js every time we create a new component we need to add a new route here so for the moment let's make the products work so here we are displaying just an html but this should be the list of the products and to do that we have to create a variable here products set products will be equal to use state and the default state will be an empty array and to get the products we have to use here use effect and we need to make a request to the backend let's add first the dependencies which should be an empty array this means that we will use use effect only once if we add the empty array here and inside i will call an asynchronous function like this because usefx does not support adding a synchronous function here on top it will throw an error that's why we need to create this and i created an asynchronous function because now we will send an asynchronous request so we'll get a response is equal to await fetch http localhost so http localhost port 8000 slash products and the content it will be equal to a weight response json so this is the content so this content will be our products and we will call here set products to the content and that should be it we added the products here and we should loop them here so let's loop the products so products map product we will return this html where the key we need to add the key for when we make for loops in react so the key will be the product dot id and the values will be actually let's add them first here on top so the first value is id which is correct then we need the name the price the quantity and the actions and when we loop the product we will display the product dot id here i'll copy paste it here this is name this is a price this is the quantity and for the actions this will be just an anchor link with an href to hashtag we need to add these class names which are button button small button outline secondary and we need to close it and we will call delete here and that should be it so let's see it uh here we can see that we are showing here a table if we inspect we're calling the products but momentarily we don't have any products so we need to create the component to create those products and i'll create it now so this will be the products create component before we add any code i will go to the products and i will add a button here on top and that will be this html with the link so this will look like this so we have another button here that will navigate to the create page which will be this products create and we are using a link here which we import from react router dom so we can navigate to that page also that page should be added on our routes here but first we need to export the constant product create and we need to return some html so i'll return the div here so we can add it here so the path now will be create and the element is product create so we added the second route now let's add the html here so we don't need this div we need to add here a form i will add the class for the form so class name here margin top should be three and for all the inputs i will use this format here so we need this class name and we need an input here so the first input will be the name so for the placeholder i will put here name and inside the label i'll put name again and i'll do the same for the other inputs which are the price and the last one is the quantity we need also a button so i preset the button also with this classes and with submit inside and this form will look so let's let me click there we will go there and we can see only the form here which is not correct because i forgot to wrap it with the wrapper i'll add here the wrapper and i will close it and if i save it we can see the form now we have a name a price and a quantity for the price and quantity i will make the type here to a number same for the quantity and this inputs now will have this arrows up and down now let's make this form work so for each input now i'll create a variable so we need a name set name is equal to use state empty and same for the other inputs which are the price set price and this is the quantity set quantity and now for all the inputs when we make a change so on change here we will have an event that will set the name to event.target.value we will do the same for all the other inputs so this is set price and this is set quantity and we got all the values now it's time to submit the form so i will create a function here submit and when we submit here on submit we will call that submit function this will have an event and what do we want to do here is we need to prevent default because if we don't add this line when we submit here it will refresh the page and that is not what we want so that's it now what is left is to send the request to the backend so we will make this asynchronous and we will await here fetch will send an http request localhost port 8000 slash products and this time the the method will be a post request we need to add the headers which are content type will be application json and we need to send the information that we need which are these three variables here and we'll send that in the body which should be a string so we need to use the function json stringify and the object that we need to send is the name will have the value of name but since they have the same key and the value i can use it directly like this so i added the name the price and the quantity and that's it this is the request that we want in order to create the product and when we are finished so if this is successful i want to navigate back to the products and we will use the function navigate is equal to use navigate so y is not imported so we need to import use navigate from react router dom and when this request completes successfully we will await navigate i'll pass here minus one which means that go to the previous page and with this let's try to create our first product product the price will be 20 and the quantity will be 100 submit we redirected back we created the product we have an id here the name the price and the quantity so everything works fine we need also to add the functionality to delete a product so let's add it now so we have this incorrectly which does nothing for the moment let's create a delete function i'll call it deal because delete is a keyword and this function will accept this will be asynchronous will accept an id and if we scroll down i will add here on click and when we get an event we will call delete with the product id inside so we have the product id let's go back and the first thing that we need to do once we delete something is to make a confirmation window so window confirm are you sure to delete this record so every time you delete something make sure to ask them the confirmation window and if they type ok we will await fetch [Music] http localhost port 8000 slash products slash the id that we just passed here and if that is successful so we need also to add the method here which is delete if that is successful then from the products here we have to remove that product and we will do it like this so set products to products but we have to filter we have to filter all the products that the product that id is different than this id that we just removed and that's it so let's test it now are you sure you want to delete this record okay and it is removed if i refresh we won't see that record so we need to create another product with a new price a new quantity and it will it works successfully now is time to add the other front end for the other microservice so again this should be another app so we need to create another react app in order to add the micro the front end for the payment microservice but i will still do it in this front end because it won't make a difference i already explained the concepts that i wanted to teach you so adding a new react app won't add anything new to this project so that's it with this i will create a new component here and i will call it orders and let's export this constant orders and for the html i will paste it it directly so this is the html that i want to show there so to see what it looks like we need to add it also to the routes so the path here will be orders and the element will be orders so don't forget to import that also and if we open the browser i'll open a new tab here i'll close this other tabs and this is slash orders and this is the checkout form so think of it as a new microservice it is the same app but it won't make a difference if we create a new react app so here we create the products and here we buy them and the way that we want to buy them is we will copy here the id of the product and we will pass the quantity here so let's go to the orders now first let's make for each input let's make a variable here so i'll add the id set id this will be equal to use state empty by default and we need also the quantity and this is set quantity and when we change those values we change them here so on change we will set the id here event.target.value and we will do the same for the quantity set quantity so we got those values and now we need to submit the form so let's create a function here submit let's add it here on submit we will call a submit function this will be an asynchronous function this will get the event and we need to prevent default and here we want to send a request to the backend so wait fetch localhost port 8000 not 8 000 sorry 8001 in this case because we are sending a request to the payment microservice so this is 8001 slash orders this should be a post request and we need to add the headers i'll copy them from here so the headers and the body and if i go here i'll paste it here so the headers are the same and the body is sending this information but we don't need the name and the price we need to send just an id and the quantity and if everything is set then i will display a message here so i'll cut this i'll create a variable message message set message is equal to use state default message is by your favorite products and when it's completed we'll set the message to thank you for your order and i will show the message here and that should be it so this will look like this let's uh try to purchase this product the quantity is three let's buy the product and as we can see thank you for your order and if we refresh this we will see 117 so we should wait five seconds till this value changes and everything is working as it should i will adjust a small change so our app is perfectly working i will add the use effect here that this use effect will depend on the id so every time we change the id here the input we want to we want to display another message here so the product price is this much so i'll first make an asynchronous function here and i will use a try catch because we may have a problem in in case that we have an error i'll set the message to uh the same message that was all the time so be buy your favorite product and if the id is set then we will send a message so request sorry wait fetch to http localhost port 8000 slash products so i'll change the quotes here because we need to use these because i will pass the id of the product here we'll get the content which is equal to a weight response json and we will set the message to your product price is in dollars and i'll put here the value content dot price and let's see if this is working fine so i will use double dollar signs because we need an actual dollar sign here so if i refresh i will copy this value paste it here and as you can see your product price is 25 dollars so i will make a small change also now so the price will be equal to we need to parse it to float so parts float times 1.2 since we are the uh 20 in this microservice so the actual price will be more than that and as you can see now your product price is 30. so this is a inventory we are selling the price we are selling the product with the price of 25 and in another app that is using those products we add the fee of 5 dollars so this is how microservices work and thank you for watching this video don't forget to like share and subscribe thank you
Info
Channel: freeCodeCamp.org
Views: 226,128
Rating: undefined out of 5
Keywords:
Id: Cy9fAvsXGZA
Channel Id: undefined
Length: 88min 53sec (5333 seconds)
Published: Thu Mar 24 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.