0% found this document useful (0 votes)
4 views5 pages

Comm Between 2 Apps

The document outlines a class focused on creating two FastAPI applications, App A (Student Manager) and App B (External Reporter), which communicate via HTTP requests. App B uses the httpx library to send POST and GET requests to App A, allowing for the management of student data. The document also discusses the importance of asynchronous programming in handling these requests efficiently and mentions potential classwork on implementing PUT and DELETE methods in App B.

Uploaded by

ANONYMOUS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views5 pages

Comm Between 2 Apps

The document outlines a class focused on creating two FastAPI applications, App A (Student Manager) and App B (External Reporter), which communicate via HTTP requests. App B uses the httpx library to send POST and GET requests to App A, allowing for the management of student data. The document also discusses the importance of asynchronous programming in handling these requests efficiently and mentions potential classwork on implementing PUT and DELETE methods in App B.

Uploaded by

ANONYMOUS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

In this class, we are going to have two API’s communicating with themselves.

Using
our example before, let’s think of a scenario like this:
App A = Student Manager
App B = External Reporter, which pulls or sends data to App A
In this case:
We are going to use the FastAPI app, we created last class as APP A, then we will
define APP B to communicate with APP A which is our student manager.
APP B will be another agent that will be used to send HTTP Request to APP A and
get responses.
What we need
• Python + FastAPI (we already have)
• Uvicorn (ASGI server to run FastAPI) (we already have)
• httpx (to make async HTTP requests between apps) (we will install using pip
install httpx)
• Two terminal windows (or run apps in separate Python scripts) (we will use
swagger here, but you guys can decide to use your terminal or Postman if
you wish)
Steps
Let’s put up our already existing code from last week in a python file and run it on
port 8000 or any port of our choice.
Now let’s create APP B, the app that will communicate with APP A. Let’s make APP B
to run on another port e.g port 8001.
How They Will Communicate
We will use httpx to send HTTP requests from APP B to APP A. (i.e. HTTP requests
from an external agent to the student manager)
These requests will be defined by the HTTP methods we earlier discussed.
Note, only code for App B is below, we will get App A’s code from the previous class
please.

Communication b/w 2 FastAPI apps Page 1 of 5


from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
import httpx

app = FastAPI()

# We're using thesame schema as the one from our last note
class Student(BaseModel):
name: str
department: Optional[str] = None
matric: int
level: str

# POST to create a new student in the student_manager app


@app.post("/send-student/")
async def send_student_to_manager(student: Student):
async with httpx.AsyncClient() as client:
response = await client.post("http://localhost:8000/students/",
json=student.dict())
return {"response_from_student_manager": response.json()}

# GET all students from student_manager app


@app.get("/get-students/")
async def get_all_students_from_manager():
async with httpx.AsyncClient() as client:
response = await client.get("http://localhost:8000/students/")
return {"students_from_student_manager": response.json()}

for this communication, we will use the httpx library which is a modern HTTP client
with async support. It allows sending of HTTP requests asynchronously to other
APIs. It is important because it enables your FastAPI app to talk to another app
using HTTP.

OUR ENDPOINTS
a. POST Endpoint
@app.post("/send-student/")
Here, we defined a POST route at /send-student. This is the route the client will call
to send a new student to the student_manager app.
Next is our async function
async def send_student_to_manager(student: Student):

Communication b/w 2 FastAPI apps Page 2 of 5


This our function handles the logic for the POST request. Student:Student means
FastAPI will parse and validate the request body against the Student schema.
Next, we define our HTTP client using
async with httpx.AsyncClient() as client:
so we create an asynchronous HTTP client using httpx. This will enable non-blocking
HTTP calls to another API
the httpx.AsyncClient() is used to create a new instance of the http client object
next, we define where to get our response from, using
response = await client.post("http://localhost:8000/students/",
json=student.model_dump())
this will send a POST request to the student_manager app at /students/, then it will
send the student data as JSON using student.model_dump()
Next, we return the response
return {"response_from_student_manager": response.json()}
we return the JSON response received from the student_manager app. This will
allow the client to see what the student_manager API returned.

b. The GET Endpoint


@app.get("/get-students/")
Declaring a GET route at /get-students/ . This will be used to fetch all students
from the student_manager app as we already know.
Next, we defined an async function, just like we did for the POST endpoint
async def get_all_students_from_manager():
This async function will define the logic for handling the GET requests at /get-
students/
Next, we create an asynchronous HTTP client as we did before.
async with httpx.AsyncClient() as client:
Next, we define where to get our response from, using
response = await client.get("http://localhost:8000/students/")
as we did before, this will send a GET request to the student_manager app to fetch
all students
next, we return the response, using

Communication b/w 2 FastAPI apps Page 3 of 5


return {"students_from_student_manager": response.json()}
This will return the list of students retrieved from the student_manager app as a
JSON response.
Question
Can we update our second FASTAPI app to handle a PUT and DELETE
methods?
Classwork
So, in our first classwork today, we will define PUT and DELETE methods in
our second APP. Take a clue from the endpoints we defined last week and
what we just did.

SomeThings to consider
Httpx: Is a third-party python library used to make HTTP requests. httpx support
async operations, it allows our app to call other APIs.
async with httpx.AsyncClient() as client: Tells python to do the task
asynchronously
httpx.AsyncClient(): Is a tool used to send HTTP requests in async mode. It helps
FastAPI act like a client and talk to other apps.
as client: This means we’re naming this HTTP client as client so we can use it to
call client.get(), client.post() etc.
response = await client.get("http://localhost:8000/students/"): Means,
FastAPI is sending a GET request to the /students/endpoint running on another app
on our device and wait for the response.
note:
• await – will wait for the server response before moving on.
• client.get() will sends an HTTP GET request to fetch data.
• response = Stores the server’s response (status, data, etc.) so you can use
it.
async and await: Are part of asynchronous programming, which is used to write
code that can pause and wait for something (like a network call) without blocking
the entire program. It makes the program to do things while waiting for something
to finish.

Communication b/w 2 FastAPI apps Page 4 of 5


async def: Will define an Asynchronous Function
When you use async def, you're telling Python:
"This function might pause and do something asynchronously (non-blocking)."
@app.post("/send-student/")
async def send_student_to_manager(student: Student):
This function is now asynchronous, which means you can use await inside it.
await: Will tell Python to “Pause and Wait”
When you write await, you’re telling Python:
"Wait here for this task to finish, but don’t block the whole app."
response = await client.post("http://localhost:8000/students/", json=student.dict())
This line sends an HTTP POST request, and rather than freezing the whole app while
it waits for a response, Python will let other operations run and resume this function
once the response comes back.

Why async/await in our example


Our FastAPI app uses HTTP requests (via httpx.AsyncClient) to talk to another app.
This network calls take time (milliseconds to seconds) and this can slow down the
app if done synchronously with (requests.post for example)
Using async/await will ensure that our FastAPI app can handle multiple requests at
the same time and it will also stay responsive instead of waiting for each HTTP
request to finish.
Homework
tell me about the requests library in FastAPI and why httpx is more
suitable than the request library.

Communication b/w 2 FastAPI apps Page 5 of 5

You might also like