Skip to content
GitLab
  • Menu
Projects Groups Snippets
  • /
  • Help
    • Help
    • Support
    • Community forum
    • Submit feedback
  • Sign in / Register
  • F FastAPI
  • Project information
    • Project information
    • Activity
    • Labels
    • Members
  • Repository
    • Repository
    • Files
    • Commits
    • Branches
    • Tags
    • Contributors
    • Graph
    • Compare
    • Locked Files
  • Issues 0
    • Issues 0
    • List
    • Boards
    • Service Desk
    • Milestones
    • Iterations
  • Deployments
    • Deployments
    • Releases
  • Packages & Registries
    • Packages & Registries
    • Package Registry
    • Container Registry
    • Infrastructure Registry
  • Wiki
    • Wiki
  • Activity
  • Graph
  • Create a new issue
  • Commits
  • Issue Boards
Collapse sidebar
  • Sitemule
  • Public
  • workshops
  • open source on IBM i
  • FastAPI
  • Wiki
  • Part 2b. Organise my first service

Part 2b. Organise my first service · Changes

Page history
Update Part 2b. Organise my first service authored Oct 30, 2021 by Jens Melgard Churchill's avatar Jens Melgard Churchill
Hide whitespace changes
Inline Side-by-side
Part-2b.-Organise-my-first-service.md
View page @ d8af6c7d
......@@ -10,7 +10,7 @@ Remove the function `read_root()` and its body, the `return {"Hello": "World"}`
```python
@app.get("/")
async def index():
def index():
content: str = """
<html>
<body>
......@@ -34,4 +34,89 @@ Success !
## Since we care about maintainability, lets do a bit of housework
First, API's can grow large containing many endpoints, having them all in one file is silly. A bit of refactoring can go a long way, but
\ No newline at end of file
API's can grow large, containing many endpoints and resources and having them all in one file is silly.
A bit of refactoring can go a long way, but first we'll add a new dependency.
Exit vim, by typing `:q`
Now in the shell, type `pip install fastapi-chameleon aiofiles`
Chameleon is a very nice templating framework, that strives to create templates that conform to xhtml specs.
And the _fastapi-chameleon_ package integrates it with FastAPI.
Since we'll also be wanting to serve static content, such as images and css, we also installed _aiofiles_, or asynchronous-input-output-files, in short, it allows us to serve static content asynchronously, for added speed.
And just a reminder, all these things we are installing and building on top of, are all opensource.
But their license therms can differ.
While where out here in the shell, lets create a couple of folders...
* `mkdir templates`
* `mkdir static`
And create some files to put in them
* `touch templates/index.html`
* `touch static/index.css`
* `touch api_router.py`
Go back into the editor, run `vim main.py`
We just changed the index function, to return HTML.
But no one wants to inline HTML into code, and since we just installed a templating engine, we should use it.
Now refactoring code using an unfamiliar editor is a daunting task, so depending on how long it takes, we might have to skip ahead after this. Keep calm and don't panic, it'll be fine.
Lets take a look at the final result for _main.py_
```python
# Move all imports to top of file, and group+sort them for good measure
from fastapi import FastAPI
from fastapi import Request
from fastapi_chameleon import global_init, template
from starlette.staticfiles import StaticFiles
from time import time
# Declare the main:app entrypoint
app = FastAPI()
# Instruct the templating system, where it should look for template files.
global_init('templates')
# And where FastAPI can locate static resources.
app.mount('/static', StaticFiles(directory='static'), name='static')
# Our middleware stays the same
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time()
response = await call_next(request)
process_time = time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
# But our index endpoint is changed to use a template file,
# and is once again back to returning data as json.
@app.get("/")
@template(template_file='index.html')
async def index():
return {
"title": "FastAPI on IBM i",
"message": "Welcome travelar"
}
# And the items route has disappeared?
```
Basically, we've added and removed imports depending on their use.
We've introduced to new features, namely support for _templates_ and _static files_.
The index function has gotten a new annotation, that "links" it to a template file.
And we've removed the items route.
As always, press `Esc` to ext insert-mode, and :w to save.
Now come the hard part, the need to changes files.
The easy way, is to simply exit vim, and start it on a new file, that is `:q` and `vim api_router.py`
But for the brave, working with multiple files, or buffers as vim calls them, is bordering on the advanced.
\ No newline at end of file
Clone repository
  • Part 1a. My first service
  • Part 1b. Testing my first service
  • Part 2a. Extending my first service
  • Part 2b. Organise my first service
  • Part 3a. Review my first service
  • Part 3b. Connecting my first service
  • Home