How can I call the rest api in django template.I want to design the microservices and just got thinking about calling a api in the front end.How could I achieve this.
Usually when I work in monolithic I directly call it from the database in the html but not case in microservices part.
CodePudding user response:
You need to separate your core logic so that you can call from your view the same logic you call from your API. To illustrate this an example,
models.py
class MyModel(db.Model):
attr_1 = ...
attr_2 = ...
def add_x_y(self, x, y):
return x y
Since your logic lives in the model which is the base of MVT structure, then you can use the defined logic anywhere you like. for example
api/views.py
def some_api_function():
x = 1
y = 3
result = {'result': MyModel.add_x_y(x,y)}
return json_response(result)
views.py
def some_template_function():
x = 1
y = 3
result = {'result': MyModel.add_x_y(x,y)}
return render_to_response(tempalate.html, {'result': result})
When you separate your logic to the bottom level of your application you can re-use in your api view, normal view and any other service functions.
Please disregard the syntax, this is just for example use.
CodePudding user response:
If you want to call Django API from your template then you can use AJAX. You can get a reference from the below code and add it to your HTML templete
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$.ajax({
type: 'GET',
dataType:"json",
url: 'https//yourendpoint/api/',
success: function (data, status, xhr) {
console.log('data: ', data);
//your logic
}
});
</script>
For more detail, you can check link. You can implement it using jquery or js.