Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Creating First REST API with FastAPI

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

FastAPI :
FastAPI is modern Web Framework . It is used for building API and is very easy to learn .

Features of FastAPI :

  • High Performance than many Web Frameworks, faster than Node.js, etc .
  • Easy to Develop API’s
  • Production Ready
  • Well Documentation to learn code fast
  • Swagger UI to form API Documentation
  • Avoid Redundancy of Code
  • Easy Testing
  • Support for GraphQL, Background Fetching, Dependency Injection

CREATING REST API USING FastAPI :

  • Install Python 3 and pip/pip3 according to your Operating System
  • Now, install fastapi using pip or pip3 :

       pip install fastapi
    
  • Install the uvicorn which is the Asynchronous Gateway Interface for your Server using :

      pip install uvicorn
    
  • Now create a main.py file and import fastapi, also create a server

      from fastapi import FastAPI
      app = FastAPI()
    
  • Now, let’s add the code for sample get request as shown below :

     @app.get("/")
     def read_root():
        return {"Hello": "World"}
    
  • Hence, the main.py file will look like :




    from fastapi import FastAPI
    app = FastAPI()
     
    @app.get("/")
    def first_example():
        """
           GFG Example First Fast API Example 
        """
       return {"GFG Example": "FastAPI"}

  • Now, start the server using

    uvicorn main:app --reload
    
  • Now open the browser and open http://localhost:8000/docs or http://127.0.0.1:8000/docs
    You will be able to see the Swagger UI Home page as below :
    Swagger UI
  • Expand the “First Example” :
    Expanded Swagger UI
  • Now try to Execute the API, you will get the success status with 200 code .
    The Response will be {“GFG Example”: “FastAPI”} as shown below :
    First Example API Execution
My Personal Notes arrow_drop_up
Last Updated : 05 Sep, 2020
Like Article
Save Article
Similar Reads
Related Tutorials